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