Skip to main content

switchyard_libsy/algorithms/
llm_class.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Judge-backed capability, escalation, and custom-policy routing.
5
6use std::collections::HashSet;
7use std::sync::Arc;
8
9use async_trait::async_trait;
10use serde::{Deserialize, Deserializer};
11use serde_json::Value;
12use switchyard_protocol::{Category, ContentBlock, Message, Role};
13
14mod decision;
15pub use decision::{DecisionChoice, DecisionJudgeConfig, DirectClassifierConfig};
16use decision::{DecisionClassifier, DirectClassifier};
17
18use super::escalation;
19use super::fall_through::FallThrough;
20use super::util::DEFAULT_JUDGE_MAX_OUTPUT_TOKENS;
21use super::util::affinity::{AffinityRouter, ClassifyTrigger, is_user_turn};
22use super::util::classifier_contract::{
23    ClassifierContract, ClassifierContractConfig, ClassifierResponseFormat,
24};
25use super::util::escalation::EscalationJudgeConfig;
26use super::util::llm_judge::{
27    ClassifierInput, JsonSchemaDecoder, JudgeClassifier, JudgePolicy, JudgeRuntimeConfig,
28    SerdeDecoder, StructuredJudge,
29};
30use super::util::target_selector::TargetSelectorPolicy;
31use crate::core::algorithm::{Algorithm, Driver};
32use crate::core::classifier::{Classification, Classifier, Score};
33use crate::core::state::State;
34use crate::{LibsyError, Result};
35use switchyard_protocol::{Request, Response};
36
37const PROMPT_TEMPLATE: &str = include_str!("../prompts/capability-classifier/prompt.md");
38const SCHEMA_TEMPLATE: &str = include_str!("../prompts/capability-classifier/schema.json");
39/// Telemetry label for this algorithm's spans, metrics, and logs.
40const ALGORITHM_NAME: &str = "llm_task_classifier";
41
42/// Restates the task after the conversation the judge is asked to route.
43///
44/// The rubric leads the request, which works while the payload is a single short
45/// message. Once `recent_turn_window` includes real conversation, those instructions
46/// sit far from the generation point and the judge sometimes *answers* the
47/// conversation instead of classifying it — the reply then fails to parse, the
48/// verdict is unavailable, and the turn silently falls back. Repeating the task at
49/// the end is what reliably prevents that.
50const TRAILING_ROUTING_INSTRUCTION: &str =
51    "Route the conversation above. Output ONLY the routing JSON object, nothing else.";
52
53#[derive(Deserialize)]
54#[serde(deny_unknown_fields)]
55struct TaskClassifierVerdict {
56    crux: String,
57    primary_rule: String,
58    capability_boundary: String,
59    p_solve: f64,
60}
61
62impl TaskClassifierVerdict {
63    /// Rejects malformed or internally inconsistent verdicts before policy evaluation.
64    fn is_valid(&self) -> bool {
65        (0.0..=1.0).contains(&self.p_solve)
66            && !self.crux.trim().is_empty()
67            && matches!(
68                (
69                    self.primary_rule.as_str(),
70                    self.capability_boundary.as_str()
71                ),
72                ("SUP-1" | "SUP-2" | "SUP-3" | "SUP-4" | "SUP-5", "supported")
73                    | ("UNC-1" | "UNC-2", "uncertain")
74                    | ("LIM-1" | "LIM-2", "unsupported")
75                    | ("none", "unmatched")
76            )
77    }
78
79    /// Returns the number of threshold steps assigned to this capability boundary.
80    ///
81    /// `unmatched_steps` comes from the route configuration: a request that matches no
82    /// capability rule has no evidence behind its solve probability, so operators can
83    /// require more confidence for it than for an uncertain verdict.
84    fn boundary_steps(&self, unmatched_steps: u8) -> Option<u8> {
85        match self.capability_boundary.as_str() {
86            "supported" => Some(0),
87            "uncertain" => Some(1),
88            "unmatched" => Some(unmatched_steps),
89            "unsupported" => Some(2),
90            _ => None,
91        }
92    }
93}
94
95/// Keeps the opening task and the last `recent_turn_window` turns after it. A
96/// window of `0` keeps the task alone.
97///
98/// Inline system and developer messages are kept, in their original order,
99/// ahead of the task.
100///
101/// Selects by reference and clones only what survives — a coding-agent
102/// conversation carries every tool result, so cloning it whole to keep a window
103/// would copy the transcript on each judged turn.
104fn trim_messages(messages: &[Message], recent_turn_window: usize) -> Vec<Message> {
105    let is_instruction = |message: &Message| matches!(message.role, Role::System | Role::Developer);
106    let mut kept: Vec<&Message> = messages.iter().filter(|m| is_instruction(m)).collect();
107    let Some(task) = messages.iter().position(is_user_turn) else {
108        return kept.into_iter().cloned().collect();
109    };
110    kept.push(&messages[task]);
111
112    let tail: Vec<&Message> = messages[task + 1..]
113        .iter()
114        .filter(|m| !is_instruction(m))
115        .collect();
116    kept.extend(&tail[window_start(&tail, recent_turn_window)..]);
117    kept.into_iter().cloned().collect()
118}
119
120/// The first index of the trailing window.
121///
122/// Counting messages alone can start the window between an assistant tool call and the
123/// result answering it, leaving the judge a result whose call id was never introduced. The
124/// start therefore moves back to the nearest one that keeps every tool pair whole.
125///
126/// One newest-to-oldest pass carries the ids still waiting for a call. Direction is what
127/// makes it correct: ids repeat across a conversation, and in this order a call is only
128/// ever seen after the results it could answer, so a later call — already passed — clears
129/// nothing. A result whose call sits before the opening task, which trimming never reaches,
130/// keeps the set non-empty to the end and falls back to the counted start, so an unpairable
131/// result costs one pass and cannot widen the window to the whole conversation.
132fn window_start(tail: &[&Message], recent_turn_window: usize) -> usize {
133    let counted = tail.len().saturating_sub(recent_turn_window);
134    // An empty window holds no result to pair, and the loop below never visits its start.
135    if counted == tail.len() {
136        return counted;
137    }
138    let mut unpaired: HashSet<&str> = HashSet::new();
139    for (start, message) in tail.iter().enumerate().rev() {
140        // Blocks reverse too, so a call answers a result only when it precedes it inside
141        // one message as well as across messages.
142        for block in message.content.iter().rev() {
143            match block {
144                ContentBlock::ToolResult(result) => {
145                    unpaired.insert(result.tool_call_id.as_str());
146                }
147                ContentBlock::ToolCall(call) => {
148                    unpaired.remove(call.id.as_str());
149                }
150                _ => {}
151            }
152        }
153        if start <= counted && unpaired.is_empty() {
154            return start;
155        }
156    }
157    counted
158}
159
160/// Keeps the opening task and the latest user follow-up when they differ.
161fn task_messages(messages: &[Message]) -> Vec<Message> {
162    // Decoders also use the user role for tool results. Select ordinary user content
163    // first, so a tool result cannot replace the opening task or latest follow-up.
164    let is_task_content = |block: &ContentBlock| {
165        !matches!(
166            block,
167            ContentBlock::ToolCall(_)
168                | ContentBlock::ToolResult(_)
169                | ContentBlock::Reasoning { .. }
170        )
171    };
172    let mut user_messages = messages
173        .iter()
174        .filter(|message| is_user_turn(message) && message.content.iter().any(is_task_content));
175    let Some(opening_task) = user_messages.next() else {
176        return Vec::new();
177    };
178    [Some(opening_task), user_messages.next_back()]
179        .into_iter()
180        .flatten()
181        .map(|message| {
182            Message::new(
183                Role::User,
184                message
185                    .content
186                    .iter()
187                    .filter(|block| is_task_content(block))
188                    .cloned()
189                    .collect(),
190            )
191        })
192        .collect()
193}
194
195/// Selects the task messages shown to capability and custom-schema classifiers.
196struct TaskInput {
197    recent_turn_window: Option<usize>,
198}
199
200impl TaskInput {
201    /// Selects conversation content without adding judge instructions.
202    fn messages(&self, request: &Request) -> Vec<Message> {
203        // The default preserves the whole-task anchor and latest user update. A
204        // configured window widens that to the surrounding conversation.
205        let mut messages = match self.recent_turn_window {
206            Some(window) => trim_messages(&request.llm_request.messages, window),
207            None => task_messages(&request.llm_request.messages),
208        };
209        // Reasoning is provider-private and not required to classify the task. Some
210        // upstreams also reject an unsigned reasoning item replayed without the
211        // opaque state it was issued with, so it cannot travel through a windowed
212        // classifier request as ordinary history. Empty text goes with it: OpenAI
213        // Chat decoding leaves an empty text placeholder beside the reasoning of a
214        // reasoning-only turn, and an Anthropic judge rejects a message whose text
215        // block is empty.
216        for message in &mut messages {
217            message.content.retain(|block| match block {
218                ContentBlock::Reasoning { .. } => false,
219                ContentBlock::Text { text } => !text.is_empty(),
220                _ => true,
221            });
222        }
223        messages.retain(|message| !message.content.is_empty());
224        messages
225    }
226}
227
228impl ClassifierInput for TaskInput {
229    fn build_messages(&self, _state: &State, request: &Request) -> Vec<Message> {
230        let mut messages = self.messages(request);
231        // Only the windowed path carries assistant turns and tool traffic for the judge
232        // to be distracted by. The default path is user task messages only — the anchor
233        // and the latest follow-up — so there is nothing there to outrank.
234        if self.recent_turn_window.is_some() {
235            messages.push(Message::text(
236                Role::User,
237                TRAILING_ROUTING_INSTRUCTION.to_string(),
238            ));
239        }
240        messages
241    }
242}
243
244struct TaskClassifierPolicy {
245    base_threshold: f64,
246    threshold_step: f64,
247    unmatched_steps: u8,
248}
249
250impl TaskClassifierPolicy {
251    fn new(config: &LlmCapabilityConfig) -> Self {
252        Self {
253            base_threshold: config.base_threshold,
254            threshold_step: config.threshold_step,
255            unmatched_steps: config.unmatched_steps,
256        }
257    }
258
259    /// Returns the required solve probability for one validated verdict.
260    fn threshold(&self, verdict: &TaskClassifierVerdict) -> Option<f64> {
261        let steps = verdict.boundary_steps(self.unmatched_steps)?;
262        Some(self.base_threshold + f64::from(steps) * self.threshold_step)
263    }
264}
265
266impl JudgePolicy for TaskClassifierPolicy {
267    type Verdict = TaskClassifierVerdict;
268
269    fn to_classification(
270        &self,
271        verdict: Option<&Self::Verdict>,
272        driver: &Driver,
273    ) -> Result<Classification> {
274        // Judge output is untrusted. An absent, invalid, or inconsistent verdict is
275        // ambiguous so the surrounding router applies its configured fallback.
276        let Some(verdict) = verdict.filter(|verdict| verdict.is_valid()) else {
277            return Ok(Classification::Ambiguous(vec![]));
278        };
279        // A usable verdict below the capability threshold is still a decision: the judge
280        // does not trust the efficient tier with this task.
281        let Some(threshold) = self.threshold(verdict) else {
282            return Ok(Classification::Ambiguous(vec![]));
283        };
284        let category = if verdict.p_solve >= threshold
285            || (threshold - verdict.p_solve).abs() <= f64::EPSILON
286        {
287            Category::Efficient
288        } else {
289            Category::Capable
290        };
291        // The chosen category may have no models configured. That is ambiguous, not an
292        // error, so the surrounding router applies its configured fallback.
293        let Some(target) = driver.models_for(&category).first().cloned() else {
294            return Ok(Classification::Ambiguous(vec![]));
295        };
296        Ok(Classification::Scores(vec![Score {
297            target,
298            confidence: 1.0,
299            category: Some(category),
300        }]))
301    }
302}
303
304/// Maps valid verdicts to scores, invalid verdicts to a reason, and leaves absent verdicts alone.
305fn capability_evidence(
306    policy: &TaskClassifierPolicy,
307    verdict: Option<&TaskClassifierVerdict>,
308) -> Option<Value> {
309    let verdict = verdict?;
310    let Some(threshold) = verdict
311        .is_valid()
312        .then(|| policy.threshold(verdict))
313        .flatten()
314    else {
315        return Some(serde_json::json!({
316            "source": "fail_open",
317            "reason_code": "invalid_verdict",
318        }));
319    };
320    Some(serde_json::json!({
321        "source": "llm-classifier",
322        "score": verdict.p_solve,
323        "threshold": threshold,
324    }))
325}
326
327/// Settings shared by capability judges and their surrounding route.
328#[derive(Clone, Debug)]
329pub struct TaskClassifierConfig {
330    /// The judge's prediction contract and routing policy.
331    pub judge: CapabilityJudgeConfig,
332    /// Routes to the capable tier on judge client failures and deadlines. Defaults to true.
333    pub fail_open: bool,
334    /// How often the classifier re-decides this session's target.
335    pub classify_trigger: ClassifyTrigger,
336    /// Uses the first user message as the SessionKey for sticky routing when session metadata is unavailable.
337    pub message_hash_fallback: bool,
338    /// `None` judges the opening task and latest user follow-up. `Some(n)` also
339    /// includes the surrounding conversation using the last `n` turns.
340    pub recent_turn_window: Option<usize>,
341}
342
343/// Selects how a capability judge obtains and interprets its prediction.
344#[derive(Clone, Debug)]
345pub enum CapabilityJudgeConfig {
346    /// A structured LLM verdict with a solve probability and capability boundary.
347    Llm(LlmCapabilityConfig),
348    /// A Choice score for the capable candidate succeeding where the efficient one fails.
349    Decision(DecisionJudgeConfig),
350}
351
352impl Default for CapabilityJudgeConfig {
353    fn default() -> Self {
354        Self::Llm(LlmCapabilityConfig::default())
355    }
356}
357
358/// Prompt, output, and solve-probability settings for an LLM capability judge.
359#[derive(Clone, Debug)]
360pub struct LlmCapabilityConfig {
361    /// Lowest solve probability that routes a supported task to the efficient target.
362    pub base_threshold: f64,
363    /// Amount added per capability-boundary step: zero for supported, one for
364    /// uncertain, `unmatched_steps` for unmatched, and two for unsupported.
365    pub threshold_step: f64,
366    /// Threshold steps applied to an unmatched verdict (no capability rule applies).
367    ///
368    /// Defaults to 1, the same as an uncertain verdict. 2 treats it like unsupported.
369    pub unmatched_steps: u8,
370    /// Prompt and verdict contract settings for the classifier judge.
371    pub contract: ClassifierContractConfig,
372    /// Maximum completion tokens available to the classifier verdict.
373    pub max_output_tokens: u64,
374    /// Whole-consultation bound on the judge call, in milliseconds. Covers the model
375    /// call and the response drain; on expiry the judge is treated as unavailable and
376    /// follows the route's `fail_open` setting. `None` is unbounded.
377    pub judge_deadline_ms: Option<u64>,
378}
379
380impl Default for LlmCapabilityConfig {
381    fn default() -> Self {
382        Self {
383            base_threshold: 0.0,
384            threshold_step: 0.0,
385            unmatched_steps: DEFAULT_UNMATCHED_STEPS,
386            contract: ClassifierContractConfig::default(),
387            max_output_tokens: DEFAULT_JUDGE_MAX_OUTPUT_TOKENS,
388            judge_deadline_ms: None,
389        }
390    }
391}
392
393/// Flat serialized shape that maps prompt settings into the runtime contract.
394#[derive(Deserialize)]
395#[serde(deny_unknown_fields)]
396struct TaskClassifierConfigWire {
397    base_threshold: f64,
398    #[serde(default = "default_fail_open")]
399    fail_open: bool,
400    #[serde(default)]
401    threshold_step: f64,
402    #[serde(default = "default_unmatched_steps")]
403    unmatched_steps: u8,
404    #[serde(default)]
405    classify_trigger: ClassifyTrigger,
406    #[serde(default)]
407    message_hash_fallback: bool,
408    #[serde(default)]
409    recent_turn_window: Option<usize>,
410    #[serde(default)]
411    prompt: Option<String>,
412    #[serde(default)]
413    response_format_type: ClassifierResponseFormat,
414    #[serde(default = "default_judge_max_output_tokens")]
415    max_output_tokens: u64,
416    #[serde(default)]
417    judge_deadline_ms: Option<u64>,
418}
419
420impl<'de> Deserialize<'de> for TaskClassifierConfig {
421    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
422    where
423        D: Deserializer<'de>,
424    {
425        let wire = TaskClassifierConfigWire::deserialize(deserializer)?;
426        let mut contract = ClassifierContractConfig::default();
427        if let Some(prompt) = wire.prompt {
428            contract = contract.with_prompt(prompt);
429        }
430        contract = contract.with_response_format_type(wire.response_format_type);
431        Ok(Self {
432            judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig {
433                base_threshold: wire.base_threshold,
434                threshold_step: wire.threshold_step,
435                unmatched_steps: wire.unmatched_steps,
436                contract,
437                max_output_tokens: wire.max_output_tokens,
438                judge_deadline_ms: wire.judge_deadline_ms,
439            }),
440            fail_open: wire.fail_open,
441            classify_trigger: wire.classify_trigger,
442            message_hash_fallback: wire.message_hash_fallback,
443            recent_turn_window: wire.recent_turn_window,
444        })
445    }
446}
447
448const fn default_fail_open() -> bool {
449    true
450}
451
452/// Unmatched verdicts share the uncertain step unless the route says otherwise.
453pub const DEFAULT_UNMATCHED_STEPS: u8 = 1;
454
455const fn default_unmatched_steps() -> u8 {
456    DEFAULT_UNMATCHED_STEPS
457}
458
459const fn default_judge_max_output_tokens() -> u64 {
460    DEFAULT_JUDGE_MAX_OUTPUT_TOKENS
461}
462
463impl Default for TaskClassifierConfig {
464    fn default() -> Self {
465        Self {
466            judge: CapabilityJudgeConfig::default(),
467            fail_open: default_fail_open(),
468            classify_trigger: ClassifyTrigger::default(),
469            message_hash_fallback: false,
470            recent_turn_window: None,
471        }
472    }
473}
474
475impl LlmCapabilityConfig {
476    fn validate(&self) -> Result<()> {
477        if !(0.0..=1.0).contains(&self.base_threshold) {
478            return Err(LibsyError::AlgorithmError {
479                message: format!(
480                    "base_threshold must be between 0 and 1, got {}",
481                    self.base_threshold
482                ),
483            });
484        }
485        if !self.threshold_step.is_finite() || self.threshold_step < 0.0 {
486            return Err(LibsyError::AlgorithmError {
487                message: format!(
488                    "threshold_step must be finite and greater than or equal to 0, got {}",
489                    self.threshold_step
490                ),
491            });
492        }
493        if self.unmatched_steps > 2 {
494            return Err(LibsyError::AlgorithmError {
495                message: format!(
496                    "unmatched_steps must be 0, 1, or 2, got {}",
497                    self.unmatched_steps
498                ),
499            });
500        }
501        let unsupported_threshold = self.base_threshold + 2.0 * self.threshold_step;
502        if unsupported_threshold > 1.0 && unsupported_threshold - 1.0 > f64::EPSILON {
503            return Err(LibsyError::AlgorithmError {
504                message: format!(
505                    "base_threshold + 2 * threshold_step must be at most 1, got {unsupported_threshold}"
506                ),
507            });
508        }
509        if self.max_output_tokens == 0 {
510            return Err(LibsyError::AlgorithmError {
511                message: "max_output_tokens must be at least 1".to_string(),
512            });
513        }
514        Ok(())
515    }
516}
517
518impl TaskClassifierConfig {
519    fn validate(&self) -> Result<()> {
520        match &self.judge {
521            CapabilityJudgeConfig::Llm(config) => config.validate()?,
522            CapabilityJudgeConfig::Decision(config) => config.validate()?,
523        }
524        // Only `every_request` is rejected: it retains no target, so a fallback identity has nothing to key on. Both retaining triggers can key the retained target on a message hash when the caller sends no session id.
525        if self.message_hash_fallback && self.classify_trigger == ClassifyTrigger::EveryRequest {
526            return Err(LibsyError::AlgorithmError {
527                message:
528                    "message_hash_fallback requires classify_trigger = new_session or user_turn"
529                        .to_string(),
530            });
531        }
532        Ok(())
533    }
534}
535
536/// Policy that maps a custom classifier verdict to a routing target.
537#[derive(Clone, Debug)]
538pub enum CustomClassifierPolicy {
539    /// Resolves a JSON Pointer and treats its string value as a model category.
540    TargetSelector {
541        /// JSON Pointer evaluated against each schema-validated verdict.
542        selector: String,
543    },
544}
545
546impl CustomClassifierPolicy {
547    /// Creates a policy that selects a model category through a JSON Pointer.
548    pub fn target_selector(selector: impl Into<String>) -> Self {
549        Self::TargetSelector {
550            selector: selector.into(),
551        }
552    }
553}
554
555/// Settings for a classifier whose JSON Schema and target-selection policy are user supplied.
556#[derive(Clone, Debug)]
557pub struct CustomClassifierConfig {
558    /// System prompt sent to the classifier judge.
559    pub prompt: String,
560    /// Inner JSON Schema placed inside the provider's structured-output wrapper.
561    pub response_schema: Value,
562    /// Deterministic policy applied after the verdict passes schema validation.
563    pub policy: CustomClassifierPolicy,
564    /// How often the classifier re-decides this session's target.
565    pub classify_trigger: ClassifyTrigger,
566    /// Uses the first user message when session metadata is unavailable.
567    pub message_hash_fallback: bool,
568    /// Trailing conversation turns shown to the classifier judge.
569    pub recent_turn_window: Option<usize>,
570    /// Maximum completion tokens available to the classifier verdict.
571    pub max_output_tokens: u64,
572    /// Whole-consultation bound on the judge call, in milliseconds. `None` is unbounded.
573    pub judge_deadline_ms: Option<u64>,
574}
575
576impl CustomClassifierConfig {
577    /// Creates a custom-schema classifier contract with conservative runtime defaults.
578    pub fn new(
579        prompt: impl Into<String>,
580        response_schema: Value,
581        policy: CustomClassifierPolicy,
582    ) -> Self {
583        Self {
584            prompt: prompt.into(),
585            response_schema,
586            policy,
587            classify_trigger: ClassifyTrigger::default(),
588            message_hash_fallback: false,
589            recent_turn_window: None,
590            max_output_tokens: DEFAULT_JUDGE_MAX_OUTPUT_TOKENS,
591            judge_deadline_ms: None,
592        }
593    }
594
595    fn validate(&self) -> Result<()> {
596        if self.max_output_tokens == 0 {
597            return Err(LibsyError::AlgorithmError {
598                message: "max_output_tokens must be at least 1".to_string(),
599            });
600        }
601        // Only `every_request` is rejected: it retains no target, so a fallback identity has nothing to key on. Both retaining triggers can key the retained target on a message hash when the caller sends no session id.
602        if self.message_hash_fallback && self.classify_trigger == ClassifyTrigger::EveryRequest {
603            return Err(LibsyError::AlgorithmError {
604                message:
605                    "message_hash_fallback requires classify_trigger = new_session or user_turn"
606                        .to_string(),
607            });
608        }
609        Ok(())
610    }
611}
612
613enum CustomPolicyRuntime {
614    TargetSelector(TargetSelectorPolicy),
615}
616
617impl JudgePolicy for CustomPolicyRuntime {
618    type Verdict = Value;
619
620    fn to_classification(
621        &self,
622        verdict: Option<&Self::Verdict>,
623        driver: &Driver,
624    ) -> Result<Classification> {
625        match self {
626            Self::TargetSelector(policy) => policy.to_classification(verdict, driver),
627        }
628    }
629}
630
631/// Builds the affinity router a trigger calls for, if any.
632fn affinity_router(
633    trigger: ClassifyTrigger,
634    message_hash_fallback: bool,
635) -> Option<Arc<AffinityRouter>> {
636    let router = match trigger {
637        ClassifyTrigger::EveryRequest => return None,
638        ClassifyTrigger::NewSession => AffinityRouter::new(),
639        ClassifyTrigger::UserTurn => AffinityRouter::new().with_release_on_user_turn(),
640    };
641    let router = if message_hash_fallback {
642        router.with_message_hash_fallback()
643    } else {
644        router
645    };
646    Some(Arc::new(router))
647}
648
649/// Routes requests through a capability, escalation, custom, or direct classifier mode.
650pub struct LlmTaskClassifier {
651    route: FallThrough,
652    /// Classifier used when this router is embedded in another cascade.
653    inner: Arc<dyn Classifier>,
654}
655
656struct ClassifierRouteConfig {
657    default_target: Category,
658    classify_trigger: ClassifyTrigger,
659    message_hash_fallback: bool,
660}
661
662/// Terminal classifier for a cascade whose classifiers may all abstain.
663/// Closes a cascade with the first runtime model in `category`.
664pub struct DefaultCategoryClassifier(pub Category);
665
666#[async_trait]
667impl Classifier for DefaultCategoryClassifier {
668    async fn score(
669        &self,
670        _state: &mut State,
671        _request: &mut Request,
672        driver: &Driver,
673    ) -> Result<(Classification, Option<Response>)> {
674        let target = driver.first_model_for(&self.0)?;
675        driver.set_evidence_if_empty(serde_json::json!({"source": "fall_open"}));
676        Ok((
677            Classification::Scores(vec![Score {
678                target: target.clone(),
679                confidence: 0.0,
680                category: Some(self.0.clone()),
681            }]),
682            None,
683        ))
684    }
685}
686
687/// Complete construction settings for one LLM classifier mode.
688#[derive(Clone)]
689#[non_exhaustive]
690pub enum LlmClassifierConfig {
691    /// Routes between efficient and capable targets from a task-level verdict.
692    Capability {
693        /// Capability classifier settings.
694        config: TaskClassifierConfig,
695    },
696    /// Judges efficient responses and escalates after a confirmed streak.
697    Escalation {
698        /// Prompt and verdict contract settings for the escalation judge.
699        contract: ClassifierContractConfig,
700        /// Escalation policy settings.
701        config: EscalationJudgeConfig,
702        /// Maximum completion tokens available to the escalation verdict.
703        max_output_tokens: u64,
704        /// Whole-consultation bound on the escalation judge call, in milliseconds.
705        judge_deadline_ms: Option<u64>,
706    },
707    /// Routes among model categories using a user-supplied schema and policy.
708    Custom {
709        /// Category selected when the judge does not produce a usable verdict.
710        default_target: Category,
711        /// Custom classifier settings.
712        config: CustomClassifierConfig,
713    },
714    /// Routes to the model category a decision service selects.
715    Direct {
716        /// Category used when the decision call fails or returns an invalid choice.
717        default_target: Category,
718        /// Direct selection settings.
719        config: DirectClassifierConfig,
720    },
721}
722
723impl LlmTaskClassifier {
724    /// Builds the classifier mode described by `config`.
725    ///
726    /// # Errors
727    ///
728    /// Returns an error when the selected mode's targets, contract, policy, or runtime
729    /// settings are invalid.
730    pub fn new(config: LlmClassifierConfig) -> Result<Self> {
731        match config {
732            LlmClassifierConfig::Capability { config } => Self::build_capability(config, false),
733            LlmClassifierConfig::Escalation {
734                contract,
735                config,
736                max_output_tokens,
737                judge_deadline_ms,
738            } => Self::build_escalation(contract, config, max_output_tokens, judge_deadline_ms),
739            LlmClassifierConfig::Custom {
740                default_target,
741                config,
742            } => Self::build_custom(default_target, config),
743            LlmClassifierConfig::Direct {
744                default_target,
745                config,
746            } => Self::build_direct(default_target, config),
747        }
748    }
749
750    pub(super) fn build_capability(
751        config: TaskClassifierConfig,
752        omit_inline_decision_instructions: bool,
753    ) -> Result<Self> {
754        config.validate()?;
755        let classify_trigger = config.classify_trigger;
756        let message_hash_fallback = config.message_hash_fallback;
757        let input = TaskInput {
758            recent_turn_window: config.recent_turn_window,
759        };
760        let classifier: Arc<dyn Classifier> = match config.judge {
761            CapabilityJudgeConfig::Llm(judge) => Arc::new(
762                JudgeClassifier::new(
763                    StructuredJudge::new(
764                        input,
765                        Self::load_capability_contract(&judge.contract)?,
766                        SerdeDecoder::new(),
767                        JudgeRuntimeConfig::new(judge.max_output_tokens)?
768                            .with_deadline_ms(judge.judge_deadline_ms)?,
769                    ),
770                    TaskClassifierPolicy::new(&judge),
771                )
772                .with_error_recovery(config.fail_open)
773                .with_evidence(capability_evidence),
774            ),
775            CapabilityJudgeConfig::Decision(judge) => Arc::new(DecisionClassifier::new(
776                judge,
777                input,
778                config.fail_open,
779                omit_inline_decision_instructions,
780            )?),
781        };
782        Self::from_classifier(
783            classifier,
784            ClassifierRouteConfig {
785                default_target: Category::Capable,
786                classify_trigger,
787                message_hash_fallback,
788            },
789        )
790    }
791
792    fn build_custom(default_target: Category, config: CustomClassifierConfig) -> Result<Self> {
793        Self::from_classifier(
794            Self::custom_classifier(&config, false)?,
795            ClassifierRouteConfig {
796                default_target,
797                classify_trigger: config.classify_trigger,
798                message_hash_fallback: config.message_hash_fallback,
799            },
800        )
801    }
802
803    fn build_direct(default_target: Category, config: DirectClassifierConfig) -> Result<Self> {
804        if !config.options.contains(&default_target) {
805            return Err(LibsyError::AlgorithmError {
806                message: "direct default_target must be one of the options".into(),
807            });
808        }
809        let route = ClassifierRouteConfig {
810            default_target,
811            classify_trigger: config.classify_trigger,
812            message_hash_fallback: config.message_hash_fallback,
813        };
814        Self::from_classifier(Arc::new(DirectClassifier::new(config)?), route)
815    }
816
817    /// The judge face alone, for composite's own trigger and retained tier.
818    pub(crate) fn custom_classifier(
819        config: &CustomClassifierConfig,
820        fail_open: bool,
821    ) -> Result<Arc<dyn Classifier>> {
822        config.validate()?;
823        let contract =
824            ClassifierContract::from_inner_schema(&config.prompt, config.response_schema.clone())?;
825        let policy = match &config.policy {
826            CustomClassifierPolicy::TargetSelector { selector } => {
827                CustomPolicyRuntime::TargetSelector(TargetSelectorPolicy::new(selector)?)
828            }
829        };
830        let classifier = JudgeClassifier::new(
831            StructuredJudge::new(
832                TaskInput {
833                    recent_turn_window: config.recent_turn_window,
834                },
835                contract,
836                JsonSchemaDecoder::new(),
837                JudgeRuntimeConfig::new(config.max_output_tokens)?
838                    .with_deadline_ms(config.judge_deadline_ms)?,
839            ),
840            policy,
841        )
842        .with_error_recovery(fail_open);
843        let classifier = if fail_open {
844            classifier.with_evidence(|_, verdict| {
845                verdict.map(|_| serde_json::json!({"source": "llm-classifier"}))
846            })
847        } else {
848            classifier
849        };
850        Ok(Arc::new(classifier))
851    }
852
853    fn build_escalation(
854        contract_config: ClassifierContractConfig,
855        config: EscalationJudgeConfig,
856        max_output_tokens: u64,
857        judge_deadline_ms: Option<u64>,
858    ) -> Result<Self> {
859        let inner = escalation::build_classifier(
860            contract_config,
861            config,
862            max_output_tokens,
863            judge_deadline_ms,
864        )?;
865        Ok(Self {
866            route: FallThrough::new_with_state()
867                .with_name(ALGORITHM_NAME)
868                .with_classifier(Arc::clone(&inner)),
869            inner,
870        })
871    }
872
873    /// Loads the packaged capability-classifier contract.
874    fn load_capability_contract(config: &ClassifierContractConfig) -> Result<ClassifierContract> {
875        ClassifierContract::from_config(config, PROMPT_TEMPLATE, SCHEMA_TEMPLATE)
876    }
877
878    /// Keeps affinity and fallback ordering identical across judge-backed modes.
879    fn from_classifier(inner: Arc<dyn Classifier>, config: ClassifierRouteConfig) -> Result<Self> {
880        // Only `every_request` is rejected: it retains no target, so a fallback identity has nothing to key on. Both retaining triggers can key the retained target on a message hash when the caller sends no session id.
881        if config.message_hash_fallback && config.classify_trigger == ClassifyTrigger::EveryRequest
882        {
883            return Err(LibsyError::AlgorithmError {
884                message:
885                    "message_hash_fallback requires classify_trigger = new_session or user_turn"
886                        .to_string(),
887            });
888        }
889        // Affinity comes first so a retained assignment short-circuits the judge call.
890        let mut route = FallThrough::new_with_state().with_name(ALGORITHM_NAME);
891        if let Some(affinity) =
892            affinity_router(config.classify_trigger, config.message_hash_fallback).as_ref()
893        {
894            // Both roles must share one `Arc` so the classifier reads what the processor wrote.
895            route = route
896                .with_processor(affinity.clone())
897                .with_classifier(affinity.clone());
898        }
899        let fallback = DefaultCategoryClassifier(config.default_target);
900        Ok(Self {
901            route: route
902                .with_classifier(inner.clone())
903                .with_classifier(Arc::new(fallback)),
904            inner,
905        })
906    }
907}
908
909#[async_trait]
910impl Classifier for LlmTaskClassifier {
911    async fn score(
912        &self,
913        state: &mut State,
914        request: &mut Request,
915        driver: &Driver,
916    ) -> Result<(Classification, Option<Response>)> {
917        self.inner.score(state, request, driver).await
918    }
919}
920
921#[async_trait]
922impl Algorithm for LlmTaskClassifier {
923    fn name(&self) -> &str {
924        "llm_task_classifier"
925    }
926
927    async fn route(
928        self: Arc<Self>,
929        driver: Driver,
930        request: Request,
931    ) -> Result<crate::RoutingOutcome> {
932        self.route.execute(driver, request).await
933    }
934}
935
936#[cfg(test)]
937mod tests {
938    use std::collections::HashMap;
939    use std::sync::Arc;
940
941    use parking_lot::Mutex;
942    use serde_json::Value;
943
944    use super::*;
945    use switchyard_protocol::{
946        ContentBlock, InstructionBlock, LlmClientError, LlmRequest, Metadata, ModelId, ToolCall,
947        ToolResult, completion_text, text_request, text_response,
948    };
949
950    use crate::algorithms::util::llm_judge::Judge;
951    use crate::core::testing::{Serve, test_drive_with_models};
952    use switchyard_protocol::{LlmResponse, Response};
953
954    const TEST_THRESHOLD: f64 = 0.5;
955
956    type CapabilityJudge = StructuredJudge<TaskInput, SerdeDecoder<TaskClassifierVerdict>>;
957
958    fn llm_config(base_threshold: f64) -> LlmCapabilityConfig {
959        LlmCapabilityConfig {
960            base_threshold,
961            ..LlmCapabilityConfig::default()
962        }
963    }
964
965    fn test_config(base_threshold: f64) -> TaskClassifierConfig {
966        TaskClassifierConfig {
967            judge: CapabilityJudgeConfig::Llm(llm_config(base_threshold)),
968            ..TaskClassifierConfig::default()
969        }
970    }
971
972    fn policy() -> TaskClassifierPolicy {
973        TaskClassifierPolicy::new(&llm_config(TEST_THRESHOLD))
974    }
975
976    fn runtime_models() -> HashMap<Category, Vec<ModelId>> {
977        [
978            (Category::Judge, vec![ModelId::from("judge")]),
979            (Category::Efficient, vec![ModelId::from("efficient")]),
980            (Category::Capable, vec![ModelId::from("capable")]),
981            (
982                Category::Any,
983                vec![ModelId::from("efficient"), ModelId::from("capable")],
984            ),
985        ]
986        .into()
987    }
988
989    fn policy_driver() -> Driver {
990        Driver::new("test", Arc::new(runtime_models().into())).0
991    }
992
993    fn verdict(
994        p_solve: f64,
995        capability_boundary: &str,
996        primary_rule: &str,
997    ) -> TaskClassifierVerdict {
998        TaskClassifierVerdict {
999            crux: "test crux".to_string(),
1000            primary_rule: primary_rule.to_string(),
1001            capability_boundary: capability_boundary.to_string(),
1002            p_solve,
1003        }
1004    }
1005
1006    fn selected(
1007        policy: &TaskClassifierPolicy,
1008        verdict: Option<&TaskClassifierVerdict>,
1009    ) -> Result<ModelId> {
1010        policy
1011            .to_classification(verdict, &policy_driver())?
1012            .argmax(false)?
1013            .map(|score| score.target)
1014            .ok_or_else(|| LibsyError::AlgorithmError {
1015                message: "policy abstained".to_string(),
1016            })
1017    }
1018
1019    /// Records what each target received; answers the judge with a supported verdict and
1020    /// every other target with a plain completion.
1021    #[derive(Default)]
1022    struct Recorder {
1023        calls: Mutex<Vec<String>>,
1024        call_roles: Mutex<Vec<(String, bool)>>,
1025        judge_max_output_tokens: Mutex<Vec<Option<u64>>>,
1026        judge_system_prompts: Mutex<Vec<String>>,
1027    }
1028
1029    impl Recorder {
1030        fn calls(&self) -> Vec<String> {
1031            self.calls.lock().clone()
1032        }
1033
1034        fn call_roles(&self) -> Vec<(String, bool)> {
1035            self.call_roles.lock().clone()
1036        }
1037
1038        fn judge_max_output_tokens(&self) -> Vec<Option<u64>> {
1039            self.judge_max_output_tokens.lock().clone()
1040        }
1041
1042        fn judge_system_prompts(&self) -> Vec<String> {
1043            self.judge_system_prompts.lock().clone()
1044        }
1045
1046        fn serve(self: &Arc<Self>) -> impl Serve {
1047            let recorder = Arc::clone(self);
1048            move |model: ModelId, request: Request| {
1049                let recorder = Arc::clone(&recorder);
1050                async move {
1051                    let model = model.to_string();
1052                    recorder.calls.lock().push(model.clone());
1053                    recorder
1054                        .call_roles
1055                        .lock()
1056                        .push((model.clone(), model != "judge"));
1057                    let completion = if model == "judge" {
1058                        recorder
1059                            .judge_max_output_tokens
1060                            .lock()
1061                            .push(request.llm_request.output.max_output_tokens);
1062                        recorder.judge_system_prompts.lock().extend(
1063                            request
1064                                .llm_request
1065                                .instructions
1066                                .first()
1067                                .and_then(|instruction| {
1068                                    instruction.content.iter().find_map(|b| {
1069                                        if let ContentBlock::Text { text } = b {
1070                                            Some(text.clone())
1071                                        } else {
1072                                            None
1073                                        }
1074                                    })
1075                                }),
1076                        );
1077                        r#"{"crux":"bounded task","primary_rule":"SUP-1","capability_boundary":"supported","p_solve":0.9}"#.to_string()
1078                    } else {
1079                        format!("answer from {model}")
1080                    };
1081                    Ok(Response {
1082                        llm_response: LlmResponse::Agg(text_response(None, completion)),
1083                        metadata: request.metadata,
1084                        upstream_headers: http::HeaderMap::new(),
1085                    })
1086                }
1087            }
1088        }
1089    }
1090
1091    /// The judge times out; every other target answers normally.
1092    fn unreachable_judge() -> impl Serve {
1093        |model: ModelId, request: Request| async move {
1094            let model = model.to_string();
1095            if model == "judge" {
1096                return Err(LlmClientError::Timeout {
1097                    source: Box::new(std::io::Error::other("judge unreachable")),
1098                });
1099            }
1100            Ok(Response {
1101                llm_response: LlmResponse::Agg(text_response(None, format!("answer from {model}"))),
1102                metadata: request.metadata,
1103                upstream_headers: http::HeaderMap::new(),
1104            })
1105        }
1106    }
1107
1108    /// The judge stalls before answering; every other target answers normally.
1109    fn slow_judge(delay: std::time::Duration) -> impl Serve {
1110        move |model: ModelId, request: Request| {
1111            let model = model.to_string();
1112            let slow = model == "judge";
1113            async move {
1114                if slow {
1115                    tokio::time::sleep(delay).await;
1116                }
1117                Ok(Response {
1118                    llm_response: LlmResponse::Agg(text_response(
1119                        None,
1120                        format!("answer from {model}"),
1121                    )),
1122                    metadata: request.metadata,
1123                    upstream_headers: http::HeaderMap::new(),
1124                })
1125            }
1126        }
1127    }
1128
1129    /// The judge accepts the call but its stream never carries a chunk.
1130    fn stalled_judge_stream() -> impl Serve {
1131        use futures::StreamExt;
1132        |model: ModelId, request: Request| async move {
1133            let model = model.to_string();
1134            let llm_response = if model == "judge" {
1135                LlmResponse::Stream(futures::stream::pending().boxed())
1136            } else {
1137                LlmResponse::Agg(text_response(None, format!("answer from {model}")))
1138            };
1139            Ok(Response {
1140                llm_response,
1141                metadata: request.metadata,
1142                upstream_headers: http::HeaderMap::new(),
1143            })
1144        }
1145    }
1146
1147    fn deadline_router(fail_open: bool) -> Result<Arc<LlmTaskClassifier>> {
1148        Ok(Arc::new(LlmTaskClassifier::new(
1149            LlmClassifierConfig::Capability {
1150                config: TaskClassifierConfig {
1151                    judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig {
1152                        judge_deadline_ms: Some(10),
1153                        ..llm_config(TEST_THRESHOLD)
1154                    }),
1155                    fail_open,
1156                    ..TaskClassifierConfig::default()
1157                },
1158            },
1159        )?))
1160    }
1161
1162    fn router() -> Result<Arc<LlmTaskClassifier>> {
1163        Ok(Arc::new(LlmTaskClassifier::new(
1164            LlmClassifierConfig::Capability {
1165                config: test_config(TEST_THRESHOLD),
1166            },
1167        )?))
1168    }
1169
1170    fn classify_request() -> Request {
1171        Request {
1172            llm_request: text_request(Some("auto".to_string()), "classify this task"),
1173            raw_request: None,
1174            metadata: None,
1175        }
1176    }
1177
1178    fn classify_session_request() -> Request {
1179        Request {
1180            metadata: Some(Metadata {
1181                session_id: Some("session-1".to_string()),
1182                ..Metadata::default()
1183            }),
1184            ..classify_request()
1185        }
1186    }
1187
1188    fn classify_follow_up_request() -> Request {
1189        let mut request = classify_request();
1190        request
1191            .llm_request
1192            .messages
1193            .push(Message::text(Role::Assistant, "I will add the test."));
1194        request.llm_request.messages.push(Message::text(
1195            Role::User,
1196            "Now run the test suite and report the result.",
1197        ));
1198        request
1199    }
1200
1201    #[tokio::test]
1202    async fn an_unreachable_judge_routes_capable_instead_of_failing_the_request() -> Result<()> {
1203        let router = router()?;
1204
1205        let (selected_model, response) = test_drive_with_models(
1206            router,
1207            classify_request(),
1208            runtime_models(),
1209            unreachable_judge(),
1210        )
1211        .await?;
1212
1213        assert_eq!(selected_model, "capable");
1214        assert_eq!(
1215            response.llm_response.as_agg().map(completion_text),
1216            Some("answer from capable".to_string())
1217        );
1218        Ok(())
1219    }
1220
1221    #[tokio::test]
1222    async fn a_judge_past_its_deadline_routes_capable() -> Result<()> {
1223        let (selected_model, response) = test_drive_with_models(
1224            deadline_router(true)?,
1225            classify_request(),
1226            runtime_models(),
1227            slow_judge(std::time::Duration::from_millis(500)),
1228        )
1229        .await?;
1230
1231        assert_eq!(selected_model, "capable");
1232        assert_eq!(
1233            response.llm_response.as_agg().map(completion_text),
1234            Some("answer from capable".to_string())
1235        );
1236        Ok(())
1237    }
1238
1239    #[tokio::test]
1240    async fn a_stalled_judge_stream_is_cut_by_the_deadline() -> Result<()> {
1241        // The judge returned headers promptly, so only a bound on the whole
1242        // consultation — the drain included — can end this turn.
1243        let (selected_model, _) = test_drive_with_models(
1244            deadline_router(true)?,
1245            classify_request(),
1246            runtime_models(),
1247            stalled_judge_stream(),
1248        )
1249        .await?;
1250
1251        assert_eq!(selected_model, "capable");
1252        Ok(())
1253    }
1254
1255    #[tokio::test]
1256    async fn a_judge_past_its_deadline_stops_when_not_failing_open() -> Result<()> {
1257        let outcome = test_drive_with_models(
1258            deadline_router(false)?,
1259            classify_request(),
1260            runtime_models(),
1261            slow_judge(std::time::Duration::from_millis(500)),
1262        )
1263        .await;
1264        let error = outcome
1265            .err()
1266            .expect("a deadline expiry with fail_open = false must stop the request");
1267
1268        assert!(
1269            matches!(
1270                error,
1271                LibsyError::ClientCall {
1272                    source: LlmClientError::Timeout { .. },
1273                    ..
1274                }
1275            ),
1276            "expected a client timeout, got {error:?}"
1277        );
1278        Ok(())
1279    }
1280
1281    #[test]
1282    fn a_zero_judge_deadline_is_rejected_in_every_mode() {
1283        let capability = LlmClassifierConfig::Capability {
1284            config: TaskClassifierConfig {
1285                judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig {
1286                    judge_deadline_ms: Some(0),
1287                    ..llm_config(TEST_THRESHOLD)
1288                }),
1289                ..TaskClassifierConfig::default()
1290            },
1291        };
1292        assert!(
1293            LlmTaskClassifier::new(capability).is_err(),
1294            "capability mode must reject judge_deadline_ms = 0"
1295        );
1296
1297        let mut custom = CustomClassifierConfig::new(
1298            "Route by topic.",
1299            serde_json::json!({"type": "object"}),
1300            CustomClassifierPolicy::target_selector("/target"),
1301        );
1302        custom.judge_deadline_ms = Some(0);
1303        assert!(
1304            LlmTaskClassifier::new(LlmClassifierConfig::Custom {
1305                default_target: Category::Capable,
1306                config: custom,
1307            })
1308            .is_err(),
1309            "custom mode must reject judge_deadline_ms = 0"
1310        );
1311
1312        let escalation = LlmClassifierConfig::Escalation {
1313            contract: ClassifierContractConfig::default(),
1314            config: EscalationJudgeConfig::default(),
1315            max_output_tokens: DEFAULT_JUDGE_MAX_OUTPUT_TOKENS,
1316            judge_deadline_ms: Some(0),
1317        };
1318        assert!(
1319            LlmTaskClassifier::new(escalation).is_err(),
1320            "escalation mode must reject judge_deadline_ms = 0"
1321        );
1322    }
1323
1324    #[test]
1325    fn classifier_config_parses_a_judge_deadline() {
1326        let config: TaskClassifierConfig = serde_json::from_value(serde_json::json!({
1327            "base_threshold": 0.5,
1328            "judge_deadline_ms": 250,
1329        }))
1330        .expect("a configured judge deadline should parse");
1331        let CapabilityJudgeConfig::Llm(judge) = config.judge else {
1332            panic!("expected the LLM judge variant");
1333        };
1334        assert_eq!(judge.judge_deadline_ms, Some(250));
1335
1336        let config: TaskClassifierConfig = serde_json::from_value(serde_json::json!({
1337            "base_threshold": 0.5,
1338        }))
1339        .expect("an unset judge deadline should parse");
1340        let CapabilityJudgeConfig::Llm(judge) = config.judge else {
1341            panic!("expected the LLM judge variant");
1342        };
1343        assert_eq!(judge.judge_deadline_ms, None);
1344    }
1345
1346    #[tokio::test]
1347    async fn classifier_judges_each_request_without_affinity() -> Result<()> {
1348        let recorder = Arc::new(Recorder::default());
1349        let router = router()?;
1350        let request = classify_request();
1351        let models = runtime_models();
1352
1353        test_drive_with_models(
1354            router.clone(),
1355            request.clone(),
1356            models.clone(),
1357            recorder.serve(),
1358        )
1359        .await?;
1360        test_drive_with_models(router, request, models, recorder.serve()).await?;
1361
1362        assert_eq!(
1363            recorder.calls(),
1364            vec!["judge", "efficient", "judge", "efficient"]
1365        );
1366        assert_eq!(
1367            recorder.call_roles(),
1368            vec![
1369                ("judge".to_string(), false),
1370                ("efficient".to_string(), true),
1371                ("judge".to_string(), false),
1372                ("efficient".to_string(), true),
1373            ]
1374        );
1375        Ok(())
1376    }
1377
1378    #[tokio::test]
1379    async fn classifier_config_sets_the_judge_completion_cap() -> Result<()> {
1380        let recorder = Arc::new(Recorder::default());
1381        let router = Arc::new(LlmTaskClassifier::new(LlmClassifierConfig::Capability {
1382            config: TaskClassifierConfig {
1383                judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig {
1384                    max_output_tokens: 512,
1385                    ..llm_config(TEST_THRESHOLD)
1386                }),
1387                ..test_config(TEST_THRESHOLD)
1388            },
1389        })?);
1390
1391        test_drive_with_models(
1392            router,
1393            classify_request(),
1394            runtime_models(),
1395            recorder.serve(),
1396        )
1397        .await?;
1398
1399        assert_eq!(recorder.judge_max_output_tokens(), vec![Some(512)]);
1400        Ok(())
1401    }
1402
1403    #[tokio::test]
1404    async fn classifier_config_overrides_the_packaged_prompt() -> Result<()> {
1405        let recorder = Arc::new(Recorder::default());
1406        let router = Arc::new(LlmTaskClassifier::new(LlmClassifierConfig::Capability {
1407            config: TaskClassifierConfig {
1408                judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig {
1409                    contract: ClassifierContractConfig::default()
1410                        .with_prompt("Custom capability rubric."),
1411                    ..llm_config(TEST_THRESHOLD)
1412                }),
1413                ..test_config(TEST_THRESHOLD)
1414            },
1415        })?);
1416
1417        test_drive_with_models(
1418            router,
1419            classify_request(),
1420            runtime_models(),
1421            recorder.serve(),
1422        )
1423        .await?;
1424
1425        let prompts = recorder.judge_system_prompts();
1426        assert_eq!(prompts.len(), 1);
1427        assert_eq!(prompts[0], "Custom capability rubric.");
1428        Ok(())
1429    }
1430
1431    #[tokio::test]
1432    async fn classifier_config_enables_new_session_trigger() -> Result<()> {
1433        let recorder = Arc::new(Recorder::default());
1434        let router = Arc::new(LlmTaskClassifier::new(LlmClassifierConfig::Capability {
1435            config: TaskClassifierConfig {
1436                classify_trigger: ClassifyTrigger::NewSession,
1437                ..test_config(TEST_THRESHOLD)
1438            },
1439        })?);
1440
1441        let request = classify_session_request();
1442        let models = runtime_models();
1443        test_drive_with_models(
1444            router.clone(),
1445            request.clone(),
1446            models.clone(),
1447            recorder.serve(),
1448        )
1449        .await?;
1450        test_drive_with_models(router, request, models, recorder.serve()).await?;
1451
1452        assert_eq!(recorder.calls(), vec!["judge", "efficient", "efficient"]);
1453        Ok(())
1454    }
1455
1456    #[tokio::test]
1457    async fn classifier_config_reuses_message_hash_affinity_for_a_follow_up() -> Result<()> {
1458        let recorder = Arc::new(Recorder::default());
1459        let router = Arc::new(LlmTaskClassifier::new(LlmClassifierConfig::Capability {
1460            config: TaskClassifierConfig {
1461                classify_trigger: ClassifyTrigger::NewSession,
1462                message_hash_fallback: true,
1463                recent_turn_window: None,
1464                ..test_config(TEST_THRESHOLD)
1465            },
1466        })?);
1467
1468        let models = runtime_models();
1469        test_drive_with_models(
1470            router.clone(),
1471            classify_request(),
1472            models.clone(),
1473            recorder.serve(),
1474        )
1475        .await?;
1476        test_drive_with_models(
1477            router,
1478            classify_follow_up_request(),
1479            models,
1480            recorder.serve(),
1481        )
1482        .await?;
1483
1484        assert_eq!(recorder.calls(), vec!["judge", "efficient", "efficient"]);
1485        Ok(())
1486    }
1487
1488    #[tokio::test]
1489    async fn one_classifier_uses_each_requests_runtime_models() -> Result<()> {
1490        let router = Arc::new(LlmTaskClassifier::new(LlmClassifierConfig::Capability {
1491            config: TaskClassifierConfig {
1492                classify_trigger: ClassifyTrigger::NewSession,
1493                ..test_config(TEST_THRESHOLD)
1494            },
1495        })?);
1496        let calls = Arc::new(Mutex::new(Vec::new()));
1497        let serve = |calls: Arc<Mutex<Vec<String>>>| {
1498            move |model: ModelId, _request: Request| {
1499                let calls = Arc::clone(&calls);
1500                async move {
1501                    calls.lock().push(model.to_string());
1502                    let text = if model.as_str().starts_with("judge-") {
1503                        r#"{"crux":"bounded task","primary_rule":"SUP-1","capability_boundary":"supported","p_solve":0.9}"#.to_string()
1504                    } else {
1505                        model.to_string()
1506                    };
1507                    Ok(Response {
1508                        llm_response: LlmResponse::Agg(text_response(None, text)),
1509                        metadata: None,
1510                        upstream_headers: Default::default(),
1511                    })
1512                }
1513            }
1514        };
1515        let models = |suffix: &str| -> HashMap<Category, Vec<ModelId>> {
1516            [
1517                (
1518                    Category::Judge,
1519                    vec![ModelId::from(format!("judge-{suffix}"))],
1520                ),
1521                (
1522                    Category::Efficient,
1523                    vec![ModelId::from(format!("efficient-{suffix}"))],
1524                ),
1525                (
1526                    Category::Capable,
1527                    vec![ModelId::from(format!("capable-{suffix}"))],
1528                ),
1529                (
1530                    Category::Any,
1531                    vec![
1532                        ModelId::from(format!("efficient-{suffix}")),
1533                        ModelId::from(format!("capable-{suffix}")),
1534                    ],
1535                ),
1536            ]
1537            .into()
1538        };
1539        let request = classify_session_request();
1540
1541        let (first, _) = test_drive_with_models(
1542            router.clone(),
1543            request.clone(),
1544            models("a"),
1545            serve(Arc::clone(&calls)),
1546        )
1547        .await?;
1548        let (second, _) =
1549            test_drive_with_models(router, request, models("b"), serve(Arc::clone(&calls))).await?;
1550
1551        assert_eq!(first, "efficient-a");
1552        assert_eq!(second, "efficient-b");
1553        assert_eq!(
1554            &*calls.lock(),
1555            &["judge-a", "efficient-a", "judge-b", "efficient-b"]
1556        );
1557        Ok(())
1558    }
1559
1560    #[tokio::test]
1561    async fn decision_judge_routes_on_capable_probability() -> Result<()> {
1562        use crate::{Call, RuntimeModels, drive};
1563        use serde_json::json;
1564        use std::collections::BTreeMap;
1565        use std::sync::atomic::{AtomicUsize, Ordering};
1566        use switchyard_protocol::{
1567            BooleanEstimate, DecisionAnswer, DecisionResponse, DecisionValue, Probability,
1568            ProviderConfidence,
1569        };
1570
1571        let settings = DecisionJudgeConfig {
1572            cutoff: Some(0.4),
1573            ..DecisionJudgeConfig::default()
1574        };
1575        let mut request = classify_session_request();
1576        request.llm_request.messages.push(Message::new(
1577            Role::Assistant,
1578            vec![
1579                ContentBlock::Reasoning {
1580                    text: "private reasoning".into(),
1581                    signature: None,
1582                    details: vec![],
1583                },
1584                ContentBlock::Text {
1585                    text: "visible progress".into(),
1586                },
1587            ],
1588        ));
1589        request
1590            .llm_request
1591            .messages
1592            .push(Message::text(Role::User, "latest follow-up"));
1593        let original_messages = request.llm_request.messages.clone();
1594        let expected_task = json!([
1595            original_messages[0].clone(),
1596            Message::text(Role::Assistant, "visible progress"),
1597            Message::text(Role::User, "latest follow-up"),
1598        ]);
1599
1600        for (name, score, fail_open, expected) in [
1601            ("above", 0.45, true, Some("capable")),
1602            ("equal", 0.4, true, Some("efficient")),
1603            ("below", 0.39, false, Some("efficient")),
1604            ("missing answer", 0.0, true, Some("capable")),
1605            ("no distribution", 0.0, true, Some("capable")),
1606            ("wrong type", 0.0, true, Some("capable")),
1607            ("out of range", 1.1, true, Some("capable")),
1608            ("nonfinite", f64::NAN, true, Some("capable")),
1609            ("missing probability", 0.0, true, Some("capable")),
1610            ("missing answer", 0.0, false, None),
1611            ("no distribution", 0.0, false, None),
1612            ("wrong type", 0.0, false, None),
1613            ("out of range", 1.1, false, None),
1614            ("negative", -0.1, false, None),
1615            ("nonfinite", f64::NAN, false, None),
1616            ("infinite", f64::INFINITY, false, None),
1617            ("missing probability", 0.0, false, None),
1618            ("provider error", 0.0, true, Some("capable")),
1619            ("provider error", 0.0, false, None),
1620            ("dropped reply", 0.0, true, Some("capable")),
1621            ("custom choices", 0.45, false, Some("capable")),
1622        ] {
1623            let mut config = settings.clone();
1624            if name == "below" {
1625                config.instructions = Some("Choose capable when the task needs it.".into());
1626            }
1627            if name == "custom choices" {
1628                config.choices[0].id = "complex".into();
1629                config.choices[1].id = "simple".into();
1630                config.apply_cutoff_to = "complex".into();
1631            }
1632            let override_instructions = config.instructions.clone();
1633            let choice_ids = [config.choices[0].id.clone(), config.choices[1].id.clone()];
1634            let router: Arc<dyn Algorithm> =
1635                Arc::new(LlmTaskClassifier::new(LlmClassifierConfig::Capability {
1636                    config: TaskClassifierConfig {
1637                        judge: CapabilityJudgeConfig::Decision(config),
1638                        fail_open,
1639                        recent_turn_window: None,
1640                        classify_trigger: ClassifyTrigger::NewSession,
1641                        ..TaskClassifierConfig::default()
1642                    },
1643                })?);
1644            let calls = AtomicUsize::new(0);
1645            let serve = |call| {
1646                let calls = &calls;
1647                let expected_task = &expected_task;
1648                let override_instructions = &override_instructions;
1649                let [capable_id, efficient_id] = choice_ids.clone();
1650                async move {
1651                    let Call::Decision(call) = call else {
1652                        panic!("judge must use the decision step")
1653                    };
1654                    calls.fetch_add(1, Ordering::SeqCst);
1655                    assert_eq!(call.model, "judge");
1656                    assert_eq!(call.request.model, Some("judge".into()));
1657                    assert_eq!(
1658                        serde_json::to_value(&call.request.input).unwrap(),
1659                        *expected_task
1660                    );
1661                    assert_eq!(call.request.questions.len(), 1);
1662                    let question = &call.request.questions["route"];
1663                    let switchyard_protocol::DecisionKind::Choice { options } = &question.kind
1664                    else {
1665                        panic!("expected a choice")
1666                    };
1667                    assert_eq!(
1668                        options
1669                            .iter()
1670                            .map(|option| option.id.as_str())
1671                            .collect::<Vec<_>>(),
1672                        [capable_id.as_str(), efficient_id.as_str()]
1673                    );
1674                    if let Some(instructions) = override_instructions {
1675                        assert_eq!(&question.instructions, instructions);
1676                    } else {
1677                        assert!(
1678                            question
1679                                .instructions
1680                                .as_str()
1681                                .is_some_and(|text| !text.is_empty())
1682                        );
1683                    }
1684                    if name == "provider error" {
1685                        return call
1686                            .respond(std::future::ready(Err(LibsyError::client_call(
1687                                "judge",
1688                                LlmClientError::General("private provider body".into()),
1689                            ))))
1690                            .await;
1691                    }
1692                    if name == "dropped reply" {
1693                        drop(call);
1694                        return Ok(());
1695                    }
1696                    let value = if name == "wrong type" {
1697                        DecisionValue::Boolean(BooleanEstimate::Value(true))
1698                    } else {
1699                        DecisionValue::Choice {
1700                            selected: efficient_id.clone(),
1701                            probabilities: (name != "no distribution").then(|| {
1702                                BTreeMap::from([
1703                                    (
1704                                        if name == "missing probability" {
1705                                            "other".into()
1706                                        } else {
1707                                            capable_id.clone()
1708                                        },
1709                                        Probability(score),
1710                                    ),
1711                                    (efficient_id.clone(), Probability(1.0 - score)),
1712                                ])
1713                            }),
1714                        }
1715                    };
1716                    let answers = if name == "missing answer" {
1717                        BTreeMap::new()
1718                    } else {
1719                        BTreeMap::from([(
1720                            "route".into(),
1721                            DecisionAnswer {
1722                                value,
1723                                provider_confidence: Some(ProviderConfidence(0.99)),
1724                            },
1725                        )])
1726                    };
1727                    call.respond(std::future::ready(Ok(DecisionResponse {
1728                        id: None,
1729                        model: Some("provider-judge".into()),
1730                        answers,
1731                        usage: Default::default(),
1732                    })))
1733                    .await
1734                }
1735            };
1736            let models = Arc::new(RuntimeModels::new(runtime_models()));
1737            let result = drive(router.clone(), request.clone(), models.clone(), &serve).await;
1738            assert_eq!(calls.load(Ordering::SeqCst), 1, "{name}");
1739            let Some(expected) = expected else {
1740                if name == "provider error" {
1741                    assert!(
1742                        matches!(result, Err(LibsyError::ClientCall { .. })),
1743                        "{name}"
1744                    );
1745                } else {
1746                    assert!(
1747                        matches!(result, Err(LibsyError::InvalidDecision { target, .. }) if target == "judge"),
1748                        "expected invalid decision error: {name}"
1749                    );
1750                }
1751                continue;
1752            };
1753            let outcome = result?;
1754            assert_eq!(outcome.selected_model_id()?, expected, "{name}");
1755            assert!(outcome.response.is_none());
1756            assert_eq!(outcome.request.llm_request.messages, original_messages);
1757            let metadata = outcome.metadata.expect("routing metadata");
1758            assert_eq!(metadata.judgments.len(), 1);
1759            let evidence = metadata.evidence.expect("routing evidence");
1760            if matches!(name, "above" | "equal" | "below" | "custom choices") {
1761                assert_eq!(metadata.judgments[0].target.as_deref(), Some(expected));
1762                assert_eq!(evidence["source"], "decision_classifier");
1763                assert_eq!(evidence["verdict"], expected);
1764                assert_eq!(evidence["capable_threshold"], 0.4);
1765                assert_eq!(evidence["capable_score"], score);
1766            } else {
1767                let reason = match name {
1768                    "provider error" => "client_error",
1769                    "dropped reply" => "call_error",
1770                    _ => "invalid_verdict",
1771                };
1772                assert_eq!(
1773                    evidence,
1774                    json!({"source": "fail_open", "reason_code": reason})
1775                );
1776            }
1777            let retained = drive(router, request.clone(), models, &serve).await?;
1778            assert_eq!(retained.selected_model_id()?, expected);
1779            assert!(
1780                retained
1781                    .metadata
1782                    .expect("retained metadata")
1783                    .judgments
1784                    .is_empty()
1785            );
1786            assert_eq!(
1787                calls.load(Ordering::SeqCst),
1788                1,
1789                "affinity should skip the judge: {name}"
1790            );
1791        }
1792        for cutoff in [-0.1, 1.1, f64::NAN] {
1793            let mut config = settings.clone();
1794            config.cutoff = Some(cutoff);
1795            assert!(
1796                LlmTaskClassifier::new(LlmClassifierConfig::Capability {
1797                    config: TaskClassifierConfig {
1798                        judge: CapabilityJudgeConfig::Decision(config),
1799                        ..TaskClassifierConfig::default()
1800                    },
1801                })
1802                .is_err()
1803            );
1804        }
1805        Ok(())
1806    }
1807
1808    #[tokio::test]
1809    async fn direct_judge_falls_back_to_the_default_target() -> Result<()> {
1810        use crate::{Call, RuntimeModels, drive};
1811        use std::collections::BTreeMap;
1812        use switchyard_protocol::{DecisionAnswer, DecisionResponse, DecisionValue};
1813
1814        for (reply, fail_open, expected) in [
1815            (Some("unknown"), true, Some("efficient")),
1816            (Some("unknown"), false, None),
1817            (None, true, Some("efficient")),
1818            (None, false, None),
1819        ] {
1820            let router: Arc<dyn Algorithm> =
1821                Arc::new(LlmTaskClassifier::new(LlmClassifierConfig::Direct {
1822                    default_target: Category::Efficient,
1823                    config: DirectClassifierConfig {
1824                        options: vec![Category::Efficient, Category::Capable],
1825                        fail_open,
1826                        classify_trigger: ClassifyTrigger::EveryRequest,
1827                        message_hash_fallback: false,
1828                        recent_turn_window: None,
1829                    },
1830                })?);
1831            let serve = |call| async move {
1832                let Call::Decision(call) = call else {
1833                    panic!("judge must use the decision step")
1834                };
1835                let response = match reply {
1836                    Some(selected) => Ok(DecisionResponse {
1837                        id: None,
1838                        model: None,
1839                        answers: BTreeMap::from([(
1840                            "route".into(),
1841                            DecisionAnswer {
1842                                value: DecisionValue::Choice {
1843                                    selected: selected.into(),
1844                                    probabilities: None,
1845                                },
1846                                provider_confidence: None,
1847                            },
1848                        )]),
1849                        usage: Default::default(),
1850                    }),
1851                    None => Err(LibsyError::client_call(
1852                        "judge",
1853                        LlmClientError::General("unavailable".into()),
1854                    )),
1855                };
1856                call.respond(std::future::ready(response)).await
1857            };
1858            let models = Arc::new(RuntimeModels::new(runtime_models()));
1859            let result = drive(router, classify_request(), models, &serve).await;
1860            match expected {
1861                Some(expected) => assert_eq!(result?.selected_model_id()?, expected),
1862                None => assert!(result.is_err()),
1863            }
1864        }
1865        Ok(())
1866    }
1867
1868    #[test]
1869    fn the_threshold_boundary_is_inclusive() -> Result<()> {
1870        let policy = policy();
1871        let at_threshold = verdict(0.5, "supported", "SUP-1");
1872        let below_threshold = verdict(0.49, "supported", "SUP-1");
1873        assert_eq!(selected(&policy, Some(&at_threshold))?, "efficient");
1874        assert_eq!(selected(&policy, Some(&below_threshold))?, "capable");
1875        Ok(())
1876    }
1877
1878    #[test]
1879    fn the_threshold_moves_the_routing_boundary() -> Result<()> {
1880        let borderline = verdict(0.5, "supported", "SUP-1");
1881        let strict = TaskClassifierPolicy::new(&llm_config(0.9));
1882        let lenient = TaskClassifierPolicy::new(&llm_config(0.1));
1883        assert_eq!(selected(&strict, Some(&borderline))?, "capable");
1884        assert_eq!(selected(&lenient, Some(&borderline))?, "efficient");
1885        Ok(())
1886    }
1887
1888    #[test]
1889    fn classifier_config_rejects_unknown_fields() {
1890        let error = serde_json::from_value::<TaskClassifierConfig>(serde_json::json!({
1891            "base_threshold": 0.5,
1892            "classifier_magic": true,
1893        }))
1894        .expect_err("unknown classifier fields must be rejected");
1895
1896        assert!(
1897            error
1898                .to_string()
1899                .contains("unknown field `classifier_magic`"),
1900            "{error}"
1901        );
1902    }
1903
1904    #[test]
1905    fn invalid_classifier_config_is_rejected() -> Result<()> {
1906        for bad in [1.5, -0.1, f64::NAN, f64::INFINITY] {
1907            assert!(
1908                LlmTaskClassifier::new(LlmClassifierConfig::Capability {
1909                    config: test_config(bad),
1910                })
1911                .is_err(),
1912                "base threshold {bad} should be rejected"
1913            );
1914        }
1915        for config in [
1916            TaskClassifierConfig {
1917                judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig {
1918                    base_threshold: 0.5,
1919                    threshold_step: -0.1,
1920                    ..LlmCapabilityConfig::default()
1921                }),
1922                ..TaskClassifierConfig::default()
1923            },
1924            TaskClassifierConfig {
1925                judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig {
1926                    base_threshold: 0.8,
1927                    threshold_step: 0.11,
1928                    ..LlmCapabilityConfig::default()
1929                }),
1930                ..TaskClassifierConfig::default()
1931            },
1932            TaskClassifierConfig {
1933                judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig {
1934                    base_threshold: 0.5,
1935                    ..LlmCapabilityConfig::default()
1936                }),
1937                message_hash_fallback: true,
1938                ..TaskClassifierConfig::default()
1939            },
1940            TaskClassifierConfig {
1941                judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig {
1942                    base_threshold: 0.5,
1943                    max_output_tokens: 0,
1944                    ..LlmCapabilityConfig::default()
1945                }),
1946                ..TaskClassifierConfig::default()
1947            },
1948        ] {
1949            assert!(LlmTaskClassifier::new(LlmClassifierConfig::Capability { config }).is_err());
1950        }
1951        for base_threshold in [0.0, 1.0] {
1952            LlmTaskClassifier::new(LlmClassifierConfig::Capability {
1953                config: test_config(base_threshold),
1954            })?;
1955        }
1956        Ok(())
1957    }
1958
1959    #[test]
1960    fn message_hash_fallback_accepts_retaining_triggers() -> Result<()> {
1961        // Only `every_request` is rejected: it retains no target, so a fallback
1962        // identity has nothing to key on. Both retaining triggers may key the
1963        // retained target on a message hash when the caller sends no session id.
1964        for trigger in [ClassifyTrigger::NewSession, ClassifyTrigger::UserTurn] {
1965            let config = TaskClassifierConfig {
1966                judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig {
1967                    base_threshold: 0.5,
1968                    ..LlmCapabilityConfig::default()
1969                }),
1970                classify_trigger: trigger,
1971                message_hash_fallback: true,
1972                ..TaskClassifierConfig::default()
1973            };
1974            LlmTaskClassifier::new(LlmClassifierConfig::Capability { config }).map_err(
1975                |error| LibsyError::AlgorithmError {
1976                    message: format!("{trigger:?} with message_hash_fallback rejected: {error}"),
1977                },
1978            )?;
1979        }
1980        let every_request = TaskClassifierConfig {
1981            judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig {
1982                base_threshold: 0.5,
1983                ..LlmCapabilityConfig::default()
1984            }),
1985            classify_trigger: ClassifyTrigger::EveryRequest,
1986            message_hash_fallback: true,
1987            ..TaskClassifierConfig::default()
1988        };
1989        assert!(
1990            LlmTaskClassifier::new(LlmClassifierConfig::Capability {
1991                config: every_request
1992            })
1993            .is_err(),
1994            "every_request with message_hash_fallback should stay rejected"
1995        );
1996        Ok(())
1997    }
1998
1999    #[test]
2000    fn an_unusable_verdict_is_ambiguous() -> Result<()> {
2001        let policy = policy();
2002        let inconsistent_rule = TaskClassifierVerdict {
2003            capability_boundary: "uncertain".to_string(),
2004            ..verdict(1.0, "supported", "SUP-1")
2005        };
2006        let empty_crux = TaskClassifierVerdict {
2007            crux: "  ".to_string(),
2008            ..verdict(1.0, "supported", "SUP-1")
2009        };
2010        let unusable = [
2011            Some(verdict(1.1, "supported", "SUP-1")),
2012            Some(inconsistent_rule),
2013            Some(empty_crux),
2014            None,
2015        ];
2016        for verdict in unusable {
2017            let classification = policy.to_classification(verdict.as_ref(), &policy_driver())?;
2018            assert!(matches!(classification, Classification::Ambiguous(_)));
2019            assert!(classification.argmax(false)?.is_none());
2020            assert!(classification.argmax(true)?.is_none());
2021        }
2022        Ok(())
2023    }
2024
2025    #[test]
2026    fn capability_boundaries_apply_monotonic_threshold_steps() -> Result<()> {
2027        let policy = TaskClassifierPolicy::new(&LlmCapabilityConfig {
2028            threshold_step: 0.1,
2029            ..llm_config(0.4)
2030        });
2031
2032        assert_eq!(
2033            selected(&policy, Some(&verdict(0.4, "supported", "SUP-2")))?,
2034            "efficient"
2035        );
2036        assert_eq!(
2037            selected(&policy, Some(&verdict(0.49, "uncertain", "UNC-1")))?,
2038            "capable"
2039        );
2040        assert_eq!(
2041            selected(&policy, Some(&verdict(0.5, "uncertain", "UNC-1")))?,
2042            "efficient"
2043        );
2044        assert_eq!(
2045            selected(&policy, Some(&verdict(0.5, "unmatched", "none")))?,
2046            "efficient"
2047        );
2048        assert_eq!(
2049            selected(&policy, Some(&verdict(0.59, "unsupported", "LIM-1")))?,
2050            "capable"
2051        );
2052        assert_eq!(
2053            selected(&policy, Some(&verdict(0.6, "unsupported", "LIM-1")))?,
2054            "efficient"
2055        );
2056        Ok(())
2057    }
2058
2059    #[test]
2060    fn unmatched_steps_raise_only_the_unmatched_threshold() -> Result<()> {
2061        let policy = TaskClassifierPolicy::new(&LlmCapabilityConfig {
2062            threshold_step: 0.1,
2063            unmatched_steps: 2,
2064            ..llm_config(0.75)
2065        });
2066
2067        // 0.85 clears one step but not two: unmatched now routes to the capable target.
2068        assert_eq!(
2069            selected(&policy, Some(&verdict(0.85, "unmatched", "none")))?,
2070            "capable"
2071        );
2072        assert_eq!(
2073            selected(&policy, Some(&verdict(0.95, "unmatched", "none")))?,
2074            "efficient"
2075        );
2076        // Other boundaries keep their steps.
2077        assert_eq!(
2078            selected(&policy, Some(&verdict(0.85, "uncertain", "UNC-1")))?,
2079            "efficient"
2080        );
2081        assert_eq!(
2082            selected(&policy, Some(&verdict(0.75, "supported", "SUP-2")))?,
2083            "efficient"
2084        );
2085        Ok(())
2086    }
2087
2088    #[test]
2089    fn unmatched_steps_default_to_one_and_reject_values_above_two() {
2090        let parsed: TaskClassifierConfig =
2091            serde_json::from_value(serde_json::json!({ "base_threshold": 0.5 }))
2092                .expect("config without unmatched_steps parses");
2093        let CapabilityJudgeConfig::Llm(judge) = &parsed.judge else {
2094            panic!("a flat capability config builds an LLM judge");
2095        };
2096        assert_eq!(judge.unmatched_steps, 1);
2097
2098        let invalid = TaskClassifierConfig {
2099            judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig {
2100                unmatched_steps: 3,
2101                ..llm_config(0.5)
2102            }),
2103            ..TaskClassifierConfig::default()
2104        };
2105        assert!(invalid.validate().is_err());
2106    }
2107
2108    /// The text of each message a judge with `recent_turn_window` would be sent.
2109    /// The no-window case is covered by `capability_judge_builds_a_structured_request`.
2110    fn capability_judge(recent_turn_window: Option<usize>) -> Result<CapabilityJudge> {
2111        Ok(StructuredJudge::new(
2112            TaskInput { recent_turn_window },
2113            LlmTaskClassifier::load_capability_contract(&ClassifierContractConfig::default())?,
2114            SerdeDecoder::new(),
2115            JudgeRuntimeConfig::new(DEFAULT_JUDGE_MAX_OUTPUT_TOKENS)?,
2116        ))
2117    }
2118
2119    fn judged_contents(recent_turn_window: usize) -> Result<Vec<String>> {
2120        let judge = capability_judge(Some(recent_turn_window))?;
2121        let request = Request {
2122            llm_request: LlmRequest {
2123                messages: vec![
2124                    Message::text(Role::System, "client instructions"),
2125                    Message::text(
2126                        Role::User,
2127                        "<environment_context>setup</environment_context>",
2128                    ),
2129                    Message::text(Role::User, "initial task"),
2130                    Message::text(Role::Assistant, "old response"),
2131                    Message::text(Role::User, "old follow-up"),
2132                    Message::text(Role::Assistant, "recent 1"),
2133                    Message::text(Role::User, "recent 2"),
2134                ],
2135                ..LlmRequest::default()
2136            },
2137            raw_request: None,
2138            metadata: None,
2139        };
2140        Ok(judge
2141            .build_request(&State::default(), &request)
2142            .llm_request
2143            .messages
2144            .iter()
2145            .filter_map(|message| message.text_content("\n"))
2146            .collect())
2147    }
2148
2149    #[test]
2150    fn a_window_widens_the_judge_to_the_surrounding_conversation() -> Result<()> {
2151        // Client instructions and the opening task, plus the last two turns.
2152        let contents = judged_contents(2)?;
2153        assert!(contents.contains(&"client instructions".to_string()));
2154        assert!(contents.contains(&"initial task".to_string()));
2155        assert!(contents.contains(&"recent 1".to_string()));
2156        assert!(contents.contains(&"recent 2".to_string()));
2157        assert!(!contents.contains(&"old response".to_string()));
2158        Ok(())
2159    }
2160
2161    #[test]
2162    fn a_zero_window_keeps_only_the_instructions_and_the_task() -> Result<()> {
2163        let contents = judged_contents(0)?;
2164        assert!(contents.contains(&"client instructions".to_string()));
2165        assert!(contents.contains(&"initial task".to_string()));
2166        assert!(!contents.contains(&"recent 2".to_string()));
2167        Ok(())
2168    }
2169
2170    fn tool_call(id: &str) -> Message {
2171        Message::new(
2172            Role::Assistant,
2173            vec![ContentBlock::ToolCall(ToolCall {
2174                id: id.to_string(),
2175                name: "search".to_string(),
2176                arguments: Value::Null,
2177            })],
2178        )
2179    }
2180
2181    fn tool_result(id: &str) -> Message {
2182        Message::new(
2183            Role::Tool,
2184            vec![ContentBlock::ToolResult(ToolResult {
2185                tool_call_id: id.to_string(),
2186                content: vec![ContentBlock::Text {
2187                    text: "tool output".to_string(),
2188                }],
2189                is_error: None,
2190            })],
2191        )
2192    }
2193
2194    #[test]
2195    fn default_task_input_keeps_user_content_around_tool_results() {
2196        let context = Message::text(
2197            Role::User,
2198            "<environment_context><current_date>2026-10-31</current_date></environment_context>",
2199        );
2200        let mut result = tool_result("call-1");
2201        result.role = Role::User;
2202        let mut mixed = result.clone();
2203        mixed.content.push(ContentBlock::Text {
2204            text: "latest follow-up".to_string(),
2205        });
2206        let input = TaskInput {
2207            recent_turn_window: None,
2208        };
2209        let mut request = Request {
2210            llm_request: LlmRequest {
2211                messages: vec![
2212                    context.clone(),
2213                    result.clone(),
2214                    Message::text(Role::User, "initial task"),
2215                    tool_call("call-1"),
2216                    mixed,
2217                    result.clone(),
2218                    context,
2219                ],
2220                ..LlmRequest::default()
2221            },
2222            ..Request::default()
2223        };
2224        assert_eq!(
2225            input.build_messages(&State::default(), &request),
2226            vec![
2227                Message::text(Role::User, "initial task"),
2228                Message::text(Role::User, "latest follow-up"),
2229            ]
2230        );
2231        request.llm_request.messages = vec![result];
2232        assert!(input.build_messages(&State::default(), &request).is_empty());
2233    }
2234
2235    /// A count-based window can begin on a tool result, which leaves the call that
2236    /// introduced its id outside the window and the classifier history invalid.
2237    #[test]
2238    fn trimming_keeps_the_call_that_introduced_a_kept_tool_result() {
2239        let messages = vec![
2240            Message::text(Role::System, "client instructions"),
2241            Message::text(Role::User, "initial task"),
2242            Message::text(Role::Assistant, "old response"),
2243            tool_call("call-1"),
2244            tool_result("call-1"),
2245            Message::text(Role::Assistant, "recent 1"),
2246            Message::text(Role::User, "recent 2"),
2247            Message::text(Role::Assistant, "recent 3"),
2248            Message::text(Role::User, "recent 4"),
2249        ];
2250
2251        // The five-message tail begins exactly on the tool result.
2252        let kept = trim_messages(&messages, 5);
2253
2254        assert_eq!(
2255            kept,
2256            vec![
2257                Message::text(Role::System, "client instructions"),
2258                Message::text(Role::User, "initial task"),
2259                tool_call("call-1"),
2260                tool_result("call-1"),
2261                Message::text(Role::Assistant, "recent 1"),
2262                Message::text(Role::User, "recent 2"),
2263                Message::text(Role::Assistant, "recent 3"),
2264                Message::text(Role::User, "recent 4"),
2265            ]
2266        );
2267    }
2268
2269    /// Ids repeat across a conversation, so a later call must not stand in for the one that
2270    /// answers an earlier result.
2271    #[test]
2272    fn trimming_pairs_a_repeated_id_with_the_call_that_precedes_it() {
2273        let messages = vec![
2274            Message::text(Role::System, "client instructions"),
2275            Message::text(Role::User, "initial task"),
2276            tool_call("x"),
2277            tool_result("x"),
2278            Message::text(Role::Assistant, "later"),
2279            tool_call("x"),
2280            tool_result("x"),
2281        ];
2282
2283        // The four-message tail begins on the first result, whose own call sits one earlier.
2284        let kept = trim_messages(&messages, 4);
2285
2286        assert_eq!(
2287            kept,
2288            vec![
2289                Message::text(Role::System, "client instructions"),
2290                Message::text(Role::User, "initial task"),
2291                tool_call("x"),
2292                tool_result("x"),
2293                Message::text(Role::Assistant, "later"),
2294                tool_call("x"),
2295                tool_result("x"),
2296            ]
2297        );
2298    }
2299
2300    /// A result whose call precedes the opening task can never be paired, because trimming
2301    /// never reaches behind the task. The window must not widen hunting for it.
2302    #[test]
2303    fn trimming_keeps_the_counted_window_when_a_result_cannot_be_paired() {
2304        let messages = vec![
2305            Message::text(Role::System, "client instructions"),
2306            tool_call("orphan"),
2307            Message::text(Role::User, "initial task"),
2308            Message::text(Role::Assistant, "old response"),
2309            tool_result("orphan"),
2310            Message::text(Role::Assistant, "recent 1"),
2311            Message::text(Role::User, "recent 2"),
2312        ];
2313
2314        let kept = trim_messages(&messages, 3);
2315
2316        assert_eq!(
2317            kept,
2318            vec![
2319                Message::text(Role::System, "client instructions"),
2320                Message::text(Role::User, "initial task"),
2321                tool_result("orphan"),
2322                Message::text(Role::Assistant, "recent 1"),
2323                Message::text(Role::User, "recent 2"),
2324            ]
2325        );
2326    }
2327
2328    #[test]
2329    fn a_window_restates_the_routing_instruction_last() -> Result<()> {
2330        let contents = judged_contents(2)?;
2331
2332        // Last, not merely present: the instruction only works in final position,
2333        // after the conversation content it is meant to outrank.
2334        assert_eq!(
2335            contents.last().map(String::as_str),
2336            Some(TRAILING_ROUTING_INSTRUCTION)
2337        );
2338        Ok(())
2339    }
2340
2341    /// Reasoning is provider-private and some upstreams reject it replayed without the
2342    /// opaque state it was issued with, so it must not reach a windowed classifier
2343    /// request. Visible assistant text and complete tool pairs still do, and a turn
2344    /// whose only content was reasoning is dropped rather than left behind empty.
2345    #[test]
2346    fn a_window_drops_reasoning_but_keeps_visible_text_and_tool_pairs() {
2347        let messages = vec![
2348            Message::text(Role::System, "client instructions"),
2349            Message::text(Role::User, "initial task"),
2350            Message::new(
2351                Role::Assistant,
2352                vec![
2353                    ContentBlock::Reasoning {
2354                        text: "private chain of thought".to_string(),
2355                        signature: None,
2356                        details: Vec::new(),
2357                    },
2358                    ContentBlock::Text {
2359                        text: "visible answer".to_string(),
2360                    },
2361                ],
2362            ),
2363            tool_call("call-1"),
2364            tool_result("call-1"),
2365            Message::new(
2366                Role::Assistant,
2367                vec![ContentBlock::Reasoning {
2368                    text: "reasoning-only turn".to_string(),
2369                    signature: None,
2370                    details: Vec::new(),
2371                }],
2372            ),
2373            Message::text(Role::User, "follow-up"),
2374        ];
2375        let request = Request {
2376            llm_request: LlmRequest {
2377                messages,
2378                ..LlmRequest::default()
2379            },
2380            raw_request: None,
2381            metadata: None,
2382        };
2383
2384        let built = TaskInput {
2385            recent_turn_window: Some(10),
2386        }
2387        .build_messages(&State::default(), &request);
2388
2389        assert!(
2390            !built
2391                .iter()
2392                .flat_map(|message| &message.content)
2393                .any(|block| matches!(block, ContentBlock::Reasoning { .. })),
2394            "{built:?}"
2395        );
2396        assert!(
2397            built
2398                .iter()
2399                .any(|message| message.text_content("\n").as_deref() == Some("visible answer"))
2400        );
2401        assert!(built.contains(&tool_call("call-1")));
2402        assert!(built.contains(&tool_result("call-1")));
2403        // Six of the seven fixtures survive — the reasoning-only turn is gone entirely
2404        // rather than left behind empty — plus the trailing routing instruction.
2405        assert_eq!(built.len(), 7);
2406        assert!(built.iter().all(|message| !message.content.is_empty()));
2407    }
2408
2409    #[test]
2410    fn a_window_drops_a_turn_left_empty_once_its_reasoning_is_removed() {
2411        // OpenAI Chat decoding places an empty text placeholder beside the reasoning of
2412        // an assistant message that carries `reasoning_content` alone. Removing the
2413        // reasoning has to take the placeholder with it: an Anthropic judge rejects a
2414        // message whose text is empty, and the whole client request then fails.
2415        let body = serde_json::json!({
2416            "model": "qa/windowed",
2417            "messages": [
2418                {"role": "user", "content": "Reply with the number four."},
2419                {"role": "assistant", "reasoning_content": "private chain of thought"},
2420                {"role": "user", "content": "This is still a simple number lookup."}
2421            ]
2422        });
2423        let request = Request {
2424            llm_request: switchyard_translation::decode_request(
2425                switchyard_translation::WireFormat::OpenAiChat,
2426                &body,
2427            )
2428            .expect("client request decodes"),
2429            ..Request::default()
2430        };
2431
2432        let built = TaskInput {
2433            recent_turn_window: Some(8),
2434        }
2435        .build_messages(&State::default(), &request);
2436
2437        assert_eq!(
2438            built,
2439            vec![
2440                Message::text(Role::User, "Reply with the number four."),
2441                Message::text(Role::User, "This is still a simple number lookup."),
2442                Message::text(Role::User, TRAILING_ROUTING_INSTRUCTION),
2443            ]
2444        );
2445        let judge_request = LlmRequest {
2446            messages: built,
2447            ..LlmRequest::default()
2448        };
2449        let encoded = switchyard_translation::encode_request(
2450            &judge_request,
2451            switchyard_translation::WireFormat::AnthropicMessages,
2452        )
2453        .expect("judge request encodes");
2454        let has_empty_text = encoded["messages"]
2455            .as_array()
2456            .expect("messages")
2457            .iter()
2458            .flat_map(|message| match &message["content"] {
2459                Value::Array(blocks) => blocks.iter().map(|block| &block["text"]).collect(),
2460                content => vec![content],
2461            })
2462            .any(|text| text.as_str().is_some_and(str::is_empty));
2463        assert!(!has_empty_text, "{encoded}");
2464    }
2465
2466    #[test]
2467    fn the_default_path_is_left_unchanged() -> Result<()> {
2468        // No window means no conversation to be distracted by, so the default
2469        // request shape stays exactly as it was.
2470        let judge = capability_judge(None)?;
2471        let request = Request {
2472            llm_request: LlmRequest {
2473                messages: vec![Message::text(Role::User, "the task")],
2474                ..LlmRequest::default()
2475            },
2476            raw_request: None,
2477            metadata: None,
2478        };
2479
2480        let built = judge.build_request(&State::default(), &request);
2481
2482        // The task message alone; the rubric reaches the judge as an instruction block
2483        // rather than a message, so nothing was dropped by it not being counted here.
2484        assert_eq!(built.llm_request.messages.len(), 1);
2485        assert!(!built.llm_request.instructions.is_empty());
2486        assert!(
2487            !built
2488                .llm_request
2489                .messages
2490                .iter()
2491                .filter_map(|message| message.text_content("\n"))
2492                .any(|text| text.contains(TRAILING_ROUTING_INSTRUCTION))
2493        );
2494        Ok(())
2495    }
2496
2497    #[test]
2498    fn capability_judge_builds_a_structured_request() -> Result<()> {
2499        let judge = capability_judge(None)?;
2500        let request = Request {
2501            llm_request: LlmRequest {
2502                model: Some("inbound".to_string()),
2503                messages: vec![
2504                    Message::text(Role::System, "client instructions"),
2505                    Message::text(Role::Developer, "client developer instructions"),
2506                    Message::text(Role::User, "initial task"),
2507                    Message::text(Role::Assistant, "old response"),
2508                    Message::text(Role::User, "old follow-up"),
2509                    Message::text(Role::Assistant, "recent 1"),
2510                    Message::text(Role::User, "recent 2"),
2511                    Message::text(Role::Assistant, "recent 3"),
2512                    Message::text(Role::User, "recent 4"),
2513                    Message::text(Role::Assistant, "recent 5"),
2514                ],
2515                ..LlmRequest::default()
2516            },
2517            raw_request: None,
2518            metadata: None,
2519        };
2520        let judge_request = judge.build_request(&State::default(), &request);
2521
2522        assert_eq!(judge_request.llm_request.model, request.llm_request.model);
2523        assert_eq!(judge_request.llm_request.instructions.len(), 1);
2524        assert_eq!(judge_request.llm_request.instructions[0].role, Role::System);
2525        assert_eq!(
2526            judge_request.llm_request.instructions[0].content,
2527            InstructionBlock {
2528                role: Role::System,
2529                content: Message::text(Role::System, judge.contract().system_prompt()).content,
2530            }
2531            .content,
2532        );
2533        assert_eq!(judge_request.llm_request.messages.len(), 2);
2534        let contents = judge_request
2535            .llm_request
2536            .messages
2537            .iter()
2538            .filter_map(|message| message.text_content("\n"))
2539            .collect::<Vec<_>>();
2540        assert!(contents.contains(&"recent 4".to_string()));
2541        assert!(contents.contains(&"initial task".to_string()));
2542        assert!(!contents.contains(&"recent 5".to_string()));
2543        assert!(!contents.contains(&"client instructions".to_string()));
2544        assert_eq!(
2545            judge_request.llm_request.output.response_format,
2546            Some(judge.contract().response_format().clone())
2547        );
2548        assert_eq!(
2549            judge_request.llm_request.output.max_output_tokens,
2550            Some(DEFAULT_JUDGE_MAX_OUTPUT_TOKENS)
2551        );
2552        Ok(())
2553    }
2554
2555    fn sample_value(spec: &Value) -> Value {
2556        if let Some(first) = spec
2557            .get("enum")
2558            .and_then(Value::as_array)
2559            .and_then(|values| values.first())
2560        {
2561            return first.clone();
2562        }
2563        match spec.get("type").and_then(Value::as_str) {
2564            Some("number") => serde_json::json!(0.5),
2565            Some("boolean") => serde_json::json!(false),
2566            _ => serde_json::json!("sample"),
2567        }
2568    }
2569
2570    fn schema_shaped_verdict(schema: &Value) -> Result<String> {
2571        let properties = schema
2572            .pointer("/json_schema/schema/properties")
2573            .and_then(Value::as_object)
2574            .ok_or_else(|| LibsyError::AlgorithmError {
2575                message: "packaged schema declares no properties".to_string(),
2576            })?;
2577        Ok(Value::Object(
2578            properties
2579                .iter()
2580                .map(|(name, spec)| (name.clone(), sample_value(spec)))
2581                .collect(),
2582        )
2583        .to_string())
2584    }
2585
2586    /// Built from the schema so a property added there fails here rather than silently
2587    /// rejecting every production verdict.
2588    #[test]
2589    fn every_schema_property_round_trips_through_the_judge_parser() -> Result<()> {
2590        let contract =
2591            LlmTaskClassifier::load_capability_contract(&ClassifierContractConfig::default())?;
2592        let schema = contract.response_format();
2593        let reply = schema_shaped_verdict(schema)?;
2594        let judge: CapabilityJudge = StructuredJudge::new(
2595            TaskInput {
2596                recent_turn_window: None,
2597            },
2598            contract,
2599            SerdeDecoder::new(),
2600            JudgeRuntimeConfig::new(DEFAULT_JUDGE_MAX_OUTPUT_TOKENS)?,
2601        );
2602
2603        let verdict = judge.parse(&text_response(None, reply))?;
2604
2605        assert!(verdict.is_valid());
2606        assert!((0.0..=1.0).contains(&verdict.p_solve));
2607        Ok(())
2608    }
2609
2610    #[test]
2611    fn packaged_prompt_keeps_the_schema_in_the_structured_request() -> Result<()> {
2612        let contract =
2613            LlmTaskClassifier::load_capability_contract(&ClassifierContractConfig::default())?;
2614        let prompt = contract.system_prompt();
2615        let schema_name = contract
2616            .response_format()
2617            .pointer("/json_schema/name")
2618            .and_then(Value::as_str)
2619            .ok_or_else(|| LibsyError::AlgorithmError {
2620                message: "packaged response schema has no name".to_string(),
2621            })?;
2622        assert_eq!(schema_name, "CapabilityClassifierDecision");
2623        assert!(prompt.contains("SUP-1 [supported]"));
2624        assert!(prompt.contains("SUP-5 [supported]"));
2625        assert!(!prompt.contains("{{RESPONSE_SCHEMA}}"));
2626        assert!(!prompt.contains("\"type\": \"object\""));
2627        assert!(!prompt.contains("\"json_schema\""));
2628        assert!(!prompt.contains(schema_name));
2629        let rule_values = contract
2630            .response_format()
2631            .pointer("/json_schema/schema/properties/primary_rule/enum")
2632            .and_then(Value::as_array)
2633            .ok_or_else(|| LibsyError::AlgorithmError {
2634                message: "rendered response schema has no primary rule enum".to_string(),
2635            })?;
2636        assert!(
2637            rule_values
2638                .iter()
2639                .any(|value| value.as_str() == Some("SUP-1"))
2640        );
2641        assert!(
2642            rule_values
2643                .iter()
2644                .any(|value| value.as_str() == Some("none"))
2645        );
2646        Ok(())
2647    }
2648}