switchyard_libsy/algorithms/advisor_gate.rs
1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Executor gated by a once-per-session advisor review.
5//!
6//! The executor answers every client-visible turn. Turns with tool calls pass
7//! through unreviewed; the first *terminal* turn — no tool calls (or a text
8//! match under the `pattern` trigger) — is buffered and shown to a stronger
9//! advisor model together with the full transcript. `APPROVE` releases the
10//! buffered turn unchanged; `REDO` appends the discarded turn's text and the
11//! advisor's plan as feedback, then re-invokes the executor so it keeps
12//! working. Each budget scope (one benchmark evaluation, one session, or the
13//! whole instance — see [`budget::budget_scope`]) is reviewed at most
14//! `max_reviews` times; afterwards every call is a pure passthrough.
15//!
16//! This design is a near-superset of solo executor behavior: identical until
17//! the executor first claims to be done, plus one quality gate that catches
18//! premature convergence. Front-loading advice was measured to suppress the
19//! executor's own test-and-iterate loop, so no advice is injected up front.
20//!
21//! Failure posture: executor errors always propagate (including
22//! `ContextWindowExceeded`, which hosts map to a client-visible 400 so agent
23//! harnesses can compact). Advisor errors honor `fail_open` — the buffered
24//! turn passes through as an implicit APPROVE — refund the consumed review,
25//! and count toward a per-scope failure cap that stops consulting a down
26//! advisor entirely.
27//!
28//! Structure: [`AdvisorGate`] is a thin orchestrator — the [`signals`]
29//! processor folds each event's facts into per-turn state, the [`trigger`]
30//! classifier reads them after the executor call, and the [`budget`] ledger
31//! holds the only mutable state.
32
33use std::sync::Arc;
34use std::time::Instant;
35
36use switchyard_protocol::{
37 ContentBlock, InstructionBlock, LlmRequest, Message, ModelId, OutputParams, Request, Role,
38 SamplingParams,
39};
40
41use crate::core::algorithm::{Algorithm, Driver, RoutingOutcome};
42use crate::core::processor::{Event, Processor};
43use crate::{LibsyError, Result};
44
45mod budget;
46mod signals;
47mod telemetry;
48#[cfg(test)]
49mod tests;
50mod transcript;
51mod trigger;
52mod turn;
53
54use budget::{ReviewBudget, ScopeKey, budget_scope, stall_key};
55use signals::{GateSignalProcessor, GateSignals};
56use telemetry::{
57 ReviewAudit, emit_discarded_audit, emit_review_audit, record_consult_failure, record_discarded,
58 record_review,
59};
60use transcript::{VERDICT_PATTERN, Verdict, advisor_reply_text, parse_verdict, review_transcript};
61use trigger::TriggerClassifier;
62#[cfg(test)]
63use turn::has_tool_use;
64use turn::{GatedTurn, buffer_turn, reasoning_text, visible_text};
65
66/// APPROVE/REDO reviewer contract sent as the advisor's system prompt.
67pub const REVIEWER_SYSTEM_PROMPT: &str =
68 include_str!("../prompts/advisor-gate/reviewer-system-prompt.md");
69
70/// Prepended to the advisor's REDO plan when it is fed back as a user turn,
71/// instructing the executor to continue rather than stop.
72pub const REDO_FEEDBACK_PREFIX: &str = concat!(
73 include_str!("../prompts/advisor-gate/redo-feedback-prefix.md"),
74 "\n"
75);
76
77/// Labels the executor's internal reasoning when a turn has no visible text,
78/// so the advisor still has evidence to review (reasoning models on vLLM/NIM
79/// can emit turns whose only output is reasoning).
80const REASONING_TAIL_LABEL: &str =
81 "(the executor produced no visible text this turn; its internal reasoning follows)\n";
82/// REDO echo when the discarded turn had neither text nor reasoning; strict
83/// endpoints (Anthropic) reject empty text blocks, so never echo "".
84const EMPTY_ECHO_PLACEHOLDER: &str = "(the executor produced no output this turn)";
85/// Benchmark harnesses stamp every request of one evaluation — sub-agents
86/// included — with this header, so it is the review budget's first-choice
87/// scope: "reviews for *this* task" survives gateways shared by many tasks.
88const BENCH_SESSION_HEADER: &str = "proxy_x_session_id";
89
90/// How the gate decides a buffered executor turn is terminal.
91#[derive(Clone, Debug, PartialEq)]
92pub enum GateTrigger {
93 /// First turn without tool calls (subject to `gate_min_tool_results`).
94 NoToolCall,
95 /// First turn whose visible text matches this regex (searched, not anchored) —
96 /// for text-protocol harnesses where every turn lacks tool calls and
97 /// completion is declared with a textual marker instead.
98 Pattern(String),
99}
100
101/// Gate knobs; defaults mirror the benchmarked Python advisor configuration.
102#[derive(Clone, Debug)]
103pub struct AdvisorGateConfig {
104 /// System prompt for the advisor's review call; states the APPROVE/REDO contract.
105 pub reviewer_system_prompt: String,
106 /// Prepended to the advisor's REDO plan when fed back to the executor.
107 pub redo_feedback_prefix: String,
108 /// What fires the review.
109 pub gate_trigger: GateTrigger,
110 /// Reviews allowed per budget scope. 1 keeps the original once-per-task
111 /// gate; higher values re-review later terminal turns, making the gate a
112 /// sequential best-of-(N+1) with the advisor as judge.
113 pub max_reviews: u32,
114 /// When > 0, additionally review (once per conversation, consuming budget)
115 /// the first request already carrying at least this many assistant turns —
116 /// a mid-task checkpoint for executors that grind without declaring
117 /// completion. 0 disables.
118 pub gate_stall_turns: u32,
119 /// For the `no_tool_call` trigger: only review once the conversation
120 /// carries at least this many tool results, skipping early commentary
121 /// turns on chatty harnesses. 0 reviews from the first terminal turn.
122 pub gate_min_tool_results: u32,
123 /// Cap on the advisor's output per consult.
124 pub advisor_max_tokens: u64,
125 /// Sampling temperature for the consult; `None` omits the field on the wire.
126 pub advisor_temperature: Option<f64>,
127 /// Cap on the serialized transcript handed to the advisor; the middle of
128 /// an over-cap conversation is dropped (task head + recent tail survive).
129 pub transcript_max_chars: usize,
130 /// When true (default), an advisor failure degrades to APPROVE; when
131 /// false, it propagates as the turn's error.
132 pub fail_open: bool,
133}
134
135impl Default for AdvisorGateConfig {
136 fn default() -> Self {
137 Self {
138 reviewer_system_prompt: REVIEWER_SYSTEM_PROMPT.to_string(),
139 redo_feedback_prefix: REDO_FEEDBACK_PREFIX.to_string(),
140 gate_trigger: GateTrigger::NoToolCall,
141 max_reviews: 1,
142 gate_stall_turns: 0,
143 gate_min_tool_results: 0,
144 advisor_max_tokens: 2048,
145 advisor_temperature: None,
146 transcript_max_chars: 200_000,
147 fail_open: true,
148 }
149 }
150}
151
152/// Advisor review gate: executor turns pass through until the first terminal
153/// turn, which a stronger advisor reviews once per scope budget (APPROVE
154/// releases it, REDO feeds the plan back and re-invokes the executor).
155pub struct AdvisorGate {
156 executor: ModelId,
157 advisor: ModelId,
158 config: AdvisorGateConfig,
159 /// Folds request- and response-side facts into the per-turn [`GateSignals`].
160 signals: GateSignalProcessor,
161 /// Decides, from the signals, whether the buffered turn warrants review.
162 trigger: TriggerClassifier,
163 /// Reserve/refund review ledger and stall latch — the gate's only mutable state.
164 budget: ReviewBudget,
165 verdict_re: regex::Regex,
166}
167
168impl AdvisorGate {
169 /// Validates ranges and compiles the trigger and verdict patterns.
170 pub fn new(executor: ModelId, advisor: ModelId, config: AdvisorGateConfig) -> Result<Self> {
171 if config.max_reviews < 1 {
172 return Err(algorithm_error("max_reviews must be at least 1"));
173 }
174 if config.advisor_max_tokens < 1 {
175 return Err(algorithm_error("advisor_max_tokens must be at least 1"));
176 }
177 if config.transcript_max_chars < 256 {
178 return Err(algorithm_error("transcript_max_chars must be at least 256"));
179 }
180 let trigger = TriggerClassifier::new(&config)?;
181 let verdict_re = regex::Regex::new(VERDICT_PATTERN).map_err(|error| {
182 algorithm_error(format!("verdict pattern failed to compile: {error}"))
183 })?;
184 let budget = ReviewBudget::new(config.max_reviews);
185 Ok(Self {
186 executor,
187 advisor,
188 config,
189 signals: GateSignalProcessor,
190 trigger,
191 budget,
192 verdict_re,
193 })
194 }
195
196 // ── Gate flow ───────────────────────────────────────────────────────────
197
198 async fn route_inner(
199 &self,
200 driver: &Driver,
201 request: Request,
202 scope: &ScopeKey,
203 ) -> Result<RoutingOutcome> {
204 // Spent budget (or failure cap): pure passthrough — live stream,
205 // verbatim preserved-body replay, zero buffering. Executor errors
206 // (including ContextWindowExceeded) propagate for the host's
207 // client-visible mapping.
208 if self.budget.check_exhausted(scope) {
209 return Ok(RoutingOutcome::route_to(
210 self.executor.clone(),
211 Vec::new(),
212 request,
213 ));
214 }
215
216 // Request-side signals fold in before the executor runs.
217 let mut request = request;
218 let mut signals = GateSignals::default();
219 self.signals
220 .process(
221 &mut signals,
222 Event::Request {
223 request: &mut request,
224 driver: Some(driver),
225 },
226 )
227 .await?;
228
229 // Gated phase: generate the turn once, fully buffered, so the gate
230 // can inspect it before the client sees anything.
231 let response = driver
232 .call_model(request.clone(), vec![self.executor.clone()])
233 .await?;
234 let turn = buffer_turn(self.executor.as_str(), response).await?;
235
236 // Response-side signals fold in after it: the terminal turn never
237 // appears on a later request, so the trigger runs on this event.
238 self.signals
239 .process(&mut signals, Event::ModelResponse(&turn.agg))
240 .await?;
241
242 let decision = self.trigger.classify(&signals);
243 // The stall checkpoint fires once per conversation regardless of the
244 // turn's shape. Only a stall with no simultaneous trigger latches
245 // (atomically — one winner per conversation), so a refunded review
246 // leaves the checkpoint re-armed.
247 let stall = decision.fired.is_none()
248 && decision.stalled
249 && self.budget.try_mark_stall_fired(stall_key(&request));
250 if decision.fired.is_none() && !stall {
251 return Ok(RoutingOutcome::answered(
252 self.executor.clone(),
253 request,
254 turn.into_response(),
255 ));
256 }
257 if !self.budget.try_reserve(scope) {
258 return Ok(RoutingOutcome::answered(
259 self.executor.clone(),
260 request,
261 turn.into_response(),
262 ));
263 }
264
265 let trigger_label = decision.fired.unwrap_or("stall");
266 let review_tail = visible_text(&turn.agg).or_else(|| {
267 reasoning_text(&turn.agg).map(|reasoning| format!("{REASONING_TAIL_LABEL}{reasoning}"))
268 });
269 match self
270 .consult(driver, &request, review_tail.as_deref(), trigger_label)
271 .await
272 {
273 Ok(ConsultOutcome::Approve) => {
274 driver.set_evidence(serde_json::json!({
275 "source": "advisor",
276 "verdict": "approve",
277 "trigger": trigger_label,
278 }));
279 Ok(RoutingOutcome::answered(
280 self.executor.clone(),
281 request,
282 turn.into_response(),
283 ))
284 }
285 Ok(ConsultOutcome::Redo { plan }) => {
286 driver.set_evidence(serde_json::json!({
287 "source": "advisor",
288 "verdict": "redo",
289 "trigger": trigger_label,
290 }));
291 Ok(self.redo(request, turn, &plan))
292 }
293 Ok(ConsultOutcome::Failed { reason }) => {
294 self.budget.refund_failure(scope);
295 driver.set_evidence(serde_json::json!({
296 "source": "advisor",
297 "verdict": "fail_open",
298 "trigger": trigger_label,
299 "reason_code": reason,
300 }));
301 Ok(RoutingOutcome::answered(
302 self.executor.clone(),
303 request,
304 turn.into_response(),
305 ))
306 }
307 Err(error) => {
308 self.budget.refund_failure(scope);
309 Err(error)
310 }
311 }
312 }
313
314 /// REDO: the client never sees the gated turn. Its text (or reasoning) is
315 /// echoed as an assistant message, the advisor's plan follows as user
316 /// feedback, and the executor continues as a pure passthrough call.
317 fn redo(&self, request: Request, turn: GatedTurn, plan: &str) -> RoutingOutcome {
318 record_discarded(&turn.agg.usage);
319 emit_discarded_audit(self.executor.as_str(), &turn.agg.usage);
320 let echo = visible_text(&turn.agg)
321 .or_else(|| reasoning_text(&turn.agg))
322 .unwrap_or_else(|| EMPTY_ECHO_PLACEHOLDER.to_string());
323 let mut redo = request;
324 redo.llm_request
325 .messages
326 .push(Message::text(Role::Assistant, echo));
327 redo.llm_request.messages.push(Message::text(
328 Role::User,
329 format!("{}{}", self.config.redo_feedback_prefix, plan),
330 ));
331 // Mandatory after any message mutation: codecs otherwise replay the
332 // preserved pre-surgery body verbatim and the feedback never reaches
333 // the executor.
334 crate::algorithms::util::prompts::drop_exact_replay(&mut redo);
335 RoutingOutcome::route_to(self.executor.clone(), Vec::new(), redo)
336 }
337
338 /// Consults the advisor over the buffered transcript and parses the
339 /// verdict. `Ok(Failed)` covers fail-open errors and unparseable replies
340 /// (the caller refunds); fail-closed errors return `Err`.
341 async fn consult(
342 &self,
343 driver: &Driver,
344 base: &Request,
345 review_tail: Option<&str>,
346 trigger: &'static str,
347 ) -> Result<ConsultOutcome> {
348 // The advisor reviews the FULL transcript: system/developer content is
349 // normalized out of `messages` into `instructions`, so prepend it back
350 // as leading messages (identical {role, content} shape) — the task
351 // constraints the verdict must check against usually live there.
352 let transcript_messages: Vec<Message> = base
353 .llm_request
354 .instructions
355 .iter()
356 .map(|block| Message {
357 role: block.role,
358 content: block.content.clone(),
359 })
360 .chain(base.llm_request.messages.iter().cloned())
361 .collect();
362 let transcript = review_transcript(
363 &transcript_messages,
364 review_tail,
365 self.config.transcript_max_chars,
366 );
367 let consult_request = self.build_consult_request(base, transcript);
368 let started = Instant::now();
369 let reply = match driver
370 .call_model(consult_request, vec![self.advisor.clone()])
371 .await
372 {
373 Ok(response) => response
374 .llm_response
375 .into_agg()
376 .await
377 .map_err(|source| LibsyError::client_call(self.advisor.clone(), source)),
378 Err(error) => Err(error),
379 };
380 let latency_ms = started.elapsed().as_secs_f64() * 1000.0;
381 let agg = match reply {
382 Ok(agg) => agg,
383 Err(error) => {
384 let reason = crate::algorithms::util::llm_judge::libsy_error_reason(&error);
385 record_consult_failure(reason);
386 if !self.config.fail_open {
387 // Surface as an algorithm failure (5xx), never as the
388 // advisor's own client error: a typed ContextWindowExceeded
389 // from the consult would otherwise reach the client as 400
390 // context_length_exceeded and trigger compaction of a
391 // healthy conversation.
392 return Err(algorithm_error(format!(
393 "advisor consult failed (fail_open = false): {error}"
394 )));
395 }
396 tracing::warn!(
397 target: "libsy",
398 error = %error,
399 "advisor gate: consult failed; passing the turn through (fail open)"
400 );
401 emit_review_audit(ReviewAudit {
402 verdict: "APPROVE",
403 error: Some(error.to_string()),
404 latency_ms,
405 reply_head: None,
406 usage: None,
407 });
408 return Ok(ConsultOutcome::Failed { reason });
409 }
410 };
411 let reply_text = advisor_reply_text(&agg);
412 let reply_head: String = reply_text.chars().take(160).collect();
413 match parse_verdict(&self.verdict_re, &reply_text) {
414 Some(Verdict::Approve) => {
415 record_review("approve", trigger);
416 emit_review_audit(ReviewAudit {
417 verdict: "APPROVE",
418 error: None,
419 latency_ms,
420 reply_head: Some(reply_head),
421 usage: Some(&agg.usage),
422 });
423 Ok(ConsultOutcome::Approve)
424 }
425 Some(Verdict::Redo { plan }) => {
426 record_review("redo", trigger);
427 emit_review_audit(ReviewAudit {
428 verdict: "REDO",
429 error: None,
430 latency_ms,
431 reply_head: Some(reply_head),
432 usage: Some(&agg.usage),
433 });
434 Ok(ConsultOutcome::Redo { plan })
435 }
436 None => {
437 // The advisor spent real tokens on a reply the gate cannot
438 // act on; the observer already recorded them. Refunded by
439 // the caller so a flaky advisor cannot burn the budget.
440 record_review("unparseable", trigger);
441 emit_review_audit(ReviewAudit {
442 verdict: "UNPARSEABLE",
443 error: None,
444 latency_ms,
445 reply_head: Some(reply_head),
446 usage: Some(&agg.usage),
447 });
448 Ok(ConsultOutcome::Failed {
449 reason: "parse_error",
450 })
451 }
452 }
453 }
454
455 /// A fresh, buffered, tool-free request carrying the reviewer contract and
456 /// the serialized transcript; metadata is kept for session correlation.
457 fn build_consult_request(&self, base: &Request, transcript: String) -> Request {
458 Request {
459 llm_request: LlmRequest {
460 model: base.llm_request.model.clone(),
461 instructions: vec![InstructionBlock {
462 role: Role::System,
463 content: vec![ContentBlock::Text {
464 text: self.config.reviewer_system_prompt.clone(),
465 }],
466 }],
467 messages: vec![Message::text(Role::User, transcript)],
468 sampling: SamplingParams {
469 temperature: self.config.advisor_temperature,
470 ..SamplingParams::default()
471 },
472 output: OutputParams {
473 max_output_tokens: Some(self.config.advisor_max_tokens),
474 response_format: None,
475 },
476 ..LlmRequest::default()
477 },
478 raw_request: None,
479 metadata: base.metadata.clone(),
480 }
481 }
482}
483
484#[async_trait::async_trait]
485impl Algorithm for AdvisorGate {
486 fn name(&self) -> &str {
487 "advisor_gate"
488 }
489
490 async fn route(self: Arc<Self>, driver: Driver, request: Request) -> Result<RoutingOutcome> {
491 let scope = budget_scope(&request);
492 let session_final = request
493 .metadata
494 .as_ref()
495 .and_then(|metadata| metadata.session_final)
496 == Some(true);
497 let result = self.route_inner(&driver, request, &scope).await;
498 if session_final {
499 self.budget.evict_scope(&scope);
500 }
501 result
502 }
503}
504
505/// Outcome of one consult; `Failed` = fail-open error or unparseable reply.
506enum ConsultOutcome {
507 Approve,
508 Redo { plan: String },
509 Failed { reason: &'static str },
510}
511
512fn algorithm_error(message: impl Into<String>) -> LibsyError {
513 LibsyError::AlgorithmError {
514 message: message.into(),
515 }
516}