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) => Ok(RoutingOutcome::answered(
274 self.executor.clone(),
275 request,
276 turn.into_response(),
277 )),
278 Ok(ConsultOutcome::Redo { plan }) => Ok(self.redo(request, turn, &plan)),
279 Ok(ConsultOutcome::Failed) => {
280 self.budget.refund_failure(scope);
281 Ok(RoutingOutcome::answered(
282 self.executor.clone(),
283 request,
284 turn.into_response(),
285 ))
286 }
287 Err(error) => {
288 self.budget.refund_failure(scope);
289 Err(error)
290 }
291 }
292 }
293
294 /// REDO: the client never sees the gated turn. Its text (or reasoning) is
295 /// echoed as an assistant message, the advisor's plan follows as user
296 /// feedback, and the executor continues as a pure passthrough call.
297 fn redo(&self, request: Request, turn: GatedTurn, plan: &str) -> RoutingOutcome {
298 record_discarded(&turn.agg.usage);
299 emit_discarded_audit(self.executor.as_str(), &turn.agg.usage);
300 let echo = visible_text(&turn.agg)
301 .or_else(|| reasoning_text(&turn.agg))
302 .unwrap_or_else(|| EMPTY_ECHO_PLACEHOLDER.to_string());
303 let mut redo = request;
304 redo.llm_request
305 .messages
306 .push(Message::text(Role::Assistant, echo));
307 redo.llm_request.messages.push(Message::text(
308 Role::User,
309 format!("{}{}", self.config.redo_feedback_prefix, plan),
310 ));
311 // Mandatory after any message mutation: codecs otherwise replay the
312 // preserved pre-surgery body verbatim and the feedback never reaches
313 // the executor.
314 crate::algorithms::util::prompts::drop_exact_replay(&mut redo);
315 RoutingOutcome::route_to(self.executor.clone(), Vec::new(), redo)
316 }
317
318 /// Consults the advisor over the buffered transcript and parses the
319 /// verdict. `Ok(Failed)` covers fail-open errors and unparseable replies
320 /// (the caller refunds); fail-closed errors return `Err`.
321 async fn consult(
322 &self,
323 driver: &Driver,
324 base: &Request,
325 review_tail: Option<&str>,
326 trigger: &'static str,
327 ) -> Result<ConsultOutcome> {
328 // The advisor reviews the FULL transcript: system/developer content is
329 // normalized out of `messages` into `instructions`, so prepend it back
330 // as leading messages (identical {role, content} shape) — the task
331 // constraints the verdict must check against usually live there.
332 let transcript_messages: Vec<Message> = base
333 .llm_request
334 .instructions
335 .iter()
336 .map(|block| Message {
337 role: block.role,
338 content: block.content.clone(),
339 })
340 .chain(base.llm_request.messages.iter().cloned())
341 .collect();
342 let transcript = review_transcript(
343 &transcript_messages,
344 review_tail,
345 self.config.transcript_max_chars,
346 );
347 let consult_request = self.build_consult_request(base, transcript);
348 let started = Instant::now();
349 let reply = match driver
350 .call_model(consult_request, vec![self.advisor.clone()])
351 .await
352 {
353 Ok(response) => response
354 .llm_response
355 .into_agg()
356 .await
357 .map_err(|source| LibsyError::client_call(self.advisor.clone(), source)),
358 Err(error) => Err(error),
359 };
360 let latency_ms = started.elapsed().as_secs_f64() * 1000.0;
361 let agg = match reply {
362 Ok(agg) => agg,
363 Err(error) => {
364 record_consult_failure(crate::algorithms::util::llm_judge::libsy_error_reason(
365 &error,
366 ));
367 if !self.config.fail_open {
368 // Surface as an algorithm failure (5xx), never as the
369 // advisor's own client error: a typed ContextWindowExceeded
370 // from the consult would otherwise reach the client as 400
371 // context_length_exceeded and trigger compaction of a
372 // healthy conversation.
373 return Err(algorithm_error(format!(
374 "advisor consult failed (fail_open = false): {error}"
375 )));
376 }
377 tracing::warn!(
378 target: "libsy",
379 error = %error,
380 "advisor gate: consult failed; passing the turn through (fail open)"
381 );
382 emit_review_audit(ReviewAudit {
383 verdict: "APPROVE",
384 error: Some(error.to_string()),
385 latency_ms,
386 reply_head: None,
387 usage: None,
388 });
389 return Ok(ConsultOutcome::Failed);
390 }
391 };
392 let reply_text = advisor_reply_text(&agg);
393 let reply_head: String = reply_text.chars().take(160).collect();
394 match parse_verdict(&self.verdict_re, &reply_text) {
395 Some(Verdict::Approve) => {
396 record_review("approve", trigger);
397 emit_review_audit(ReviewAudit {
398 verdict: "APPROVE",
399 error: None,
400 latency_ms,
401 reply_head: Some(reply_head),
402 usage: Some(&agg.usage),
403 });
404 Ok(ConsultOutcome::Approve)
405 }
406 Some(Verdict::Redo { plan }) => {
407 record_review("redo", trigger);
408 emit_review_audit(ReviewAudit {
409 verdict: "REDO",
410 error: None,
411 latency_ms,
412 reply_head: Some(reply_head),
413 usage: Some(&agg.usage),
414 });
415 Ok(ConsultOutcome::Redo { plan })
416 }
417 None => {
418 // The advisor spent real tokens on a reply the gate cannot
419 // act on; the observer already recorded them. Refunded by
420 // the caller so a flaky advisor cannot burn the budget.
421 record_review("unparseable", trigger);
422 emit_review_audit(ReviewAudit {
423 verdict: "UNPARSEABLE",
424 error: None,
425 latency_ms,
426 reply_head: Some(reply_head),
427 usage: Some(&agg.usage),
428 });
429 Ok(ConsultOutcome::Failed)
430 }
431 }
432 }
433
434 /// A fresh, buffered, tool-free request carrying the reviewer contract and
435 /// the serialized transcript; metadata is kept for session correlation.
436 fn build_consult_request(&self, base: &Request, transcript: String) -> Request {
437 Request {
438 llm_request: LlmRequest {
439 model: base.llm_request.model.clone(),
440 instructions: vec![InstructionBlock {
441 role: Role::System,
442 content: vec![ContentBlock::Text {
443 text: self.config.reviewer_system_prompt.clone(),
444 }],
445 }],
446 messages: vec![Message::text(Role::User, transcript)],
447 sampling: SamplingParams {
448 temperature: self.config.advisor_temperature,
449 ..SamplingParams::default()
450 },
451 output: OutputParams {
452 max_output_tokens: Some(self.config.advisor_max_tokens),
453 response_format: None,
454 },
455 ..LlmRequest::default()
456 },
457 raw_request: None,
458 metadata: base.metadata.clone(),
459 }
460 }
461}
462
463#[async_trait::async_trait]
464impl Algorithm for AdvisorGate {
465 fn name(&self) -> &str {
466 "advisor_gate"
467 }
468
469 async fn route(self: Arc<Self>, driver: Driver, request: Request) -> Result<RoutingOutcome> {
470 let scope = budget_scope(&request);
471 let session_final = request
472 .metadata
473 .as_ref()
474 .and_then(|metadata| metadata.session_final)
475 == Some(true);
476 let result = self.route_inner(&driver, request, &scope).await;
477 if session_final {
478 self.budget.evict_scope(&scope);
479 }
480 result
481 }
482}
483
484/// Outcome of one consult; `Failed` = fail-open error or unparseable reply.
485enum ConsultOutcome {
486 Approve,
487 Redo { plan: String },
488 Failed,
489}
490
491fn algorithm_error(message: impl Into<String>) -> LibsyError {
492 LibsyError::AlgorithmError {
493 message: message.into(),
494 }
495}