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