1use serde_json::Value;
39use std::sync::atomic::{AtomicU64, Ordering};
40
41use crate::core::config::Effort;
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum TurnClass {
46 Routine,
48 Full,
50}
51
52#[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
71pub 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
93pub 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 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
116pub 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 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 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 if blocks.len() > 3 {
155 return TurnClass::Full;
156 }
157
158 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
176pub fn effort_for_turn(class: TurnClass, base: Effort) -> Effort {
179 match class {
180 TurnClass::Routine => {
181 ROUTINE_COUNT.fetch_add(1, Ordering::Relaxed);
182 Effort::Minimal
184 }
185 TurnClass::Full => {
186 FULL_COUNT.fetch_add(1, Ordering::Relaxed);
187 base
188 }
189 }
190}
191
192pub 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
230pub 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#[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
286pub fn score_session_complexity(messages: &[Value]) -> u8 {
294 messages
295 .iter()
296 .find(|message| message.get("role").and_then(Value::as_str) == Some("user"))
297 .map_or(1, |first_user| {
298 score_complexity(std::slice::from_ref(first_user))
299 })
300}
301
302pub fn score_complexity(messages: &[Value]) -> u8 {
304 let user_text = messages
305 .iter()
306 .rev()
307 .find(|message| message.get("role").and_then(Value::as_str) == Some("user"))
308 .and_then(|message| {
309 extract_text_from_content(message.get("content").unwrap_or(&Value::Null))
310 })
311 .unwrap_or_default();
312 let text = user_text.to_ascii_lowercase();
313 let file_mentions = count_file_mentions(&text);
314 let has_errors = messages.iter().any(message_has_error);
315 let critical = ["security", "vulnerability", "production", "incident", "cve"]
316 .iter()
317 .any(|marker| text.contains(marker));
318 let complex = ["debug", "architecture", "refactor", "design"]
319 .iter()
320 .any(|marker| text.contains(marker));
321
322 if critical {
323 5
324 } else if has_errors || complex {
325 4
326 } else if file_mentions >= 2 || user_text.len() > 1_200 || text.contains("test") {
327 3
328 } else if file_mentions == 1 || user_text.len() > 300 {
329 2
330 } else {
331 1
332 }
333}
334
335pub fn route_effort_budget(body: &mut Value) -> TaskComplexity {
337 let complexity = body
338 .get("messages")
339 .or_else(|| body.get("input"))
340 .and_then(Value::as_array)
341 .map_or(1, |messages| score_session_complexity(messages));
342 apply_effort_budget(body, complexity)
343}
344
345const MIN_THINKING_BUDGET: u32 = 1_024;
347
348fn anthropic_thinking_budget(
359 object: &serde_json::Map<String, Value>,
360 task: TaskComplexity,
361) -> Option<u32> {
362 let max_tokens = object.get("max_tokens").and_then(Value::as_u64)?;
363 let half = u32::try_from(max_tokens / 2).unwrap_or(u32::MAX);
364 let budget = task.budget_tokens.min(half);
365 if budget < MIN_THINKING_BUDGET {
366 return None;
367 }
368 if object
369 .get("temperature")
370 .and_then(Value::as_f64)
371 .is_some_and(|temperature| (temperature - 1.0).abs() > f64::EPSILON)
372 || object.contains_key("top_k")
373 || object
374 .get("top_p")
375 .and_then(Value::as_f64)
376 .is_some_and(|top_p| top_p < 0.95)
377 {
378 return None;
379 }
380 let forced_tool = object
381 .get("tool_choice")
382 .and_then(|choice| choice.get("type"))
383 .and_then(Value::as_str)
384 .is_some_and(|kind| matches!(kind, "any" | "tool"));
385 if forced_tool {
386 return None;
387 }
388 let assistants = object
389 .get("messages")
390 .and_then(Value::as_array)
391 .map(|messages| {
392 messages
393 .iter()
394 .filter(|message| message.get("role").and_then(Value::as_str) == Some("assistant"))
395 .collect::<Vec<_>>()
396 })
397 .unwrap_or_default();
398 let history_has_thinking = assistants.iter().any(|message| {
399 message
400 .get("content")
401 .and_then(Value::as_array)
402 .is_some_and(|blocks| {
403 blocks.iter().any(|block| {
404 matches!(
405 block.get("type").and_then(Value::as_str),
406 Some("thinking" | "redacted_thinking")
407 )
408 })
409 })
410 });
411 if !assistants.is_empty() && !history_has_thinking {
412 return None;
413 }
414 Some(budget)
415}
416
417fn anthropic_supports_thinking(model: &str) -> bool {
428 let bare = model.rsplit('/').next().unwrap_or(model);
429 let budget_token_families = [
430 "claude-3-5-sonnet",
431 "claude-3-7-sonnet",
432 "claude-3.5-sonnet",
433 "claude-3.7-sonnet",
434 "claude-sonnet-4-5",
435 "claude-opus-4-5",
436 "claude-haiku-4-5",
437 "claude-4-5", "claude-sonnet-4-2025", "claude-opus-4-2025", ];
441 budget_token_families
442 .iter()
443 .any(|family| bare.starts_with(family))
444 || bare == "claude-sonnet-4"
446 || bare == "claude-opus-4"
447}
448
449pub fn apply_effort_budget(body: &mut Value, complexity: u8) -> TaskComplexity {
451 inject_effort_budget(body, complexity).0
452}
453
454pub(crate) fn inject_effort_budget(body: &mut Value, complexity: u8) -> (TaskComplexity, bool) {
461 let task = TaskComplexity::from_score(complexity);
462 let Some(object) = body.as_object_mut() else {
463 return (task, false);
464 };
465
466 let model = object
467 .get("model")
468 .and_then(Value::as_str)
469 .unwrap_or_default()
470 .to_string();
471 let is_anthropic = object.contains_key("messages")
472 && (object.contains_key("max_tokens") || model.contains("claude"));
473 let mut injected_budget = None;
474 if is_anthropic && anthropic_supports_thinking(&model) {
475 if object.get("thinking").is_none() {
476 if let Some(budget) = anthropic_thinking_budget(object, task) {
477 object.insert(
478 "thinking".into(),
479 serde_json::json!({"type": "enabled", "budget_tokens": budget}),
480 );
481 injected_budget = Some(budget);
482 }
483 }
484 } else if crate::proxy::effort::openai_supports_effort(&model) {
485 let client_chose = object.contains_key("reasoning_effort")
486 || object
487 .get("reasoning")
488 .is_some_and(|reasoning| reasoning.get("effort").is_some());
489 if !client_chose {
490 let effort = Value::String(openai_effort_value(task.effort).into());
491 if object.contains_key("messages") {
492 object.insert("reasoning_effort".into(), effort);
494 injected_budget = Some(task.budget_tokens);
495 } else if object.contains_key("input") {
496 let reasoning = object
498 .entry("reasoning")
499 .or_insert_with(|| Value::Object(serde_json::Map::new()));
500 if let Some(reasoning) = reasoning.as_object_mut() {
501 reasoning.insert("effort".into(), effort);
502 injected_budget = Some(task.budget_tokens);
503 }
504 }
505 }
506 }
507 let Some(budget) = injected_budget else {
508 return (task, false);
509 };
510 ESTIMATED_OUTPUT_TOKENS_WITHOUT_ROUTING.fetch_add(16_384, Ordering::Relaxed);
511 ACTUAL_EFFORT_BUDGET_TOKENS.fetch_add(budget.into(), Ordering::Relaxed);
512 (task, true)
513}
514
515fn openai_effort_value(effort: Effort) -> &'static str {
516 match effort {
517 Effort::Minimal | Effort::Low => "low",
518 Effort::Medium => "medium",
519 Effort::High => "high",
520 }
521}
522
523#[cfg(test)]
524mod output_token_intelligence_tests {
525 use super::*;
526 use serde_json::json;
527
528 #[test]
529 fn trivial_task_gets_low_effort() {
530 let messages = vec![json!({"role": "user", "content": "Read src/lib.rs"})];
531 assert_eq!(score_complexity(&messages), 2);
532 assert_eq!(TaskComplexity::from_score(1).budget_tokens, 1_024);
533 }
534
535 #[test]
536 fn complex_task_gets_high_effort() {
537 let messages =
538 vec![json!({"role": "user", "content": "Design the architecture for this refactor"})];
539 let task = TaskComplexity::from_score(score_complexity(&messages));
540 assert_eq!(task.score, 4);
541 assert_eq!(task.effort, Effort::High);
542 }
543
544 #[test]
545 fn error_presence_increases_complexity() {
546 let messages = vec![
547 json!({"role": "tool", "content": "error[E0308]: mismatched types"}),
548 json!({"role": "user", "content": "fix this"}),
549 ];
550 assert_eq!(score_complexity(&messages), 4);
551 }
552
553 #[test]
554 fn applies_anthropic_thinking_budget() {
555 let mut body = json!({"model": "claude-sonnet-4", "max_tokens": 32_000, "messages": []});
556 let task = apply_effort_budget(&mut body, 4);
557 assert_eq!(task.budget_tokens, 8_192);
558 assert_eq!(body["thinking"]["budget_tokens"], 8_192);
559 assert_eq!(body["thinking"]["type"], "enabled");
560 }
561
562 #[test]
563 fn thinking_budget_stays_below_max_tokens() {
564 let mut body = json!({"model": "claude-sonnet-4-5", "max_tokens": 4096, "messages": []});
567 let (_, changed) = inject_effort_budget(&mut body, 5);
568 assert!(changed);
569 let budget = body["thinking"]["budget_tokens"].as_u64().unwrap();
570 assert_eq!(budget, 2_048);
571 assert!(budget < 4096);
572 }
573
574 #[test]
575 fn small_max_tokens_gets_no_thinking() {
576 for max_tokens in [1_024, 2_047] {
578 let mut body =
579 json!({"model": "claude-sonnet-4-5", "max_tokens": max_tokens, "messages": []});
580 let (_, changed) = inject_effort_budget(&mut body, 5);
581 assert!(!changed, "max_tokens {max_tokens} must not get thinking");
582 assert!(body.get("thinking").is_none());
583 }
584 let mut body = json!({"model": "claude-sonnet-4-5", "messages": []});
585 assert!(
586 !inject_effort_budget(&mut body, 5).1,
587 "no max_tokens → no injection"
588 );
589 }
590
591 #[test]
592 fn skips_thinking_when_sampling_or_tool_choice_conflicts() {
593 let base = json!({"model": "claude-sonnet-4-5", "max_tokens": 32_000, "messages": []});
594 for (key, value) in [
595 ("temperature", json!(0.2)),
596 ("top_k", json!(40)),
597 ("top_p", json!(0.5)),
598 ("tool_choice", json!({"type": "any"})),
599 ("tool_choice", json!({"type": "tool", "name": "x"})),
600 ] {
601 let mut body = base.clone();
602 body[key] = value.clone();
603 let (_, changed) = inject_effort_budget(&mut body, 4);
604 assert!(!changed, "{key}={value} must block thinking");
605 assert!(body.get("thinking").is_none());
606 }
607 let mut body = base.clone();
608 body["temperature"] = json!(1.0);
609 body["tool_choice"] = json!({"type": "auto"});
610 assert!(
611 inject_effort_budget(&mut body, 4).1,
612 "defaults must still inject"
613 );
614 }
615
616 #[test]
617 fn skips_thinking_when_history_has_no_thinking_blocks() {
618 let mut body = json!({
621 "model": "claude-sonnet-4-5",
622 "max_tokens": 32_000,
623 "messages": [
624 {"role": "user", "content": "hi"},
625 {"role": "assistant", "content": [{"type": "text", "text": "hello"}]},
626 {"role": "user", "content": "debug this"}
627 ]
628 });
629 assert!(!inject_effort_budget(&mut body, 4).1);
630 assert!(body.get("thinking").is_none());
631
632 body["messages"][1]["content"] = json!([
633 {"type": "thinking", "thinking": "…", "signature": "sig"},
634 {"type": "text", "text": "hello"}
635 ]);
636 assert!(inject_effort_budget(&mut body, 4).1);
637 }
638
639 #[test]
640 fn session_score_is_stable_across_turns() {
641 let first = json!({"role": "user", "content": "rename a variable"});
644 let turn_one = vec![first.clone()];
645 let turn_two = vec![
646 first,
647 json!({"role": "assistant", "content": "done"}),
648 json!({"role": "tool", "content": "error[E0308]: mismatched types"}),
649 json!({"role": "user", "content": "debug the production security incident"}),
650 ];
651 assert_eq!(
652 score_session_complexity(&turn_one),
653 score_session_complexity(&turn_two)
654 );
655 assert_ne!(score_complexity(&turn_one), score_complexity(&turn_two));
656 assert_eq!(score_session_complexity(&[]), 1);
657 }
658
659 #[test]
660 fn skips_thinking_for_unsupported_models() {
661 let mut body = json!({"model": "claude-sonnet-5", "max_tokens": 4096, "messages": []});
662 let task = apply_effort_budget(&mut body, 4);
663 assert_eq!(task.budget_tokens, 8_192);
664 assert!(
665 body.get("thinking").is_none(),
666 "sonnet-5 must not get thinking params"
667 );
668 }
669
670 #[test]
671 fn skips_thinking_for_openrouter_wrapped_unsupported() {
672 let mut body =
673 json!({"model": "anthropic/claude-sonnet-5", "max_tokens": 4096, "messages": []});
674 apply_effort_budget(&mut body, 4);
675 assert!(
676 body.get("thinking").is_none(),
677 "openrouter-wrapped sonnet-5 must not get thinking"
678 );
679 }
680
681 #[test]
682 fn preserves_client_thinking_params() {
683 let mut body = json!({
684 "model": "claude-sonnet-4",
685 "thinking": {"type": "adaptive"},
686 "messages": []
687 });
688 apply_effort_budget(&mut body, 4);
689 assert_eq!(
690 body["thinking"]["type"], "adaptive",
691 "must not overwrite client thinking"
692 );
693 assert!(
694 body["thinking"].get("budget_tokens").is_none(),
695 "must not inject budget_tokens"
696 );
697 }
698
699 #[test]
700 fn skips_thinking_for_adaptive_only_models() {
701 for model in [
704 "claude-opus-4-6",
705 "claude-opus-4-7",
706 "claude-opus-4-8",
707 "claude-sonnet-4-6",
708 "claude-sonnet-5",
709 "claude-opus-5",
710 "claude-fable-5",
711 ] {
712 let mut body = json!({"model": model, "max_tokens": 4096, "messages": []});
713 apply_effort_budget(&mut body, 4);
714 assert!(
715 body.get("thinking").is_none(),
716 "{model} must not get thinking params"
717 );
718 }
719 }
720
721 #[test]
722 fn skips_thinking_for_thinkingless_claude3() {
723 for model in [
725 "claude-3-opus-20240229",
726 "claude-3-sonnet-20240229",
727 "claude-3-haiku-20240307",
728 "claude-3-5-haiku",
729 ] {
730 let mut body = json!({"model": model, "max_tokens": 4096, "messages": []});
731 apply_effort_budget(&mut body, 4);
732 assert!(
733 body.get("thinking").is_none(),
734 "{model} must not get thinking params"
735 );
736 }
737 }
738
739 #[test]
740 fn applies_thinking_to_budget_token_era() {
741 for model in [
743 "claude-3-5-sonnet",
744 "claude-3-7-sonnet",
745 "anthropic/claude-3.5-sonnet",
746 "claude-sonnet-4-5",
747 "claude-opus-4-5",
748 "claude-haiku-4-5",
749 "claude-sonnet-4-20250514",
750 "claude-opus-4-20250514",
751 ] {
752 let mut body = json!({"model": model, "max_tokens": 32_000, "messages": []});
753 apply_effort_budget(&mut body, 4);
754 assert_eq!(
755 body["thinking"]["budget_tokens"], 8_192,
756 "{model} must get a thinking budget"
757 );
758 }
759 }
760
761 #[test]
762 fn applies_openai_reasoning_effort() {
763 let mut body = json!({"model": "gpt-5.4", "messages": []});
765 assert!(inject_effort_budget(&mut body, 3).1);
766 assert_eq!(body["reasoning_effort"], "medium");
767 assert!(body.get("reasoning").is_none());
768
769 let mut body = json!({"model": "gpt-5.4", "input": []});
770 assert!(inject_effort_budget(&mut body, 3).1);
771 assert_eq!(body["reasoning"]["effort"], "medium");
772 assert!(body.get("reasoning_effort").is_none());
773 }
774
775 #[test]
776 fn keeps_client_openai_effort() {
777 let mut body = json!({"model": "gpt-5.4", "messages": [], "reasoning_effort": "high"});
779 let before = body.clone();
780 assert!(!inject_effort_budget(&mut body, 1).1);
781 assert_eq!(body, before);
782
783 let mut body = json!({"model": "gpt-5.4", "input": [], "reasoning": {"effort": "minimal"}});
784 let before = body.clone();
785 assert!(!inject_effort_budget(&mut body, 5).1);
786 assert_eq!(body, before);
787 }
788}
789
790fn count_file_mentions(text: &str) -> usize {
791 text.split_whitespace()
792 .filter(|word| {
793 let word = word.trim_matches(|character: char| {
794 !character.is_ascii_alphanumeric()
795 && character != '.'
796 && character != '_'
797 && character != '/'
798 });
799 word.contains('/')
800 || [".rs", ".toml", ".json", ".md", ".py", ".ts", ".js"]
801 .iter()
802 .any(|suffix| word.ends_with(suffix))
803 })
804 .count()
805}
806
807fn message_has_error(message: &Value) -> bool {
808 message.get("is_error").and_then(Value::as_bool) == Some(true)
809 || extract_text_from_content(message.get("content").unwrap_or(&Value::Null))
810 .is_some_and(contains_error_indicators)
811}
812
813fn classify_tool_result(msg: &Value, _all_messages: &[Value]) -> TurnClass {
818 let content = msg.get("content").and_then(Value::as_str).unwrap_or("");
819
820 if contains_error_indicators(content) {
821 return TurnClass::Full;
822 }
823
824 if is_routine_tool_output(content) {
825 return TurnClass::Routine;
826 }
827
828 TurnClass::Full
829}
830
831fn is_routine_tool_output(content: &str) -> bool {
833 if content.is_empty() || content.len() < 10 {
834 return false;
835 }
836
837 if contains_error_indicators(content) {
839 return false;
840 }
841
842 if content.len() > 8000 {
844 return false;
845 }
846
847 let routine_signals = [
849 "deps ", "[unchanged", "[lean-ctx]", "lines:", "exit_code: 0",
856 "Command completed",
857 "0 errors",
858 "All tests passed",
859 "no changes",
860 "nothing to commit",
861 "Already up to date",
862 "Build succeeded",
863 "matches in",
865 "0 matches",
866 ];
867
868 routine_signals.iter().any(|sig| content.contains(sig))
869}
870
871fn contains_error_indicators(content: &str) -> bool {
873 let lower = content.to_ascii_lowercase();
874 let indicators = [
875 "error",
876 "failed",
877 "failure",
878 "fatal",
879 "panic",
880 "exception",
881 "traceback",
882 "stack trace",
883 "segfault",
884 "abort",
885 "denied",
886 "permission",
887 "not found",
888 "timed out",
889 "exit_code: 1",
890 "exit code 1",
891 "compilation error",
892 "syntax error",
893 "type error",
894 ];
895
896 indicators.iter().any(|ind| lower.contains(ind))
897}
898
899fn extract_text_from_content(content: &Value) -> Option<&str> {
901 if let Some(s) = content.as_str() {
902 return Some(s);
903 }
904 if let Some(arr) = content.as_array() {
905 for block in arr {
906 if block.get("type").and_then(Value::as_str) == Some("text") {
907 return block.get("text").and_then(Value::as_str);
908 }
909 }
910 }
911 None
912}
913
914#[cfg(test)]
915mod tests {
916 use super::*;
917 use serde_json::json;
918
919 #[test]
920 fn user_message_is_always_full() {
921 let messages = json!([
922 {"role": "user", "content": "What does this function do?"}
923 ]);
924 assert_eq!(classify_turn(&messages), TurnClass::Full);
925 }
926
927 #[test]
928 fn successful_file_read_is_routine() {
929 let messages = json!([
930 {"role": "assistant", "content": "Let me read that file."},
931 {"role": "tool", "content": "main.rs 50L\n deps serde\n[lean-ctx] full source: ..."}
932 ]);
933 assert_eq!(classify_turn(&messages), TurnClass::Routine);
934 }
935
936 #[test]
937 fn error_tool_result_is_full() {
938 let messages = json!([
939 {"role": "tool", "content": "error[E0308]: mismatched types\n --> src/main.rs:5:12"}
940 ]);
941 assert_eq!(classify_turn(&messages), TurnClass::Full);
942 }
943
944 #[test]
945 fn successful_shell_is_routine() {
946 let messages = json!([
947 {"role": "tool", "content": "Command completed in 150ms\nexit_code: 0\nAll tests passed"}
948 ]);
949 assert_eq!(classify_turn(&messages), TurnClass::Routine);
950 }
951
952 #[test]
953 fn anthropic_tool_result_routine() {
954 let messages = json!([
955 {"role": "user", "content": [
956 {"type": "tool_result", "tool_use_id": "abc", "content": "[unchanged 5L]\n[lean-ctx] cached"}
957 ]}
958 ]);
959 assert_eq!(classify_turn_anthropic(&messages), TurnClass::Routine);
960 }
961
962 #[test]
963 fn anthropic_tool_result_with_error() {
964 let messages = json!([
965 {"role": "user", "content": [
966 {"type": "tool_result", "tool_use_id": "abc", "is_error": true, "content": "Tool failed"}
967 ]}
968 ]);
969 assert_eq!(classify_turn_anthropic(&messages), TurnClass::Full);
970 }
971
972 #[test]
973 fn effort_mapping() {
974 assert_eq!(
975 effort_for_turn(TurnClass::Routine, Effort::High),
976 Effort::Minimal
977 );
978 assert_eq!(effort_for_turn(TurnClass::Full, Effort::High), Effort::High);
979 assert_eq!(
980 effort_for_turn(TurnClass::Full, Effort::Medium),
981 Effort::Medium
982 );
983 }
984
985 #[test]
986 fn intent_adjusts_effort_by_task_complexity() {
987 assert_eq!(
988 intent_aware_effort("fix the parser", Effort::Low),
989 Effort::High
990 );
991 assert_eq!(
992 intent_aware_effort("read the config", Effort::High),
993 Effort::Minimal
994 );
995 assert_eq!(intent_aware_effort("chat", Effort::Medium), Effort::Medium);
996 }
997
998 #[test]
999 fn empty_messages_is_full() {
1000 assert_eq!(classify_turn(&json!([])), TurnClass::Full);
1001 assert_eq!(classify_turn(&json!(null)), TurnClass::Full);
1002 }
1003
1004 #[test]
1005 fn deterministic_classification() {
1006 let messages = json!([
1007 {"role": "tool", "content": "Build succeeded\nexit_code: 0\nCommand completed in 2s"}
1008 ]);
1009 let c1 = classify_turn(&messages);
1010 let c2 = classify_turn(&messages);
1011 assert_eq!(c1, c2, "classification must be deterministic");
1012 }
1013}