Skip to main content

lean_ctx/proxy/
effort_routing.rs

1//! Per-turn effort routing (#1148, opt-in dynamic thinking budget).
2//!
3//! Unlike the static `effort.rs` which applies a constant reasoning level
4//! across all turns (for cache stability), this module classifies each turn
5//! and adjusts thinking effort dynamically.
6//!
7//! **Opt-in only** (`proxy.effort_routing = true`). When disabled, the static
8//! `effort.rs` path remains the sole controller. When enabled, this module
9//! overrides the static level with a per-turn classification.
10//!
11//! ## Cache stability tradeoff
12//!
13//! Provider prompt caches (Anthropic `cache_control`, OpenAI prefix caching)
14//! break when reasoning parameters change. This module accepts that tradeoff
15//! because:
16//! 1. Output tokens on Opus-class models cost **5x** input tokens — savings
17//!    from reduced thinking often exceed the cache-miss penalty.
18//! 2. Routine turns (file reads, passing tests) generate disproportionate
19//!    thinking waste for trivial tool-result acknowledgements.
20//! 3. The module uses a **two-level** strategy (not N levels) to minimize cache
21//!    key diversity: `routine` or `full` — only two cache prefixes to warm.
22//!
23//! ## Classification
24//!
25//! A turn is classified as **routine** when the last assistant message was a
26//! tool call and the tool result indicates success on a non-complex operation:
27//! - File read (tool_use with `ctx_read`, `read_file`, `Read`)
28//! - Successful shell command (exit_code == 0, no error indicators)
29//! - Search results (grep/glob/find)
30//! - Status checks (git status, test passing)
31//!
32//! A turn is classified as **full** (keep maximum thinking) when:
33//! - The user sent a new message (requires understanding intent)
34//! - The tool result contains errors/failures
35//! - Multiple tool results arrived (complex multi-step)
36//! - The content is architecturally complex (refactoring, debugging)
37
38use serde_json::Value;
39use std::sync::atomic::{AtomicU64, Ordering};
40
41use crate::core::config::Effort;
42
43/// Turn classification result.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum TurnClass {
46    /// Routine tool-result acknowledgement — minimize thinking.
47    Routine,
48    /// Full complexity — keep maximum thinking effort.
49    Full,
50}
51
52/// Statistics for monitoring effort routing effectiveness.
53#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
54pub struct RoutingStats {
55    pub routine_count: u64,
56    pub full_count: u64,
57}
58
59static ESTIMATED_OUTPUT_TOKENS_WITHOUT_ROUTING: AtomicU64 = AtomicU64::new(0);
60static ACTUAL_EFFORT_BUDGET_TOKENS: AtomicU64 = AtomicU64::new(0);
61
62#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
63pub struct EffortSavingsStats {
64    pub estimated_output_tokens_without_routing: u64,
65    pub actual_effort_budget_tokens: u64,
66}
67
68static ROUTINE_COUNT: AtomicU64 = AtomicU64::new(0);
69static FULL_COUNT: AtomicU64 = AtomicU64::new(0);
70
71/// Classify the current turn based on the message array.
72/// Returns `Routine` if the latest context is a simple tool-result
73/// acknowledgement, `Full` otherwise.
74pub fn classify_turn(messages: &Value) -> TurnClass {
75    let Some(arr) = messages.as_array() else {
76        return TurnClass::Full;
77    };
78
79    if arr.is_empty() {
80        return TurnClass::Full;
81    }
82
83    let last = &arr[arr.len() - 1];
84    let role = last.get("role").and_then(Value::as_str).unwrap_or("");
85
86    if role == "tool" {
87        classify_tool_result(last, arr)
88    } else {
89        TurnClass::Full
90    }
91}
92
93/// Classify based on OpenAI Responses API `input` array (different structure).
94pub fn classify_turn_responses(input: &Value) -> TurnClass {
95    let Some(arr) = input.as_array() else {
96        return TurnClass::Full;
97    };
98    if arr.is_empty() {
99        return TurnClass::Full;
100    }
101
102    // In Responses API, look for the last item's type.
103    let last = &arr[arr.len() - 1];
104    let item_type = last.get("type").and_then(Value::as_str).unwrap_or("");
105
106    if item_type == "function_call_output" {
107        let output = last.get("output").and_then(Value::as_str).unwrap_or("");
108        if is_routine_tool_output(output) {
109            return TurnClass::Routine;
110        }
111    }
112
113    TurnClass::Full
114}
115
116/// Classify based on Anthropic messages structure.
117pub fn classify_turn_anthropic(messages: &Value) -> TurnClass {
118    let Some(arr) = messages.as_array() else {
119        return TurnClass::Full;
120    };
121    if arr.is_empty() {
122        return TurnClass::Full;
123    }
124
125    let last = &arr[arr.len() - 1];
126    let role = last.get("role").and_then(Value::as_str).unwrap_or("");
127
128    if role != "user" {
129        return TurnClass::Full;
130    }
131
132    // Anthropic puts tool_results in user messages with content array.
133    let content = last.get("content");
134    if let Some(Value::Array(blocks)) = content {
135        let all_tool_results = !blocks.is_empty()
136            && blocks
137                .iter()
138                .all(|b| b.get("type").and_then(Value::as_str) == Some("tool_result"));
139
140        if all_tool_results {
141            // Check if any tool result has errors.
142            let has_errors = blocks.iter().any(|b| {
143                b.get("is_error") == Some(&Value::Bool(true))
144                    || b.get("content")
145                        .and_then(|c| c.as_str().or_else(|| extract_text_from_content(c)))
146                        .is_some_and(contains_error_indicators)
147            });
148
149            if has_errors {
150                return TurnClass::Full;
151            }
152
153            // Multiple tool results → likely complex multi-step.
154            if blocks.len() > 3 {
155                return TurnClass::Full;
156            }
157
158            // Check individual results.
159            let all_routine = blocks.iter().all(|b| {
160                let text = b
161                    .get("content")
162                    .and_then(|c| c.as_str().or_else(|| extract_text_from_content(c)))
163                    .unwrap_or("");
164                is_routine_tool_output(text)
165            });
166
167            if all_routine {
168                return TurnClass::Routine;
169            }
170        }
171    }
172
173    TurnClass::Full
174}
175
176/// Map a turn classification to the effort level to apply.
177/// `base` is the operator's configured static effort level.
178pub fn effort_for_turn(class: TurnClass, base: Effort) -> Effort {
179    match class {
180        TurnClass::Routine => {
181            ROUTINE_COUNT.fetch_add(1, Ordering::Relaxed);
182            // Routine turns get minimal thinking regardless of base.
183            Effort::Minimal
184        }
185        TurnClass::Full => {
186            FULL_COUNT.fetch_add(1, Ordering::Relaxed);
187            base
188        }
189    }
190}
191
192/// Adjust effort from a classifier intent while preserving the configured
193/// effort for intents that are not clearly simple reads or coding work.
194pub fn intent_aware_effort(intent: &str, base_effort: Effort) -> Effort {
195    let intent = intent.to_ascii_lowercase();
196    if [
197        "code",
198        "coding",
199        "fix",
200        "implement",
201        "refactor",
202        "debug",
203        "build",
204        "patch",
205        "test",
206    ]
207    .iter()
208    .any(|term| intent.contains(term))
209    {
210        Effort::High
211    } else if [
212        "read",
213        "list",
214        "show",
215        "explain",
216        "summarize",
217        "status",
218        "search",
219        "lookup",
220    ]
221    .iter()
222    .any(|term| intent.contains(term))
223    {
224        Effort::Minimal
225    } else {
226        base_effort
227    }
228}
229
230/// Snapshot routing statistics.
231pub fn stats() -> RoutingStats {
232    RoutingStats {
233        routine_count: ROUTINE_COUNT.load(Ordering::Relaxed),
234        full_count: FULL_COUNT.load(Ordering::Relaxed),
235    }
236}
237
238pub fn effort_savings_stats() -> EffortSavingsStats {
239    EffortSavingsStats {
240        estimated_output_tokens_without_routing: ESTIMATED_OUTPUT_TOKENS_WITHOUT_ROUTING
241            .load(Ordering::Relaxed),
242        actual_effort_budget_tokens: ACTUAL_EFFORT_BUDGET_TOKENS.load(Ordering::Relaxed),
243    }
244}
245
246/// Dynamic reasoning budget selected from the current request context.
247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
248pub struct TaskComplexity {
249    pub score: u8,
250    pub effort: Effort,
251    pub budget_tokens: u32,
252}
253
254impl TaskComplexity {
255    pub const fn from_score(score: u8) -> Self {
256        match score {
257            1 => Self {
258                score: 1,
259                effort: Effort::Low,
260                budget_tokens: 1_024,
261            },
262            2 => Self {
263                score: 2,
264                effort: Effort::Low,
265                budget_tokens: 2_048,
266            },
267            3 => Self {
268                score: 3,
269                effort: Effort::Medium,
270                budget_tokens: 4_096,
271            },
272            4 => Self {
273                score: 4,
274                effort: Effort::High,
275                budget_tokens: 8_192,
276            },
277            _ => Self {
278                score: 5,
279                effort: Effort::High,
280                budget_tokens: 16_384,
281            },
282        }
283    }
284}
285
286/// Scores request complexity on a stable 1–5 scale.
287pub fn score_complexity(messages: &[Value]) -> u8 {
288    let user_text = messages
289        .iter()
290        .rev()
291        .find(|message| message.get("role").and_then(Value::as_str) == Some("user"))
292        .and_then(|message| {
293            extract_text_from_content(message.get("content").unwrap_or(&Value::Null))
294        })
295        .unwrap_or_default();
296    let text = user_text.to_ascii_lowercase();
297    let file_mentions = count_file_mentions(&text);
298    let has_errors = messages.iter().any(message_has_error);
299    let critical = ["security", "vulnerability", "production", "incident", "cve"]
300        .iter()
301        .any(|marker| text.contains(marker));
302    let complex = ["debug", "architecture", "refactor", "design"]
303        .iter()
304        .any(|marker| text.contains(marker));
305
306    if critical {
307        5
308    } else if has_errors || complex {
309        4
310    } else if file_mentions >= 2 || user_text.len() > 1_200 || text.contains("test") {
311        3
312    } else if file_mentions == 1 || user_text.len() > 300 {
313        2
314    } else {
315        1
316    }
317}
318
319/// Scores and mutates a provider request in one step for proxy handlers.
320pub fn route_effort_budget(body: &mut Value) -> TaskComplexity {
321    let complexity = body
322        .get("messages")
323        .or_else(|| body.get("input"))
324        .and_then(Value::as_array)
325        .map_or(1, |messages| score_complexity(messages));
326    apply_effort_budget(body, complexity)
327}
328
329/// Whether an Anthropic model accepts the `thinking` parameter with a fixed
330/// `budget_tokens`, the form this module injects.
331///
332/// The list is deliberately narrow and fails **closed**: unknown models get no
333/// injection rather than risk a 400 from a model whose capabilities we guessed
334/// wrong. Ineligible families:
335/// - `claude-3-opus`/`claude-3-sonnet`/`claude-3-haiku`/`claude-3-5-haiku` have
336///   no extended thinking at all.
337/// - Opus/Sonnet 4.6+ and the 5-generation models reject `budget_tokens` (400);
338///   they take `thinking: {type: "adaptive"}` plus `output_config.effort`.
339fn anthropic_supports_thinking(model: &str) -> bool {
340    let bare = model.rsplit('/').next().unwrap_or(model);
341    let budget_token_families = [
342        "claude-3-5-sonnet",
343        "claude-3-7-sonnet",
344        "claude-3.5-sonnet",
345        "claude-3.7-sonnet",
346        "claude-sonnet-4-5",
347        "claude-opus-4-5",
348        "claude-haiku-4-5",
349        "claude-4-5",           // alias form (claude-4-5-sonnet / -haiku)
350        "claude-sonnet-4-2025", // dated snapshot (claude-sonnet-4-20250514)
351        "claude-opus-4-2025",   // dated snapshot (claude-opus-4-20250514)
352    ];
353    budget_token_families
354        .iter()
355        .any(|family| bare.starts_with(family))
356        // Bare launch-model ids that predate the 4.6+ adaptive-only era.
357        || bare == "claude-sonnet-4"
358        || bare == "claude-opus-4"
359}
360
361/// Calculates complexity for a request and applies its provider-native effort budget.
362pub fn apply_effort_budget(body: &mut Value, complexity: u8) -> TaskComplexity {
363    let task = TaskComplexity::from_score(complexity);
364    let Some(object) = body.as_object_mut() else {
365        return task;
366    };
367
368    let model = object
369        .get("model")
370        .and_then(Value::as_str)
371        .unwrap_or_default();
372    let is_anthropic = object.contains_key("messages")
373        && (object.contains_key("max_tokens") || model.contains("claude"));
374    if is_anthropic && anthropic_supports_thinking(model) {
375        // Don't overwrite client-set thinking params
376        if object.get("thinking").is_none() {
377            let thinking = object
378                .entry("thinking")
379                .or_insert_with(|| Value::Object(serde_json::Map::new()));
380            if let Some(thinking) = thinking.as_object_mut() {
381                thinking.insert("type".into(), Value::String("enabled".into()));
382                thinking.insert("budget_tokens".into(), Value::from(task.budget_tokens));
383            }
384        }
385    } else if crate::proxy::effort::openai_supports_effort(model) {
386        if object.contains_key("reasoning_effort") {
387            object.insert(
388                "reasoning_effort".into(),
389                Value::String(openai_effort_value(task.effort).into()),
390            );
391        } else {
392            let reasoning = object
393                .entry("reasoning")
394                .or_insert_with(|| Value::Object(serde_json::Map::new()));
395            if let Some(reasoning) = reasoning.as_object_mut() {
396                reasoning.insert(
397                    "effort".into(),
398                    Value::String(openai_effort_value(task.effort).into()),
399                );
400            }
401        }
402    }
403    ESTIMATED_OUTPUT_TOKENS_WITHOUT_ROUTING.fetch_add(16_384, Ordering::Relaxed);
404    ACTUAL_EFFORT_BUDGET_TOKENS.fetch_add(task.budget_tokens.into(), Ordering::Relaxed);
405    task
406}
407
408fn openai_effort_value(effort: Effort) -> &'static str {
409    match effort {
410        Effort::Minimal | Effort::Low => "low",
411        Effort::Medium => "medium",
412        Effort::High => "high",
413    }
414}
415
416#[cfg(test)]
417mod output_token_intelligence_tests {
418    use super::*;
419    use serde_json::json;
420
421    #[test]
422    fn trivial_task_gets_low_effort() {
423        let messages = vec![json!({"role": "user", "content": "Read src/lib.rs"})];
424        assert_eq!(score_complexity(&messages), 2);
425        assert_eq!(TaskComplexity::from_score(1).budget_tokens, 1_024);
426    }
427
428    #[test]
429    fn complex_task_gets_high_effort() {
430        let messages =
431            vec![json!({"role": "user", "content": "Design the architecture for this refactor"})];
432        let task = TaskComplexity::from_score(score_complexity(&messages));
433        assert_eq!(task.score, 4);
434        assert_eq!(task.effort, Effort::High);
435    }
436
437    #[test]
438    fn error_presence_increases_complexity() {
439        let messages = vec![
440            json!({"role": "tool", "content": "error[E0308]: mismatched types"}),
441            json!({"role": "user", "content": "fix this"}),
442        ];
443        assert_eq!(score_complexity(&messages), 4);
444    }
445
446    #[test]
447    fn applies_anthropic_thinking_budget() {
448        let mut body = json!({"model": "claude-sonnet-4", "max_tokens": 4096, "messages": []});
449        let task = apply_effort_budget(&mut body, 4);
450        assert_eq!(task.budget_tokens, 8_192);
451        assert_eq!(body["thinking"]["budget_tokens"], 8_192);
452    }
453
454    #[test]
455    fn skips_thinking_for_unsupported_models() {
456        let mut body = json!({"model": "claude-sonnet-5", "max_tokens": 4096, "messages": []});
457        let task = apply_effort_budget(&mut body, 4);
458        assert_eq!(task.budget_tokens, 8_192);
459        assert!(
460            body.get("thinking").is_none(),
461            "sonnet-5 must not get thinking params"
462        );
463    }
464
465    #[test]
466    fn skips_thinking_for_openrouter_wrapped_unsupported() {
467        let mut body =
468            json!({"model": "anthropic/claude-sonnet-5", "max_tokens": 4096, "messages": []});
469        apply_effort_budget(&mut body, 4);
470        assert!(
471            body.get("thinking").is_none(),
472            "openrouter-wrapped sonnet-5 must not get thinking"
473        );
474    }
475
476    #[test]
477    fn preserves_client_thinking_params() {
478        let mut body = json!({
479            "model": "claude-sonnet-4",
480            "thinking": {"type": "adaptive"},
481            "messages": []
482        });
483        apply_effort_budget(&mut body, 4);
484        assert_eq!(
485            body["thinking"]["type"], "adaptive",
486            "must not overwrite client thinking"
487        );
488        assert!(
489            body["thinking"].get("budget_tokens").is_none(),
490            "must not inject budget_tokens"
491        );
492    }
493
494    #[test]
495    fn skips_thinking_for_adaptive_only_models() {
496        // Opus/Sonnet 4.6+ and the 5-generation reject `budget_tokens` with a
497        // 400 — never inject, even though these models do support thinking.
498        for model in [
499            "claude-opus-4-6",
500            "claude-opus-4-7",
501            "claude-opus-4-8",
502            "claude-sonnet-4-6",
503            "claude-sonnet-5",
504            "claude-opus-5",
505            "claude-fable-5",
506        ] {
507            let mut body = json!({"model": model, "max_tokens": 4096, "messages": []});
508            apply_effort_budget(&mut body, 4);
509            assert!(
510                body.get("thinking").is_none(),
511                "{model} must not get thinking params"
512            );
513        }
514    }
515
516    #[test]
517    fn skips_thinking_for_thinkingless_claude3() {
518        // The 2024 claude-3 series has no extended thinking at all.
519        for model in [
520            "claude-3-opus-20240229",
521            "claude-3-sonnet-20240229",
522            "claude-3-haiku-20240307",
523            "claude-3-5-haiku",
524        ] {
525            let mut body = json!({"model": model, "max_tokens": 4096, "messages": []});
526            apply_effort_budget(&mut body, 4);
527            assert!(
528                body.get("thinking").is_none(),
529                "{model} must not get thinking params"
530            );
531        }
532    }
533
534    #[test]
535    fn applies_thinking_to_budget_token_era() {
536        // claude-3-5/3-7 sonnet and the 4-5 era still accept budget_tokens.
537        for model in [
538            "claude-3-5-sonnet",
539            "claude-3-7-sonnet",
540            "anthropic/claude-3.5-sonnet",
541            "claude-sonnet-4-5",
542            "claude-opus-4-5",
543            "claude-haiku-4-5",
544            "claude-sonnet-4-20250514",
545            "claude-opus-4-20250514",
546        ] {
547            let mut body = json!({"model": model, "max_tokens": 4096, "messages": []});
548            apply_effort_budget(&mut body, 4);
549            assert_eq!(
550                body["thinking"]["budget_tokens"], 8_192,
551                "{model} must get a thinking budget"
552            );
553        }
554    }
555
556    #[test]
557    fn applies_openai_reasoning_effort() {
558        let mut body = json!({"model": "gpt-5.4", "messages": []});
559        apply_effort_budget(&mut body, 3);
560        assert_eq!(body["reasoning"]["effort"], "medium");
561    }
562}
563
564fn count_file_mentions(text: &str) -> usize {
565    text.split_whitespace()
566        .filter(|word| {
567            let word = word.trim_matches(|character: char| {
568                !character.is_ascii_alphanumeric()
569                    && character != '.'
570                    && character != '_'
571                    && character != '/'
572            });
573            word.contains('/')
574                || [".rs", ".toml", ".json", ".md", ".py", ".ts", ".js"]
575                    .iter()
576                    .any(|suffix| word.ends_with(suffix))
577        })
578        .count()
579}
580
581fn message_has_error(message: &Value) -> bool {
582    message.get("is_error").and_then(Value::as_bool) == Some(true)
583        || extract_text_from_content(message.get("content").unwrap_or(&Value::Null))
584            .is_some_and(contains_error_indicators)
585}
586
587// ---------------------------------------------------------------------------
588// Internal classification helpers
589// ---------------------------------------------------------------------------
590
591fn classify_tool_result(msg: &Value, _all_messages: &[Value]) -> TurnClass {
592    let content = msg.get("content").and_then(Value::as_str).unwrap_or("");
593
594    if contains_error_indicators(content) {
595        return TurnClass::Full;
596    }
597
598    if is_routine_tool_output(content) {
599        return TurnClass::Routine;
600    }
601
602    TurnClass::Full
603}
604
605/// Heuristic: does this tool output look like a routine, successful result?
606fn is_routine_tool_output(content: &str) -> bool {
607    if content.is_empty() || content.len() < 10 {
608        return false;
609    }
610
611    // Error indicators → not routine.
612    if contains_error_indicators(content) {
613        return false;
614    }
615
616    // Very large outputs (>8000 chars) likely need careful processing.
617    if content.len() > 8000 {
618        return false;
619    }
620
621    // Positive signals for routine:
622    let routine_signals = [
623        // File read results (lean-ctx or native).
624        "deps ",      // lean-ctx read header
625        "[unchanged", // cached re-read
626        "[lean-ctx]", // lean-ctx footer
627        "lines:",     // line count indicators
628        // Shell success patterns.
629        "exit_code: 0",
630        "Command completed",
631        "0 errors",
632        "All tests passed",
633        "no changes",
634        "nothing to commit",
635        "Already up to date",
636        "Build succeeded",
637        // Search results.
638        "matches in",
639        "0 matches",
640    ];
641
642    routine_signals.iter().any(|sig| content.contains(sig))
643}
644
645/// Check if content contains error/failure indicators that need full thinking.
646fn contains_error_indicators(content: &str) -> bool {
647    let lower = content.to_ascii_lowercase();
648    let indicators = [
649        "error",
650        "failed",
651        "failure",
652        "fatal",
653        "panic",
654        "exception",
655        "traceback",
656        "stack trace",
657        "segfault",
658        "abort",
659        "denied",
660        "permission",
661        "not found",
662        "timed out",
663        "exit_code: 1",
664        "exit code 1",
665        "compilation error",
666        "syntax error",
667        "type error",
668    ];
669
670    indicators.iter().any(|ind| lower.contains(ind))
671}
672
673/// Extract text from Anthropic content blocks.
674fn extract_text_from_content(content: &Value) -> Option<&str> {
675    if let Some(s) = content.as_str() {
676        return Some(s);
677    }
678    if let Some(arr) = content.as_array() {
679        for block in arr {
680            if block.get("type").and_then(Value::as_str) == Some("text") {
681                return block.get("text").and_then(Value::as_str);
682            }
683        }
684    }
685    None
686}
687
688#[cfg(test)]
689mod tests {
690    use super::*;
691    use serde_json::json;
692
693    #[test]
694    fn user_message_is_always_full() {
695        let messages = json!([
696            {"role": "user", "content": "What does this function do?"}
697        ]);
698        assert_eq!(classify_turn(&messages), TurnClass::Full);
699    }
700
701    #[test]
702    fn successful_file_read_is_routine() {
703        let messages = json!([
704            {"role": "assistant", "content": "Let me read that file."},
705            {"role": "tool", "content": "main.rs 50L\n  deps serde\n[lean-ctx] full source: ..."}
706        ]);
707        assert_eq!(classify_turn(&messages), TurnClass::Routine);
708    }
709
710    #[test]
711    fn error_tool_result_is_full() {
712        let messages = json!([
713            {"role": "tool", "content": "error[E0308]: mismatched types\n  --> src/main.rs:5:12"}
714        ]);
715        assert_eq!(classify_turn(&messages), TurnClass::Full);
716    }
717
718    #[test]
719    fn successful_shell_is_routine() {
720        let messages = json!([
721            {"role": "tool", "content": "Command completed in 150ms\nexit_code: 0\nAll tests passed"}
722        ]);
723        assert_eq!(classify_turn(&messages), TurnClass::Routine);
724    }
725
726    #[test]
727    fn anthropic_tool_result_routine() {
728        let messages = json!([
729            {"role": "user", "content": [
730                {"type": "tool_result", "tool_use_id": "abc", "content": "[unchanged 5L]\n[lean-ctx] cached"}
731            ]}
732        ]);
733        assert_eq!(classify_turn_anthropic(&messages), TurnClass::Routine);
734    }
735
736    #[test]
737    fn anthropic_tool_result_with_error() {
738        let messages = json!([
739            {"role": "user", "content": [
740                {"type": "tool_result", "tool_use_id": "abc", "is_error": true, "content": "Tool failed"}
741            ]}
742        ]);
743        assert_eq!(classify_turn_anthropic(&messages), TurnClass::Full);
744    }
745
746    #[test]
747    fn effort_mapping() {
748        assert_eq!(
749            effort_for_turn(TurnClass::Routine, Effort::High),
750            Effort::Minimal
751        );
752        assert_eq!(effort_for_turn(TurnClass::Full, Effort::High), Effort::High);
753        assert_eq!(
754            effort_for_turn(TurnClass::Full, Effort::Medium),
755            Effort::Medium
756        );
757    }
758
759    #[test]
760    fn intent_adjusts_effort_by_task_complexity() {
761        assert_eq!(
762            intent_aware_effort("fix the parser", Effort::Low),
763            Effort::High
764        );
765        assert_eq!(
766            intent_aware_effort("read the config", Effort::High),
767            Effort::Minimal
768        );
769        assert_eq!(intent_aware_effort("chat", Effort::Medium), Effort::Medium);
770    }
771
772    #[test]
773    fn empty_messages_is_full() {
774        assert_eq!(classify_turn(&json!([])), TurnClass::Full);
775        assert_eq!(classify_turn(&json!(null)), TurnClass::Full);
776    }
777
778    #[test]
779    fn deterministic_classification() {
780        let messages = json!([
781            {"role": "tool", "content": "Build succeeded\nexit_code: 0\nCommand completed in 2s"}
782        ]);
783        let c1 = classify_turn(&messages);
784        let c2 = classify_turn(&messages);
785        assert_eq!(c1, c2, "classification must be deterministic");
786    }
787}