1#[macro_use]
9mod delegate;
10#[cfg(test)]
11pub(crate) mod fixture;
12pub(crate) mod patterns;
14
15pub mod claude;
16pub mod codex;
17pub mod grok;
18pub mod kimi;
19pub mod minimax;
20pub mod opencode;
21
22use crate::config;
23use crate::parser::AgentResponse;
24use std::collections::BTreeSet;
25use std::error;
26use std::fmt;
27use std::fmt::Display;
28use std::fmt::Formatter;
29use std::path::PathBuf;
30use std::time::Duration;
31use tokio::process::Command;
32
33#[derive(Debug, Clone)]
39pub struct PermissionRules {
40 pub autonomous: bool,
42 pub sandbox: SandboxLevel,
44 pub disallowed_tools: Vec<String>,
46 pub allowed_tools: Vec<String>,
52 pub allowed_edit_paths: Vec<PathBuf>,
56 pub deny_read_only: bool,
60 pub extra_writable_dirs: Vec<PathBuf>,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
69pub enum SandboxLevel {
70 WorkspaceWrite,
72 FullAccess,
74 None,
76 Os,
78 ReadOnly,
81}
82
83impl Default for PermissionRules {
84 fn default() -> Self {
85 Self {
86 autonomous: true,
87 sandbox: SandboxLevel::WorkspaceWrite,
88 disallowed_tools: vec![
89 "Bash(rm *)".to_string(),
90 "Bash(rm -*)".to_string(),
91 "Bash(git push*)".to_string(),
92 ],
93 allowed_tools: vec![],
94 allowed_edit_paths: vec![],
95 deny_read_only: false,
96 extra_writable_dirs: vec![],
97 }
98 }
99}
100
101impl PermissionRules {
102 pub fn from_config() -> Self {
104 let mut rules = Self::default();
105
106 if let Ok(mode) = config::get("workflow.permissions.mode") {
107 rules.autonomous = mode != "supervised";
108 }
109
110 if let Ok(sandbox) = config::get("workflow.permissions.sandbox") {
111 rules.sandbox = match sandbox.as_str() {
112 "full-access" | "danger-full-access" => SandboxLevel::FullAccess,
113 "none" => SandboxLevel::None,
114 _ => SandboxLevel::WorkspaceWrite,
115 };
116 }
117
118 if let Ok(tools) = config::get("workflow.disallowed_tools") {
119 let parsed: Vec<String> = tools
120 .split(',')
121 .map(|s| s.trim().to_string())
122 .filter(|s| !s.is_empty())
123 .collect();
124 if !parsed.is_empty() {
125 rules.disallowed_tools = parsed;
126 }
127 }
128
129 if let Ok(tools) = config::get_list("workflow.allowed_tools") {
130 rules.allowed_tools = tools;
131 }
132
133 rules
134 }
135
136 pub fn read_only(allowed: Vec<String>) -> Self {
144 Self {
145 autonomous: false,
146 sandbox: SandboxLevel::ReadOnly,
147 disallowed_tools: vec![],
148 allowed_tools: allowed,
149 allowed_edit_paths: vec![],
150 deny_read_only: false,
151 extra_writable_dirs: vec![],
152 }
153 }
154
155 pub fn deny_read_only() -> Self {
156 Self {
157 autonomous: true,
158 sandbox: SandboxLevel::WorkspaceWrite,
159 disallowed_tools: vec![
160 "Bash(rm *)".to_string(),
161 "Bash(rm -*)".to_string(),
162 "Bash(git push*)".to_string(),
163 "Bash(ls *)".to_string(),
164 "Bash(ls)".to_string(),
165 "Bash(find *)".to_string(),
166 "Bash(cat *)".to_string(),
167 "Bash(head *)".to_string(),
168 "Bash(tail *)".to_string(),
169 "Bash(fzf *)".to_string(),
170 "Bash(less *)".to_string(),
171 "Bash(more *)".to_string(),
172 "Read".to_string(),
173 "Glob".to_string(),
174 "Grep".to_string(),
175 ],
176 allowed_tools: vec![],
177 allowed_edit_paths: vec![],
178 deny_read_only: true,
179 extra_writable_dirs: vec![],
180 }
181 }
182}
183
184#[derive(Debug, Clone)]
190pub struct AgentResult {
191 pub is_error: bool,
193 pub result_text: String,
195 pub input_tokens: Option<u64>,
197 pub output_tokens: Option<u64>,
199 pub cost_usd: Option<f64>,
201 pub duration_ms: Option<u64>,
203 pub truncated_by_length: bool,
209}
210
211pub fn collect_assistant_messages_text(_agent: &str, ndjson: &str) -> String {
216 claude::collect_assistant_messages_text(ndjson)
217}
218
219pub fn find_agent_result(agent: &str, ndjson: &str) -> Option<AgentResult> {
224 match agent {
225 "grok" => grok::find_grok_result(ndjson),
226 "opencode" => opencode::find_opencode_result(ndjson),
227 "codex" => codex::find_codex_result(ndjson),
228 _ => claude::find_claude_result(ndjson),
230 }
231}
232
233#[derive(Debug, Clone)]
236pub struct ParsedResponse {
237 pub response: AgentResponse,
239 pub input_tokens: Option<u64>,
241 pub output_tokens: Option<u64>,
243 pub cost_usd: Option<f64>,
245 pub duration_ms: Option<u64>,
247}
248
249#[derive(Debug, Clone)]
251pub enum AgentError {
252 RateLimit { message: String },
254 Auth { message: String },
256 ModelUnavailable { message: String, model: String },
258 ContextOverflow { message: String },
260 Timeout { elapsed: Duration },
262 Interrupted { message: String },
264 MissingTool { tool: String },
266 PermissionDenied { message: String },
268 WaitingForInput { message: String },
270 StaleSession { session_id: String },
275 InvalidResponse { raw: String },
277 AgentFailed { message: String },
279 NetworkError { message: String },
281 ThinkingBlockConflict { message: String },
288 Unknown { exit_code: i32, message: String },
290}
291
292impl Display for AgentError {
293 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
294 match self {
295 Self::RateLimit { message, .. } => write!(f, "rate limit: {message}"),
296 Self::Auth { message } => write!(f, "auth error: {message}"),
297 Self::ModelUnavailable { message, model } => {
298 write!(f, "model unavailable ({model}): {message}")
299 }
300 Self::ContextOverflow { message, .. } => write!(f, "context overflow: {message}"),
301 Self::Timeout { elapsed } => write!(f, "timeout after {}s", elapsed.as_secs()),
302 Self::Interrupted { message } => write!(f, "interrupted: {message}"),
303 Self::MissingTool { tool } => write!(f, "missing tool: {tool}"),
304 Self::PermissionDenied { message } => write!(f, "permission denied: {message}"),
305 Self::WaitingForInput { message } => write!(f, "waiting for input: {message}"),
306 Self::StaleSession { session_id } => {
307 write!(f, "stale session (session expired): {session_id}")
308 }
309 Self::InvalidResponse { raw } => {
310 let end = truncate_at_char_boundary(raw, 200);
311 write!(f, "invalid response: {}", &raw[..end])
312 }
313 Self::AgentFailed { message } => write!(f, "agent failed: {message}"),
314 Self::NetworkError { message } => write!(f, "network error: {message}"),
315 Self::ThinkingBlockConflict { message } => {
316 write!(f, "thinking block conflict: {message}")
317 }
318 Self::Unknown { exit_code, message } => {
319 write!(f, "unknown error (exit {exit_code}): {message}")
320 }
321 }
322 }
323}
324
325impl error::Error for AgentError {}
326
327pub fn error_class_name(err: &AgentError) -> &'static str {
330 match err {
331 AgentError::RateLimit { .. } => "RateLimit",
332 AgentError::Auth { .. } => "Auth",
333 AgentError::ModelUnavailable { .. } => "ModelUnavailable",
334 AgentError::ContextOverflow { .. } => "ContextOverflow",
335 AgentError::Timeout { .. } => "Timeout",
336 AgentError::Interrupted { .. } => "Interrupted",
337 AgentError::MissingTool { .. } => "MissingTool",
338 AgentError::PermissionDenied { .. } => "PermissionDenied",
339 AgentError::WaitingForInput { .. } => "WaitingForInput",
340 AgentError::StaleSession { .. } => "StaleSession",
341 AgentError::InvalidResponse { .. } => "InvalidResponse",
342 AgentError::AgentFailed { .. } => "AgentFailed",
343 AgentError::NetworkError { .. } => "NetworkError",
344 AgentError::ThinkingBlockConflict { .. } => "ThinkingBlockConflict",
345 AgentError::Unknown { .. } => "Unknown",
346 }
347}
348
349fn extract_file_paths(text: &str) -> Vec<String> {
354 let extensions = [
357 "rs", "py", "ts", "tsx", "js", "jsx", "go", "java", "c", "cpp", "h", "hpp", "rb", "sh",
358 "md", "toml", "yaml", "yml", "json", "sql", "html", "css", "swift", "kt",
359 ];
360 let mut found: BTreeSet<String> = BTreeSet::new();
361 for token in text.split_whitespace() {
362 let token = token.trim_matches(|c: char| {
365 matches!(
366 c,
367 '`' | '\'' | '"' | '(' | ')' | '[' | ']' | ',' | ':' | ';'
368 )
369 });
370 let token = if let Some(without) = token.strip_suffix('.') {
374 let still_has_ext = extensions
375 .iter()
376 .any(|ext| without.ends_with(&format!(".{ext}")));
377 if still_has_ext { without } else { token }
378 } else {
379 token
380 };
381 let has_ext = extensions
384 .iter()
385 .any(|ext| token.ends_with(&format!(".{ext}")));
386 if !has_ext {
387 continue;
388 }
389 let path_like = token.contains('/')
392 || token.starts_with("src")
393 || token.starts_with("tests")
394 || token.starts_with("lib")
395 || token.starts_with("bin")
396 || token.starts_with("prompts")
397 || token.starts_with("migrations");
398 if path_like && token.len() >= 4 && !token.contains("://") {
399 found.insert(token.to_string());
400 }
401 }
402 found.into_iter().collect()
403}
404
405fn extract_bullet_sections(text: &str) -> (Vec<String>, Vec<String>) {
410 let remaining_headers = [
411 "remaining",
412 "todo",
413 "to do",
414 "next steps",
415 "still needed",
416 "left to do",
417 "not done",
418 "outstanding",
419 ];
420
421 let mut accomplished: Vec<String> = vec![];
422 let mut remaining: Vec<String> = vec![];
423 let mut in_remaining_section = false;
424
425 for line in text.lines() {
426 let trimmed = line.trim();
427 if trimmed.is_empty() {
428 continue;
429 }
430 let lower = trimmed.to_lowercase();
431
432 let is_heading = trimmed.ends_with(':') || trimmed.starts_with('#');
437
438 if is_heading {
439 in_remaining_section = remaining_headers.iter().any(|h| lower.contains(h));
440 continue;
441 }
442
443 let is_bullet = trimmed.starts_with('-')
445 || trimmed.starts_with('*')
446 || trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains('.');
447
448 if !is_bullet {
449 continue;
450 }
451
452 let content = trimmed
454 .trim_start_matches(|c: char| c == '-' || c == '*' || c.is_ascii_digit() || c == '.')
455 .trim()
456 .to_string();
457
458 if content.is_empty() {
459 continue;
460 }
461
462 if in_remaining_section {
463 remaining.push(content);
464 } else {
465 accomplished.push(content);
466 }
467 }
468
469 (accomplished, remaining)
470}
471
472fn is_cli_parser_diagnostic(text: &str) -> bool {
475 let lower = text.to_lowercase();
476
477 if lower.contains("error: unexpected argument") {
479 return true;
480 }
481
482 if text.lines().any(|line| {
484 let trimmed = line.trim();
485 trimmed.starts_with("Usage:") || trimmed.starts_with("usage:")
486 }) {
487 return true;
488 }
489
490 if lower.contains("for more information, try '--help'") {
492 return true;
493 }
494
495 if lower.contains("tip: to pass '") {
497 return true;
498 }
499
500 false
501}
502
503fn looks_like_ndjson_event_stream(text: &str) -> bool {
511 let Some(first_line) = text.lines().map(str::trim).find(|l| !l.is_empty()) else {
512 return false;
513 };
514
515 if !first_line.starts_with('{') {
516 return false;
517 }
518
519 let Ok(value) = serde_json::from_str::<serde_json::Value>(first_line) else {
520 return false;
521 };
522
523 let Some(event_type) = value.get("type").and_then(|v| v.as_str()) else {
524 return false;
525 };
526
527 matches!(
528 event_type,
529 "step_start"
530 | "step_finish"
531 | "tool_use"
532 | "tool_result"
533 | "assistant"
534 | "system"
535 | "message"
536 | "text"
537 )
538}
539
540pub fn synthesize_response_from_text(text: &str) -> Option<AgentResponse> {
545 fn contains_word(text: &str, word: &str) -> bool {
548 let mut start = 0;
549 while let Some(pos) = text[start..].find(word) {
550 let abs = start + pos;
551 let before_ok = abs == 0 || !text.as_bytes()[abs - 1].is_ascii_alphanumeric();
552 let after_ok = abs + word.len() >= text.len()
553 || !text.as_bytes()[abs + word.len()].is_ascii_alphanumeric();
554 if before_ok && after_ok {
555 return true;
556 }
557 start = abs + 1;
558 if start >= text.len() {
559 break;
560 }
561 }
562 false
563 }
564
565 let trimmed = text.trim();
566 if trimmed.is_empty() {
567 return None;
568 }
569
570 if is_cli_parser_diagnostic(trimmed) {
578 return None;
579 }
580
581 if looks_like_ndjson_event_stream(trimmed) {
587 return None;
588 }
589
590 let lower = trimmed.to_lowercase();
591 let looks_negative = [
598 "not done",
599 "not yet done",
600 "not complete",
601 "not yet complete",
602 "not completed",
603 "not yet completed",
604 "not committed",
605 "incomplete",
606 "undone",
607 ]
608 .iter()
609 .any(|needle| lower.contains(needle));
610
611 let explicit_done = [
614 "nothing to",
615 "nothing to do",
616 "nothing to execute",
617 "no positions",
618 "no open positions",
619 "no trades",
620 "no trade",
621 "no action needed",
622 "no changes to commit",
623 "completed",
624 "filed",
626 "filed issue",
627 "filed issues",
628 "created issue",
629 "created issues",
630 "opened issue",
631 "opened issues",
632 "issue created",
633 "issues created",
634 "issues filed",
635 "task created",
636 "posted comment",
637 "comment posted",
638 "changes committed",
639 "commit created",
640 "fixed.",
641 "has been fixed",
642 "the fix has been applied",
643 "the fix has already been applied",
644 "the fix is complete",
646 "fix is working",
647 "all tests pass",
648 "tests pass.",
649 ]
650 .iter()
651 .any(|needle| lower.contains(needle));
652
653 let mut done_confident = false;
659 for sentence in trimmed
660 .split(['.', '!', '?', '\n'])
661 .map(str::trim)
662 .filter(|s| !s.is_empty())
663 {
664 let s_lower = sentence.to_lowercase();
665 let word_count = sentence.split_whitespace().count();
667 let hedging = [
668 "let",
669 "let me",
670 "check",
671 "checking",
672 "will",
673 "i'll",
674 "i will",
675 "trying",
676 "try",
677 "investigat",
678 "maybe",
679 "could",
680 "should",
681 "might",
682 "if ",
683 "plan",
684 "planning",
685 ];
686 let contains_hedge = hedging.iter().any(|h| s_lower.contains(h));
687
688 if contains_word(&s_lower, "done") && word_count <= 8 && !contains_hedge {
689 done_confident = true;
690 break;
691 }
692
693 if s_lower.contains("committed") || s_lower.contains("commit created") {
697 if s_lower.contains("changes")
699 || s_lower.contains("i've")
700 || s_lower.contains("i have")
701 || s_lower.contains("the commit")
702 {
703 done_confident = true;
704 break;
705 }
706 }
707
708 let past_tense_actions = [
713 "added ",
714 "fixed ",
715 "updated ",
716 "implemented ",
717 "created ",
718 "removed ",
719 "changed ",
720 "deleted ",
721 "applied ",
722 "resolved ",
723 "patched ",
724 "refactored ",
725 "merged ",
726 "pushed ",
727 "deployed ",
728 ];
729 if !contains_hedge
730 && word_count <= 12
731 && past_tense_actions.iter().any(|v| s_lower.starts_with(v))
732 {
733 done_confident = true;
734 break;
735 }
736 }
737
738 let looks_done = !looks_negative && (explicit_done || done_confident);
739
740 let looks_error = [
741 "error:",
742 "failed to",
743 "cannot",
744 "permission denied",
745 "unable to",
746 ]
747 .iter()
748 .any(|needle| lower.contains(needle));
749
750 let status = if looks_error {
751 "needs_review"
752 } else if looks_done {
753 "done"
754 } else if looks_negative {
755 "needs_review"
757 } else {
758 return None;
764 };
765
766 let summary_end = truncate_at_char_boundary(trimmed, 500);
767 let summary = trimmed[..summary_end].to_string();
768 let error =
769 (status == "needs_review").then(|| "agent returned plain text instead of JSON".to_string());
770
771 let files = extract_file_paths(trimmed);
773 let (accomplished, remaining) = extract_bullet_sections(trimmed);
774
775 Some(AgentResponse {
776 status: status.to_string(),
777 summary,
778 accomplished,
779 remaining,
780 files,
781 error,
782 input_tokens: None,
783 output_tokens: None,
784 learnings: vec![],
785 delegations: vec![],
786 screenshots: vec![],
787 screenshot_note: None,
788 })
789}
790
791pub(crate) fn shell_single_quote(value: &str) -> String {
793 format!("'{}'", value.replace('\'', "'\\''"))
794}
795
796pub fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> usize {
799 if max_bytes >= s.len() {
800 return s.len();
801 }
802 let mut end = max_bytes;
804 while end > 0 && !s.is_char_boundary(end) {
805 end -= 1;
806 }
807 end
808}
809
810#[derive(Debug, Clone, PartialEq)]
812pub enum StreamEvent {
813 Started {
814 model: String,
815 },
816 Text(String),
817 Thinking(String),
818 ToolCall {
820 id: String,
821 name: String,
822 input: serde_json::Value,
823 },
824 ToolResult {
826 id: String,
827 name: String,
828 output: String,
829 is_error: bool,
830 },
831 Done(String),
832 Error(String),
833}
834
835pub(crate) fn json_str<'a>(v: &'a serde_json::Value, pointer: &str) -> &'a str {
837 v.pointer(pointer)
838 .and_then(serde_json::Value::as_str)
839 .unwrap_or("")
840}
841
842pub(crate) fn json_error_message(v: &serde_json::Value) -> String {
844 [
845 "/message",
846 "/error",
847 "/error/message",
848 "/error/data/message",
849 ]
850 .iter()
851 .find_map(|p| v.pointer(p).and_then(serde_json::Value::as_str))
852 .unwrap_or("unknown error")
853 .to_string()
854}
855
856#[derive(Debug, Clone, Copy, PartialEq, Eq)]
858pub enum RouterTranscript {
859 Messages,
861 OpenCode,
863 Raw,
865}
866
867pub trait AgentRunner: Send + Sync {
872 #[cfg(test)]
874 fn name(&self) -> &str;
875
876 fn build_command(
882 &self,
883 model: Option<&str>,
884 timeout_cmd: &str,
885 sys_file: &str,
886 msg_file: &str,
887 permissions: &PermissionRules,
888 ) -> String;
889
890 fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError>;
895
896 fn extract_text(&self, raw: &str) -> Result<String, AgentError> {
911 Ok(raw.to_string())
912 }
913
914 fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent>;
916
917 fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError;
922
923 fn classify_error_with_elapsed(
925 &self,
926 exit_code: i32,
927 stdout: &str,
928 stderr: &str,
929 elapsed_secs: Option<u64>,
930 ) -> AgentError {
931 let mut err = self.classify_error(exit_code, stdout, stderr);
932 if let AgentError::Timeout { elapsed } = &mut err
933 && let Some(actual_elapsed) = elapsed_secs
934 {
935 *elapsed = Duration::from_secs(actual_elapsed);
936 }
937 err
938 }
939
940 fn available_models(&self) -> Vec<String> {
942 vec![]
943 }
944
945 fn free_models(&self) -> Vec<String> {
947 vec![]
948 }
949
950 fn router_transcript(&self) -> RouterTranscript {
952 RouterTranscript::Raw
953 }
954
955 fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command>;
961}
962
963pub fn supports_session(agent: &str) -> bool {
965 matches!(agent, "claude" | "kimi" | "minimax" | "grok")
966}
967
968const CLAUDE_COMPATIBLE_AGENTS: &[&str] = &["claude", "kimi", "minimax", "olm", "glm"];
971
972pub fn is_claude_compatible(agent_name: &str) -> bool {
974 CLAUDE_COMPATIBLE_AGENTS.contains(&agent_name)
975}
976
977pub fn get_runner(agent_name: &str) -> Box<dyn AgentRunner> {
978 match agent_name {
979 "claude" => Box::new(claude::ClaudeRunner::new(agent_name)),
980 "kimi" => Box::new(kimi::KimiClaudeRunner::new()),
981 "minimax" => Box::new(minimax::MiniMaxClaudeRunner::new(agent_name)),
982 "codex" => Box::new(codex::CodexRunner),
983 "opencode" => Box::new(opencode::OpenCodeRunner::new()),
984 "grok" => Box::new(grok::GrokRunner),
985 other => {
987 if !CLAUDE_COMPATIBLE_AGENTS.contains(&other) {
989 tracing::warn!(
990 agent = other,
991 "unknown agent, using claude-compatible runner"
992 );
993 }
994 Box::new(claude::ClaudeRunner::new(other))
995 }
996 }
997}
998
999pub(crate) fn parse_ndjson(raw: &str) -> Vec<serde_json::Value> {
1008 let events: Vec<serde_json::Value> = raw
1010 .lines()
1011 .filter(|line| !line.trim().is_empty())
1012 .filter_map(|line| match serde_json::from_str(line) {
1013 Ok(val) => Some(val),
1014 Err(e) => {
1015 tracing::debug!(line, error = %e, "skipping unparseable NDJSON line");
1016 None
1017 }
1018 })
1019 .collect();
1020
1021 if !events.is_empty() {
1025 return events;
1026 }
1027
1028 let acc: String = raw
1034 .lines()
1035 .filter(|line| {
1036 let t = line.trim();
1037 !t.is_empty() && !t.starts_with("//") && !t.starts_with('#')
1038 })
1039 .collect::<Vec<_>>()
1040 .join(" ");
1041
1042 if acc.is_empty() {
1043 return Vec::new();
1044 }
1045
1046 if let Ok(val) = serde_json::from_str::<serde_json::Value>(acc.trim()) {
1049 let stripped: String = acc.chars().filter(|c| !c.is_ascii_whitespace()).collect();
1054 if let Ok(stripped_val) = serde_json::from_str::<serde_json::Value>(&stripped) {
1055 if stripped_val == val {
1059 return Vec::new();
1060 }
1061 }
1062 return vec![val];
1063 }
1064
1065 extract_json_objects(&acc)
1069}
1070
1071fn extract_json_objects(text: &str) -> Vec<serde_json::Value> {
1076 let mut results = Vec::new();
1077 let mut start: Option<usize> = None;
1078 let mut depth: i32 = 0;
1079 let mut in_string = false;
1080 let mut escape = false;
1081
1082 for (idx, ch) in text.char_indices() {
1083 if let Some(start_idx) = start {
1084 if in_string {
1085 if escape {
1086 escape = false;
1087 } else if ch == '\\' {
1088 escape = true;
1089 } else if ch == '"' {
1090 in_string = false;
1091 }
1092 continue;
1093 }
1094
1095 match ch {
1096 '"' => in_string = true,
1097 '{' => depth += 1,
1098 '}' => {
1099 depth -= 1;
1100 if depth == 0 {
1101 let candidate = &text[start_idx..=idx];
1102 if let Ok(val) = serde_json::from_str::<serde_json::Value>(candidate) {
1103 results.push(val);
1104 }
1105 start = None;
1106 }
1107 }
1108 _ => {}
1109 }
1110 continue;
1111 }
1112
1113 if ch == '{' {
1114 start = Some(idx);
1115 depth = 1;
1116 in_string = false;
1117 escape = false;
1118 }
1119 }
1120
1121 results
1122}
1123
1124#[cfg(test)]
1125mod tests {
1126 use tracing::Level;
1127 use tracing_subscriber::EnvFilter;
1128 use tracing_subscriber::fmt::writer::MakeWriter;
1129 use tracing_subscriber::util::SubscriberInitExt;
1130
1131 use std::io;
1132 use std::io::Write;
1133 use std::sync::Arc;
1134 use std::sync::Mutex;
1135
1136 use super::*;
1137
1138 #[test]
1139 fn get_runner_returns_correct_types() {
1140 assert_eq!(get_runner("claude").name(), "claude");
1141 assert_eq!(get_runner("kimi").name(), "kimi");
1142 assert_eq!(get_runner("minimax").name(), "minimax");
1143 assert_eq!(get_runner("codex").name(), "codex");
1144 assert_eq!(get_runner("opencode").name(), "opencode");
1145 assert_eq!(get_runner("grok").name(), "grok");
1146 assert_eq!(
1147 get_runner("claude").router_transcript(),
1148 RouterTranscript::Messages
1149 );
1150 assert_eq!(
1151 get_runner("kimi").router_transcript(),
1152 RouterTranscript::Messages
1153 );
1154 assert_eq!(
1155 get_runner("minimax").router_transcript(),
1156 RouterTranscript::Messages
1157 );
1158 assert_eq!(
1159 get_runner("grok").router_transcript(),
1160 RouterTranscript::Messages
1161 );
1162 assert_eq!(
1163 get_runner("glm").router_transcript(),
1164 RouterTranscript::Messages
1165 );
1166 assert_eq!(
1167 get_runner("olm").router_transcript(),
1168 RouterTranscript::Messages
1169 );
1170 assert_eq!(
1171 get_runner("opencode").router_transcript(),
1172 RouterTranscript::OpenCode
1173 );
1174 assert_eq!(
1175 get_runner("codex").router_transcript(),
1176 RouterTranscript::Raw
1177 );
1178 assert!(supports_session("grok"));
1179 assert!(!supports_session("codex"));
1180 assert_eq!(get_runner("olm").name(), "olm");
1182 assert_eq!(get_runner("glm").name(), "glm");
1183 assert_eq!(get_runner("unknown-agent").name(), "unknown-agent");
1185 }
1186
1187 #[test]
1190 fn get_runner_no_warning_for_claude_compatible_agents() {
1191 struct CaptureWriter(Arc<Mutex<Vec<u8>>>);
1192 impl Write for CaptureWriter {
1193 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1194 self.0.lock().unwrap().extend_from_slice(buf);
1195 Ok(buf.len())
1196 }
1197 fn flush(&mut self) -> io::Result<()> {
1198 Ok(())
1199 }
1200 }
1201 impl<'a> MakeWriter<'a> for CaptureWriter {
1202 type Writer = CaptureWriter;
1203 fn make_writer(&'a self) -> Self::Writer {
1204 CaptureWriter(Arc::clone(&self.0))
1205 }
1206 }
1207
1208 let output: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
1209 let output_clone = Arc::clone(&output);
1210
1211 tracing_subscriber::fmt()
1212 .with_env_filter(EnvFilter::from_default_env().add_directive(Level::WARN.into()))
1213 .with_writer(CaptureWriter(output_clone))
1214 .with_ansi(false)
1215 .finish()
1216 .init();
1217
1218 for agent in &["claude", "kimi", "minimax", "olm", "glm", "grok"] {
1219 get_runner(agent);
1220 }
1221
1222 let captured = {
1223 let guard = output.lock().unwrap();
1224 String::from_utf8_lossy(&guard).to_string()
1225 };
1226 assert!(
1227 !captured.contains("unknown agent"),
1228 "known claude-compatible agents must not emit 'unknown agent' warnings; got: {captured}"
1229 );
1230 }
1231
1232 #[test]
1233 fn agent_error_display() {
1234 let e = AgentError::RateLimit {
1235 message: "429 Too Many Requests".to_string(),
1236 };
1237 assert!(e.to_string().contains("rate limit"));
1238
1239 let e = AgentError::Timeout {
1240 elapsed: Duration::from_mins(30),
1241 };
1242 assert!(e.to_string().contains("1800"));
1243 }
1244
1245 #[test]
1246 fn pattern_detect_rate_limit() {
1247 assert!(patterns::detect_rate_limit("Error: rate limit exceeded").is_some());
1248 assert!(patterns::detect_rate_limit("HTTP 429 Too Many Requests").is_some());
1249 assert!(patterns::detect_rate_limit("You've hit your usage limit").is_some());
1250 assert!(
1251 patterns::detect_rate_limit(
1252 "You've hit your session limit · resets 10:30am (America/Sao_Paulo)"
1253 )
1254 .is_some()
1255 );
1256 assert!(patterns::detect_rate_limit(
1257 "Upstream error from Alibaba: Request rate increased too quickly. \
1258 To ensure system stability, please adjust your client logic to scale requests more smoothly over time."
1259 ).is_some());
1260 assert!(patterns::detect_rate_limit("all good").is_none());
1261 }
1262
1263 #[test]
1264 fn classify_from_text_detects_weekly_limit_as_rate_limit() {
1265 let system_event = r#"{"type":"system","subtype":"error","error":{"type":"weekly_limit","message":"You've hit your weekly limit · resets Jun 9 at 1am (America/Sao_Paulo)"}}"#;
1269 let work_product = "{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"Working on the task...\"}]}}\n"
1270 .repeat(200);
1271 let text = format!("{system_event}\n{work_product}");
1272 assert!(
1273 text.len() > 3000,
1274 "test output must exceed tail window to be meaningful"
1275 );
1276 let err = patterns::classify_from_text(1, &text);
1277 assert!(
1278 matches!(err, AgentError::RateLimit { .. }),
1279 "weekly limit as early system event must be detected via head scan, got: {err:?}"
1280 );
1281 let msg = err.to_string();
1282 assert!(
1283 msg.contains("weekly limit"),
1284 "error message should reference weekly limit, got: {msg}"
1285 );
1286 }
1287
1288 #[test]
1289 fn detect_rate_limit_github_copilot_monthly_quota() {
1290 let err = patterns::detect_rate_limit("You have exceeded your monthly quota");
1294 assert!(
1295 matches!(err, Some(AgentError::RateLimit { .. })),
1296 "monthly quota exhaustion must be detected as rate limit, got: {err:?}"
1297 );
1298 }
1299
1300 #[test]
1301 fn detect_rate_limit_nvidia_resourceexhausted() {
1302 let opencode_error = r#"opencode agent error: agent failed: "Upstream error from Nvidia: ResourceExhausted: Worker local total request limit reached (42/32)""#;
1306 let err = patterns::detect_rate_limit(opencode_error);
1307 assert!(
1308 matches!(err, Some(AgentError::RateLimit { .. })),
1309 "Nvidia ResourceExhausted must be detected as rate limit, got: {err:?}"
1310 );
1311
1312 assert!(
1314 patterns::detect_rate_limit("ResourceExhausted: some capacity error").is_some(),
1315 "bare ResourceExhausted must match"
1316 );
1317 assert!(
1318 patterns::detect_rate_limit("Worker local total request limit reached (10/8)")
1319 .is_some(),
1320 "worker local total request limit reached must match"
1321 );
1322
1323 let err = patterns::classify_from_text(1, opencode_error);
1325 assert!(
1326 matches!(err, AgentError::RateLimit { .. }),
1327 "classify_from_text must produce RateLimit for Nvidia ResourceExhausted, got: {err:?}"
1328 );
1329 }
1330
1331 #[test]
1332 fn detect_rate_limit_message_contains_context_not_tail() {
1333 let padding = "x".repeat(5000);
1336 let text = format!(
1337 "{padding}you've reached your usage limit for this billing cycle{padding}\
1338 {{\"web_fetch_requests\":0,\"service_tier\":\"standard\"}}"
1339 );
1340 let err = patterns::detect_rate_limit(&text).expect("should detect");
1341 let msg = err.to_string();
1342 assert!(
1343 msg.contains("usage limit"),
1344 "message should contain the actual error, got: {msg}"
1345 );
1346 assert!(
1347 !msg.contains("web_fetch_requests"),
1348 "message should not be the tail JSON, got: {msg}"
1349 );
1350 }
1351
1352 #[test]
1353 fn pattern_detect_rate_limit_529_not_bare() {
1354 assert!(
1357 patterns::detect_rate_limit("error on line 529").is_none(),
1358 "bare line number 529 should not match"
1359 );
1360 assert!(
1361 patterns::detect_rate_limit("file size 529 bytes").is_none(),
1362 "bare file size 529 should not match"
1363 );
1364 assert!(
1365 patterns::detect_rate_limit("port :5290 in config").is_none(),
1366 "port number containing 529 should not match"
1367 );
1368 assert!(
1369 patterns::detect_rate_limit("timeout after 5290ms").is_none(),
1370 "duration containing 529 should not match"
1371 );
1372 assert!(
1374 patterns::detect_rate_limit("HTTP 529 Service Unavailable").is_some(),
1375 "HTTP 529 status should match"
1376 );
1377 assert!(
1378 patterns::detect_rate_limit("http 529").is_some(),
1379 "http 529 should match"
1380 );
1381 assert!(
1382 patterns::detect_rate_limit("529 service unavailable").is_some(),
1383 "529 service unavailable should match"
1384 );
1385 assert!(
1386 patterns::detect_rate_limit("status: 529").is_some(),
1387 "status: 529 should match"
1388 );
1389 }
1390
1391 #[test]
1392 fn pattern_detect_auth() {
1393 assert!(patterns::detect_auth_error("401 Unauthorized").is_some());
1394 assert!(patterns::detect_auth_error("HTTP 401").is_some());
1395 assert!(patterns::detect_auth_error("error: 401").is_some());
1396 assert!(patterns::detect_auth_error("403 Forbidden").is_some());
1397 assert!(patterns::detect_auth_error("HTTP 403").is_some());
1398 assert!(patterns::detect_auth_error("HTTP 407 Authentication Required").is_some());
1399 assert!(patterns::detect_auth_error("407 Proxy Authentication Required").is_some());
1400 assert!(patterns::detect_auth_error("invalid api key").is_some());
1401 assert!(patterns::detect_auth_error("billing expired").is_some());
1402 assert!(patterns::detect_auth_error("task done").is_none());
1403 assert!(patterns::detect_auth_error("duration_api_ms 4010292").is_none());
1405 assert!(
1406 patterns::detect_auth_error(
1407 "API Error: Unable to connect to API (ConnectionRefused) duration_api_ms 4010292"
1408 )
1409 .is_none()
1410 );
1411 assert!(patterns::detect_auth_error(r#""duration_api_ms": 4010292"#).is_none());
1413 assert!(
1414 patterns::detect_auth_error(
1415 r#"{"error":"ConnectionRefused","duration_api_ms": 4010292}"#
1416 )
1417 .is_none()
1418 );
1419 assert!(patterns::detect_auth_error("status: 401").is_some());
1421 assert!(patterns::detect_auth_error("error: 403").is_some());
1422 }
1423
1424 #[test]
1425 fn pattern_detect_auth_insufficient_balance() {
1426 assert!(
1431 patterns::detect_auth_error("402 Payment Required: insufficient balance").is_some(),
1432 "insufficient balance must be detected as auth error"
1433 );
1434 assert!(
1435 patterns::detect_auth_error("insufficient balance").is_some(),
1436 "bare insufficient balance must be detected as auth error"
1437 );
1438 let err = patterns::detect_auth_error("402 Payment Required: insufficient balance")
1440 .expect("should detect auth error");
1441 let AgentError::Auth { message } = err else {
1442 panic!("expected Auth, got {err:?}");
1443 };
1444 assert!(
1445 message.to_lowercase().contains("insufficient balance"),
1446 "stored message should contain the matched pattern, got: {message}"
1447 );
1448 assert!(
1450 message.lines().count() <= 2,
1451 "message should be the auth line, not the full tail: {}",
1452 message.len()
1453 );
1454 }
1455
1456 #[test]
1457 fn auth_error_message_contains_match_not_tail() {
1458 let mut text = "some output\nunauthorized: your api key has expired\nx".repeat(400);
1462 text.push_str(r#","outputTokens":744,"cacheReadInputTokens":344785,"uuid":"86d13b1f-..."#);
1463 let err = patterns::detect_auth_error(&text).expect("should detect auth error");
1464 let AgentError::Auth { message } = err else {
1465 panic!("expected Auth, got {err:?}");
1466 };
1467 assert!(
1468 message.to_lowercase().contains("unauthorized"),
1469 "stored message should contain the matched pattern, got: {message}"
1470 );
1471 assert!(
1472 !message.contains("outputTokens"),
1473 "stored message must not be the trailing NDJSON, got: {message}"
1474 );
1475 assert!(
1477 message.lines().count() <= 2,
1478 "message should be the auth line, not the full tail: {}",
1479 message.len()
1480 );
1481 }
1482
1483 #[test]
1484 fn pattern_detect_network_error() {
1485 assert!(patterns::detect_network_error("connection refused").is_some());
1486 assert!(patterns::detect_network_error("ConnectionRefused").is_some());
1487 assert!(patterns::detect_network_error("Unable to connect to API").is_some());
1488 assert!(patterns::detect_network_error("ECONNREFUSED").is_some());
1489 assert!(patterns::detect_network_error("network unreachable").is_some());
1490 assert!(patterns::detect_network_error("Upstream idle timeout exceeded").is_some());
1491 assert!(patterns::detect_network_error("upstream idle timeout").is_some());
1492 assert!(patterns::detect_network_error("Streaming response failed").is_some());
1493 assert!(patterns::detect_network_error("Upstream request failed").is_some());
1494 assert!(patterns::detect_network_error("all systems operational").is_none());
1495 }
1496
1497 #[test]
1498 fn network_error_message_contains_match_not_tail() {
1499 let prefix = "connection refused connecting to api.anthropic.com:443 ";
1501 let mut suffix = "x".repeat(2000);
1502 suffix.push_str(r#"":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0}"#);
1503 let text = format!("{prefix}{suffix}");
1504
1505 let err = patterns::detect_network_error(&text).expect("should detect network error");
1506 let AgentError::NetworkError { message } = err else {
1507 panic!("expected NetworkError, got {err:?}");
1508 };
1509 assert!(
1510 message.to_lowercase().contains("connection refused"),
1511 "stored message should contain the matched pattern, got: {message}"
1512 );
1513 assert!(
1514 !message.contains("web_fetch_requests"),
1515 "stored message must not be the unrelated stats tail, got: {message}"
1516 );
1517 }
1518
1519 #[test]
1520 fn pattern_detect_context_overflow() {
1521 assert!(patterns::detect_context_overflow("context_length_exceeded").is_some());
1522 assert!(patterns::detect_context_overflow("too many tokens in prompt").is_some());
1523 assert!(patterns::detect_context_overflow("success").is_none());
1524 }
1525
1526 #[test]
1527 fn pattern_detect_worktree_missing() {
1528 assert!(
1529 patterns::detect_worktree_missing("worktree directory does not exist: /tmp/wt")
1530 .is_some()
1531 );
1532 assert!(patterns::detect_worktree_missing("all good").is_none());
1533 }
1534
1535 #[test]
1536 fn pattern_detect_missing_tool() {
1537 assert!(patterns::detect_missing_tool("bun: command not found").is_some());
1538 assert!(patterns::detect_missing_tool("env: anchor: no such file").is_some());
1539 assert!(patterns::detect_missing_tool("everything works").is_none());
1540 }
1541
1542 #[test]
1543 fn pattern_detect_permission_denied() {
1544 assert!(patterns::detect_permission_denied("permission denied: /etc/hosts").is_some());
1545 assert!(patterns::detect_permission_denied("sandbox violation detected").is_some());
1546 assert!(patterns::detect_permission_denied("disallowed tool: Bash(rm *)").is_some());
1547 assert!(patterns::detect_permission_denied("task completed").is_none());
1548 }
1549
1550 #[test]
1551 fn pattern_detect_waiting_for_input() {
1552 assert!(patterns::detect_waiting_for_input("Enter passphrase for key").is_some());
1553 assert!(patterns::detect_waiting_for_input("1Password CLI required").is_some());
1554 assert!(
1555 patterns::detect_waiting_for_input("SSH authentication required for deploy key")
1556 .is_some()
1557 );
1558 assert!(
1559 patterns::detect_waiting_for_input("HTTP 407 Proxy Authentication Required").is_none()
1560 );
1561 assert!(patterns::detect_waiting_for_input("done").is_none());
1562 }
1563
1564 #[test]
1565 fn pattern_detect_stale_session() {
1566 let err = patterns::detect_stale_session(
1568 "No conversation found with session ID: 2be572c4-57bb-4f86-bc03-b593c329177c",
1569 );
1570 assert!(err.is_some(), "should detect stale session");
1571 if let Some(AgentError::StaleSession { session_id }) = err {
1572 assert_eq!(session_id, "2be572c4-57bb-4f86-bc03-b593c329177c");
1573 }
1574
1575 let err = patterns::detect_stale_session("no conversation found with session id: abc-123");
1577 assert!(err.is_some(), "should detect lowercase variant");
1578
1579 assert!(patterns::detect_stale_session("all good").is_none());
1581 assert!(patterns::detect_stale_session("conversation started").is_none());
1582
1583 let multibyte = "Straße: No conversation found with session ID: dead-beef";
1587 let err = patterns::detect_stale_session(multibyte);
1588 assert!(
1589 err.is_some(),
1590 "should detect stale session after multi-byte chars"
1591 );
1592 if let Some(AgentError::StaleSession { session_id }) = err {
1593 assert_eq!(session_id, "dead-beef");
1594 }
1595 }
1596
1597 #[test]
1598 fn stale_session_display() {
1599 let e = AgentError::StaleSession {
1600 session_id: "abc-123".to_string(),
1601 };
1602 assert!(e.to_string().contains("stale session"));
1603 assert!(e.to_string().contains("abc-123"));
1604 }
1605
1606 #[test]
1607 fn classify_from_text_timeout() {
1608 let err = patterns::classify_from_text(124, "");
1609 assert!(matches!(err, AgentError::Timeout { .. }));
1610 }
1611
1612 #[test]
1613 fn classify_from_text_missing_tool_before_rate_limit() {
1614 let err = patterns::classify_from_text(1, "bun: command not found rate limit");
1616 assert!(matches!(err, AgentError::MissingTool { .. }));
1617 }
1618
1619 #[test]
1620 fn classify_from_text_worktree_missing() {
1621 let err = patterns::classify_from_text(1, "worktree directory does not exist: /tmp/wt");
1622 assert!(matches!(err, AgentError::AgentFailed { .. }));
1623 }
1624
1625 #[test]
1626 fn classify_from_text_model_not_found_backtick() {
1627 let text = "codex failed: model unavailable (gpt-5.5): Reconnecting... 2/5 \
1631 (unexpected status 404 Not Found: The model `gpt-5.5` does not exist \
1632 or you do not have access to it.)";
1633 let err = patterns::classify_from_text(1, text);
1634 match err {
1635 AgentError::ModelUnavailable { model, .. } => assert_eq!(model, "gpt-5.5"),
1636 other => panic!("expected ModelUnavailable, got: {other:?}"),
1637 }
1638 }
1639
1640 #[test]
1641 fn classify_from_text_model_metadata_not_found() {
1642 let text = "Model metadata for `gpt-5.4` not found. Defaulting to fallback \
1643 metadata; this can degrade performance and cause issues.";
1644 let err = patterns::classify_from_text(1, text);
1645 match err {
1646 AgentError::ModelUnavailable { model, .. } => assert_eq!(model, "gpt-5.4"),
1647 other => panic!("expected ModelUnavailable, got: {other:?}"),
1648 }
1649 }
1650
1651 #[test]
1652 fn classify_from_text_no_false_positive_from_work_product() {
1653 let work_product = "Added `is_copilot_model(model) -> bool` helper\n\
1656 - Added copilot quota patterns to `parse_retry_at`\n\
1657 fn detect_rate_limit(text: &str) -> Option<AgentError> {\n\
1658 quota exceeded handling for billing cycle\n"
1659 .repeat(50); let actual_error = "\nerror: command not found: cargo\n";
1661 let text = format!("{work_product}{actual_error}");
1662 let err = patterns::classify_from_text(1, &text);
1663 assert!(
1664 !matches!(err, AgentError::RateLimit { .. }),
1665 "work product keywords must not trigger rate limit, got: {err:?}"
1666 );
1667 }
1668
1669 #[test]
1670 fn classify_from_text_still_detects_real_rate_limit_at_tail() {
1671 let padding = "normal agent work output ".repeat(100);
1674 let text = format!("{padding}\nError: rate limit exceeded (429 Too Many Requests)\n");
1675 let err = patterns::classify_from_text(1, &text);
1676 assert!(
1677 matches!(err, AgentError::RateLimit { .. }),
1678 "real rate limit at tail must be detected, got: {err:?}"
1679 );
1680 }
1681
1682 #[test]
1683 fn classify_from_text_ignores_markdown_rate_limit_table_at_tail() {
1684 let padding = "normal agent work output ".repeat(250);
1685 let text = format!(
1686 "{padding}\n+| agent | model | outcome | count |\n+| codex | gpt-5.4 | failed | 1 |\n+| kimi | opus | rate_limit | 1 |\n"
1687 );
1688 let err = patterns::classify_from_text(1, &text);
1689 assert!(
1690 !matches!(err, AgentError::RateLimit { .. }),
1691 "markdown table cell must not trigger rate limit, got: {err:?}"
1692 );
1693 }
1694
1695 #[test]
1696 fn classify_from_text_rate_limit_non_ascii_prefix_does_not_panic() {
1697 let text = "Aflαβrate_limit error: too many requests";
1701 let err = patterns::classify_from_text(1, text);
1702 assert!(
1703 matches!(err, AgentError::RateLimit { .. }),
1704 "real rate_limit should still be detected with non-ASCII prefix, got: {err:?}"
1705 );
1706 }
1707
1708 #[test]
1709 fn classify_from_text_detects_session_limit_as_early_system_event() {
1710 let system_event = r#"{"type":"system","subtype":"error","error":{"type":"session_limit","message":"You've hit your session limit · resets 4:10am (America/Sao_Paulo)"}}"#;
1716 let work_product = "{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"Working on the task...\"}]}}\n"
1719 .repeat(200);
1720 let text = format!("{system_event}\n{work_product}");
1721 assert!(
1723 text.len() > 3000,
1724 "test output must exceed tail window to be meaningful"
1725 );
1726 let err = patterns::classify_from_text(1, &text);
1727 assert!(
1728 matches!(err, AgentError::RateLimit { .. }),
1729 "session limit as early system event must be detected via head scan, got: {err:?}"
1730 );
1731 let msg = err.to_string();
1733 assert!(
1734 msg.contains("session limit"),
1735 "error message should contain the rate limit reason, got: {msg}"
1736 );
1737 }
1738
1739 #[test]
1740 fn classify_from_text_no_false_positive_auth_from_work_product() {
1741 let work_product = "if response.status == 401 { return Err(\"unauthorized\") }\n\
1745 // handle 403 forbidden errors\n\
1746 // billing checks happen elsewhere\n"
1747 .repeat(80);
1748 let actual_error = "\nerror: command not found: cargo\n";
1749 let text = format!("{work_product}{actual_error}");
1750 let err = patterns::classify_from_text(1, &text);
1751 assert!(
1752 !matches!(err, AgentError::Auth { .. }),
1753 "work product auth keywords must not trigger auth classification, got: {err:?}"
1754 );
1755 assert!(
1756 matches!(err, AgentError::MissingTool { .. }),
1757 "the real tail error should still win, got: {err:?}"
1758 );
1759 }
1760
1761 #[test]
1762 fn classify_from_text_still_detects_real_auth_at_tail() {
1763 let padding = "normal agent work output ".repeat(100);
1764 let text = format!("{padding}\nHTTP 401 Unauthorized\n");
1765 let err = patterns::classify_from_text(1, &text);
1766 assert!(
1767 matches!(err, AgentError::Auth { .. }),
1768 "real auth error at tail must be detected, got: {err:?}"
1769 );
1770 }
1771
1772 #[test]
1773 fn classify_from_text_no_false_positive_context_overflow_from_work_product() {
1774 let work_product = "const MAX_TOKEN_LIMIT = 10000;\n\
1778 // Ensure we don't exceed the token limit per request\n\
1779 fn check_token_limit(tokens: usize) { ... }\n\
1780 if total_tokens > MAX_TOKEN_LIMIT { ... }\n\
1781 // Note: too many tokens in the prompt causes context_length_exceeded\n"
1782 .repeat(80);
1783 let actual_error = "\nerror: command not found: cargo\n";
1784 let text = format!("{work_product}{actual_error}");
1785 let err = patterns::classify_from_text(1, &text);
1786 assert!(
1787 !matches!(err, AgentError::ContextOverflow { .. }),
1788 "work product context keywords must not trigger ContextOverflow, got: {err:?}"
1789 );
1790 assert!(
1791 matches!(err, AgentError::MissingTool { .. }),
1792 "the real tail error should still win, got: {err:?}"
1793 );
1794 }
1795
1796 #[test]
1797 fn classify_from_text_still_detects_real_context_overflow_at_tail() {
1798 let padding = "normal agent work output ".repeat(100);
1799 let text = format!("{padding}\nError: context_length_exceeded\n");
1800 let err = patterns::classify_from_text(1, &text);
1801 assert!(
1802 matches!(err, AgentError::ContextOverflow { .. }),
1803 "real context overflow at tail must be detected, got: {err:?}"
1804 );
1805 }
1806
1807 #[test]
1808 fn classify_from_text_no_false_positive_permission_denied_from_work_product() {
1809 let work_product = "match fs::metadata(path) {\n\
1813 Err(ref e) if e.kind() == ErrorKind::PermissionDenied => {\n\
1814 bail!(\"access denied: {path}\");\n\
1815 }\n\
1816 // Check if directory is writable\n\
1817 if !path.is_writable() { ... }\n\
1818 }\n"
1819 .repeat(80);
1820 let actual_error = "\nerror: command not found: cargo\n";
1821 let text = format!("{work_product}{actual_error}");
1822 let err = patterns::classify_from_text(1, &text);
1823 assert!(
1824 !matches!(err, AgentError::PermissionDenied { .. }),
1825 "work product permission keywords must not trigger PermissionDenied, got: {err:?}"
1826 );
1827 assert!(
1828 matches!(err, AgentError::MissingTool { .. }),
1829 "the real tail error should still win, got: {err:?}"
1830 );
1831 }
1832
1833 #[test]
1834 fn classify_from_text_still_detects_real_permission_denied_at_tail() {
1835 let padding = "normal agent work output ".repeat(100);
1836 let text = format!("{padding}\npermission denied: /etc/hosts\n");
1837 let err = patterns::classify_from_text(1, &text);
1838 assert!(
1839 matches!(err, AgentError::PermissionDenied { .. }),
1840 "real permission denied at tail must be detected, got: {err:?}"
1841 );
1842 }
1843
1844 #[test]
1845 fn classify_from_text_no_false_positive_waiting_for_input_from_work_product() {
1846 let work_product = "// Handle password prompts gracefully\n\
1850 if prompt.contains(\"password:\") {\n\
1851 log::warn!(\"Password prompt detected — skipping interactive step\");\n\
1852 }\n\
1853 // SSH agent will ask for the deploy key passphrase\n\
1854 fn handle_ssh_passphrase() { ... }\n\
1855 )\n"
1856 .repeat(80);
1857 let actual_error = "\nerror: command not found: cargo\n";
1858 let text = format!("{work_product}{actual_error}");
1859 let err = patterns::classify_from_text(1, &text);
1860 assert!(
1861 !matches!(err, AgentError::WaitingForInput { .. }),
1862 "work product input keywords must not trigger WaitingForInput, got: {err:?}"
1863 );
1864 assert!(
1865 matches!(err, AgentError::MissingTool { .. }),
1866 "the real tail error should still win, got: {err:?}"
1867 );
1868 }
1869
1870 #[test]
1871 fn classify_from_text_still_detects_real_waiting_for_input_at_tail() {
1872 let padding = "normal agent work output ".repeat(100);
1873 let text = format!("{padding}\nEnter passphrase for key:\n");
1874 let err = patterns::classify_from_text(1, &text);
1875 assert!(
1876 matches!(err, AgentError::WaitingForInput { .. }),
1877 "real waiting for input at tail must be detected, got: {err:?}"
1878 );
1879 }
1880
1881 #[test]
1882 fn classify_from_text_prefers_auth_over_permission_denied() {
1883 let err = patterns::classify_from_text(1, "HTTP 403 access denied: invalid token");
1884 assert!(
1885 matches!(err, AgentError::Auth { .. }),
1886 "auth errors must outrank permission denied, got: {err:?}"
1887 );
1888 }
1889
1890 #[test]
1891 fn classify_from_text_prefers_auth_over_waiting_for_input() {
1892 let err = patterns::classify_from_text(1, "HTTP 407 Proxy Authentication Required");
1893 assert!(
1894 matches!(err, AgentError::Auth { .. }),
1895 "HTTP auth failures must not be treated as waiting for input, got: {err:?}"
1896 );
1897 }
1898
1899 #[test]
1900 fn classify_from_text_detects_stale_session() {
1901 let text = "No conversation found with session ID: 2be572c4-57bb-4f86-bc03-b593c329177c";
1906 let err = patterns::classify_from_text(1, text);
1907 assert!(
1908 matches!(err, AgentError::StaleSession { .. }),
1909 "stale session must be detected via classify_from_text, got: {err:?}"
1910 );
1911 assert!(
1913 err.to_string().contains("stale session"),
1914 "error display must contain 'stale session' for recovery code to trigger"
1915 );
1916 }
1917
1918 #[test]
1919 fn classify_from_text_detects_socket_closed() {
1920 let text = "API Error: The socket connection was closed unexpectedly. \
1923 For more information, pass `verbose: true` in the second argument to fetch()";
1924 let err = patterns::classify_from_text(1, text);
1925 assert!(
1926 matches!(err, AgentError::NetworkError { .. }),
1927 "socket closed must be NetworkError, got: {err:?}"
1928 );
1929 }
1930
1931 #[test]
1932 fn classify_from_text_detects_socket_hang_up() {
1933 let err = patterns::classify_from_text(1, "Error: socket hang up");
1934 assert!(
1935 matches!(err, AgentError::NetworkError { .. }),
1936 "socket hang up must be NetworkError, got: {err:?}"
1937 );
1938 }
1939
1940 #[test]
1941 fn classify_from_text_detects_fetch_failed() {
1942 let err = patterns::classify_from_text(1, "TypeError: fetch failed");
1943 assert!(
1944 matches!(err, AgentError::NetworkError { .. }),
1945 "fetch failed must be NetworkError, got: {err:?}"
1946 );
1947 }
1948
1949 #[test]
1950 fn classify_from_text_detects_econnreset() {
1951 let err = patterns::classify_from_text(1, "read ECONNRESET");
1952 assert!(
1953 matches!(err, AgentError::NetworkError { .. }),
1954 "ECONNRESET must be NetworkError, got: {err:?}"
1955 );
1956 }
1957
1958 #[test]
1959 fn classify_from_text_detects_stalled_mid_stream() {
1960 let err = patterns::classify_from_text(
1963 1,
1964 "API Error: Response stalled mid-stream. The response above may be incomplete.",
1965 );
1966 assert!(
1967 matches!(err, AgentError::NetworkError { .. }),
1968 "stalled mid-stream must be NetworkError, got: {err:?}"
1969 );
1970 }
1971
1972 #[test]
1973 fn classify_from_text_detects_connection_closed_mid_response() {
1974 let err = patterns::classify_from_text(
1977 1,
1978 "API Error: Connection closed mid-response. The response above may be incomplete.",
1979 );
1980 assert!(
1981 matches!(err, AgentError::NetworkError { .. }),
1982 "connection closed mid-response must be NetworkError, got: {err:?}"
1983 );
1984 }
1985
1986 #[test]
1987 fn synthesize_response_marks_done_for_plain_text_no_op() {
1988 let response = synthesize_response_from_text(
1989 "No open positions, no trade executions, no conditions change. Full cash, holding.",
1990 )
1991 .unwrap();
1992
1993 assert_eq!(response.status, "done");
1994 assert_eq!(
1995 response.summary,
1996 "No open positions, no trade executions, no conditions change. Full cash, holding."
1997 );
1998 assert!(response.error.is_none());
1999 }
2000
2001 #[test]
2002 fn synthesize_response_marks_needs_review_for_plain_text_error() {
2003 let response =
2004 synthesize_response_from_text("Failed to update branch: permission denied").unwrap();
2005
2006 assert_eq!(response.status, "needs_review");
2007 assert_eq!(
2008 response.error.as_deref(),
2009 Some("agent returned plain text instead of JSON")
2010 );
2011 }
2012
2013 #[test]
2014 fn synthesize_response_rejects_empty_text() {
2015 assert!(synthesize_response_from_text(" \n\t ").is_none());
2016 }
2017
2018 #[test]
2024 fn synthesize_response_rejects_ndjson_event_stream() {
2025 let ndjson = r#"{"type":"step_start","timestamp":1,"part":{"type":"step-start"}}
2026{"type":"tool_use","timestamp":2,"name":"bash","input":{"cmd":"echo completed"}}
2027{"type":"step_finish","timestamp":3,"part":{"type":"step-finish","reason":"stop"}}"#;
2028 assert!(
2029 synthesize_response_from_text(ndjson).is_none(),
2030 "raw NDJSON must not be interpreted as agent prose"
2031 );
2032
2033 let single = r#"{"type":"step_finish","reason":"stop","completed":true}"#;
2034 assert!(
2035 synthesize_response_from_text(single).is_none(),
2036 "single-line NDJSON event must also be rejected"
2037 );
2038 }
2039
2040 #[test]
2041 fn synthesize_response_accepts_json_without_event_type() {
2042 let text = "The task is complete. Filed issue #1234 successfully.";
2046 let response = synthesize_response_from_text(text).expect("plain prose should synthesize");
2047 assert_eq!(response.status, "done");
2048 }
2049
2050 #[test]
2057 fn synthesize_response_returns_none_for_ambiguous_startup_text() {
2058 assert!(
2060 synthesize_response_from_text("Let's go!").is_none(),
2061 "startup greeting must not synthesize as needs_review"
2062 );
2063 assert!(
2065 synthesize_response_from_text(
2066 "I need to find where the stream command is implemented. \
2067 Looking at the CLI structure, it seems like the stream functionality \
2068 might be in the task module or another file. Let me check the CLI \
2069 command structure. First, let me look at the task module since stream \
2070 is related to tasks."
2071 )
2072 .is_none(),
2073 "exploratory prose must not synthesize as needs_review"
2074 );
2075 }
2076
2077 #[test]
2078 fn synthesize_response_does_not_mark_done_for_incomplete() {
2079 let response = synthesize_response_from_text("The task is incomplete").unwrap();
2080 assert_eq!(
2081 response.status, "needs_review",
2082 "\"incomplete\" should not match \"complete\""
2083 );
2084 }
2085
2086 #[test]
2087 fn synthesize_response_does_not_mark_done_for_not_done() {
2088 let response = synthesize_response_from_text("Changes are not done yet").unwrap();
2089 assert_eq!(
2090 response.status, "needs_review",
2091 "\"not done\" should not match bare \"done\""
2092 );
2093 }
2094
2095 #[test]
2096 fn synthesize_response_does_not_mark_done_for_not_complete() {
2097 let response = synthesize_response_from_text("Still in progress, not complete").unwrap();
2098 assert_eq!(
2099 response.status, "needs_review",
2100 "\"not complete\" should not match \"complete\""
2101 );
2102 }
2103
2104 #[test]
2105 fn synthesize_response_does_not_mark_done_for_not_yet_completed() {
2106 let response = synthesize_response_from_text("The task is not yet completed").unwrap();
2107 assert_eq!(
2108 response.status, "needs_review",
2109 "\"not yet completed\" should not match \"completed\""
2110 );
2111 }
2112
2113 #[test]
2114 fn synthesize_response_marks_done_for_completed() {
2115 let response =
2116 synthesize_response_from_text("Task has been completed successfully").unwrap();
2117 assert_eq!(response.status, "done");
2118 }
2119
2120 #[test]
2121 fn synthesize_response_marks_done_for_word_boundary_done() {
2122 let response = synthesize_response_from_text("All changes are done.").unwrap();
2123 assert_eq!(response.status, "done");
2124 }
2125
2126 #[test]
2127 fn synthesize_response_marks_done_for_issue_creation_text() {
2128 let response =
2129 synthesize_response_from_text("Filed 3 high-value GitHub issues: #1037, #1038, #1039")
2130 .unwrap();
2131
2132 assert_eq!(response.status, "done");
2133 assert!(response.error.is_none());
2134 assert!(
2135 response
2136 .summary
2137 .contains("Filed 3 high-value GitHub issues")
2138 );
2139 }
2140
2141 #[test]
2142 fn synthesize_response_marks_done_for_committed() {
2143 let response =
2144 synthesize_response_from_text("I've committed the changes to the repository").unwrap();
2145 assert_eq!(response.status, "done");
2146 }
2147
2148 #[test]
2149 fn synthesize_response_rejects_exploratory_prose() {
2150 let exploratory = "I explored the codebase and found several .expect()/.unwrap() uses.\n\nLet me check each occurrence directly and run the tests to be sure. I may commit fixes afterwards.";
2156 match synthesize_response_from_text(exploratory) {
2157 None => {
2158 }
2160 Some(resp) => {
2161 assert_ne!(
2162 resp.status, "done",
2163 "Exploratory prose must not be auto-marked done"
2164 );
2165 }
2166 }
2167 }
2168
2169 #[test]
2170 fn synthesize_response_marks_done_for_commit_created() {
2171 let response = synthesize_response_from_text(
2172 "Commit created locally. The push is being blocked by permissions.",
2173 )
2174 .unwrap();
2175 assert_eq!(response.status, "done");
2176 }
2177
2178 #[test]
2179 fn synthesize_response_does_not_mark_done_for_not_committed() {
2180 let response = synthesize_response_from_text("The changes are not committed yet").unwrap();
2181 assert_eq!(
2182 response.status, "needs_review",
2183 "\"not committed\" should not match \"committed\""
2184 );
2185 }
2186
2187 #[test]
2190 fn synthesize_response_marks_done_for_fix_is_complete() {
2191 let response = synthesize_response_from_text(
2195 "All 73 cooldown tests pass. The fix is complete.\n\n\
2196 **Summary of changes:**\n\n\
2197 1. **`src/store/kv.rs`** — Added `kv_increment()` method that uses a single \
2198 `INSERT … ON CONFLICT … DO UPDATE … RETURNING` SQL statement.",
2199 )
2200 .unwrap();
2201 assert_eq!(
2202 response.status, "done",
2203 "\"The fix is complete\" must be classified as done, not needs_review"
2204 );
2205 }
2206
2207 #[test]
2208 fn synthesize_response_marks_done_for_tests_pass_fix_working() {
2209 let response = synthesize_response_from_text(
2213 "All tests pass. The fix is clean and working.\n\n\
2214 **Summary of changes** to `src/engine/runner/response.rs:37`:\n\n\
2215 - **Before:** `capped + jitter` → range `[capped, 1.6*capped]`\n\
2216 - **After:** `capped.saturating_sub(jitter_range) + jitter` → range `[0.7*capped, 1.3*capped]`",
2217 )
2218 .unwrap();
2219 assert_eq!(
2220 response.status, "done",
2221 "\"All tests pass. The fix is clean and working.\" must be classified as done"
2222 );
2223 }
2224
2225 #[test]
2228 fn parse_ndjson_handles_standard_lines() {
2229 let raw = r#"{"type":"text","text":"hello"}
2230{"type":"text","text":"world"}"#;
2231 let events = parse_ndjson(raw);
2232 assert_eq!(events.len(), 2);
2233 assert_eq!(events[0].get("type").unwrap().as_str(), Some("text"));
2234 assert_eq!(events[1].get("type").unwrap().as_str(), Some("text"));
2235 }
2236
2237 #[test]
2238 fn parse_ndjson_skips_empty_lines() {
2239 let raw = r#"{"type":"text"}
2240
2241{"type":"text"}
2242"#;
2243 let events = parse_ndjson(raw);
2244 assert_eq!(events.len(), 2);
2245 }
2246
2247 #[test]
2248 fn parse_ndjson_skips_malformed_lines() {
2249 let raw = r#"{"type":"valid"}
2250not json at all
2251{"type":"also_valid"}"#;
2252 let events = parse_ndjson(raw);
2253 assert_eq!(events.len(), 2);
2254 }
2255
2256 #[test]
2257 fn parse_ndjson_fallback_extracts_embedded_json() {
2258 let raw =
2260 r#"text: {"text": "here is the result: ```json\n{\"status\":\"done\"}\n```"} more"#;
2261 let events = parse_ndjson(raw);
2262 assert!(
2264 !events.is_empty(),
2265 "should extract JSON objects via fallback"
2266 );
2267 }
2268
2269 #[test]
2270 fn parse_ndjson_fallback_handles_fragmented_objects() {
2271 let raw = r#"{"type": "text
2273", "content": "hello
2274world"}"#;
2275 let events = parse_ndjson(raw);
2276 assert!(!events.is_empty(), "should handle fragmented JSON");
2278 }
2279
2280 #[test]
2283 fn permission_rules_default_is_autonomous() {
2284 let rules = PermissionRules::default();
2285 assert!(rules.autonomous);
2286 }
2287
2288 #[test]
2289 fn permission_rules_default_sandbox_is_workspace_write() {
2290 let rules = PermissionRules::default();
2291 assert_eq!(rules.sandbox, SandboxLevel::WorkspaceWrite);
2292 }
2293
2294 #[test]
2295 fn permission_rules_default_disallows_rm() {
2296 let rules = PermissionRules::default();
2297 assert!(rules.disallowed_tools.contains(&"Bash(rm *)".to_string()));
2298 assert!(rules.disallowed_tools.contains(&"Bash(rm -*)".to_string()));
2299 }
2300
2301 #[test]
2302 fn permission_rules_default_no_allowed_edit_paths() {
2303 let rules = PermissionRules::default();
2304 assert!(
2305 rules.allowed_edit_paths.is_empty(),
2306 "{:?}",
2307 rules.allowed_edit_paths
2308 );
2309 }
2310
2311 #[test]
2315 fn all_agents_handle_default_permissions() {
2316 let perms = PermissionRules::default();
2317 let sys = "/tmp/sys.md";
2318 let msg = "/tmp/msg.md";
2319
2320 let claude = get_runner("claude");
2322 let cmd = claude.build_command(None, "", sys, msg, &perms);
2323 assert!(
2324 cmd.contains("--permission-mode bypassPermissions"),
2325 "claude default: expected bypassPermissions, got: {cmd}"
2326 );
2327 assert!(
2328 cmd.contains("Bash(rm *)"),
2329 "claude default: expected rm disallowed, got: {cmd}"
2330 );
2331
2332 let codex = get_runner("codex");
2334 let cmd = codex.build_command(None, "", sys, msg, &perms);
2335 assert!(
2336 cmd.contains("--sandbox workspace-write"),
2337 "codex default: expected --sandbox workspace-write, got: {cmd}"
2338 );
2339 assert!(
2340 cmd.contains(r#"-c 'approval_policy="never"'"#),
2341 "codex default: expected -c approval_policy=never, got: {cmd}"
2342 );
2343 assert!(
2344 !cmd.contains("--ask-for-approval"),
2345 "codex default: --ask-for-approval was removed in 0.133.0 and must not appear, got: {cmd}"
2346 );
2347 assert!(
2348 !cmd.contains("--full-auto"),
2349 "codex default: --full-auto is deprecated and must not appear, got: {cmd}"
2350 );
2351
2352 let opencode = get_runner("opencode");
2355 let cmd = opencode.build_command(None, "", sys, msg, &perms);
2356 assert!(
2357 cmd.contains("--dangerously-skip-permissions"),
2358 "opencode default: should pass --dangerously-skip-permissions, got: {cmd}"
2359 );
2360 assert!(
2361 !cmd.contains("opencode.json"),
2362 "opencode default: should not write a config file, got: {cmd}"
2363 );
2364 assert!(
2365 !cmd.contains("XDG_CONFIG_HOME"),
2366 "opencode default: should not override XDG_CONFIG_HOME, got: {cmd}"
2367 );
2368 assert!(
2369 !cmd.contains(".orch-opencode"),
2370 "opencode default: should not reference .orch-opencode, got: {cmd}"
2371 );
2372 }
2373
2374 #[test]
2376 fn all_agents_handle_supervised_mode() {
2377 let perms = PermissionRules {
2378 autonomous: false,
2379 sandbox: SandboxLevel::WorkspaceWrite,
2380 disallowed_tools: vec![],
2381 allowed_tools: vec![],
2382 allowed_edit_paths: vec![],
2383 deny_read_only: false,
2384 extra_writable_dirs: vec![],
2385 };
2386 let sys = "/tmp/sys.md";
2387 let msg = "/tmp/msg.md";
2388
2389 let claude = get_runner("claude");
2391 let cmd = claude.build_command(None, "", sys, msg, &perms);
2392 assert!(
2393 cmd.contains("--permission-mode acceptEdits"),
2394 "claude supervised: expected acceptEdits, got: {cmd}"
2395 );
2396
2397 let codex = get_runner("codex");
2399 let cmd = codex.build_command(None, "", sys, msg, &perms);
2400 assert!(
2401 cmd.contains(r#"-c 'approval_policy="on-request"'"#),
2402 "codex supervised: expected -c approval_policy=on-request, got: {cmd}"
2403 );
2404 assert!(
2405 !cmd.contains("--ask-for-approval"),
2406 "codex supervised: --ask-for-approval was removed in 0.133.0 and must not appear, got: {cmd}"
2407 );
2408 }
2409
2410 #[test]
2412 fn all_agents_handle_full_access_sandbox() {
2413 let perms = PermissionRules {
2414 autonomous: true,
2415 sandbox: SandboxLevel::FullAccess,
2416 disallowed_tools: vec![],
2417 allowed_tools: vec![],
2418 allowed_edit_paths: vec![],
2419 deny_read_only: false,
2420 extra_writable_dirs: vec![],
2421 };
2422 let sys = "/tmp/sys.md";
2423 let msg = "/tmp/msg.md";
2424
2425 let claude = get_runner("claude");
2427 let cmd = claude.build_command(None, "", sys, msg, &perms);
2428 assert!(
2429 !cmd.contains("--sandbox"),
2430 "claude full_access: should have no sandbox flag, got: {cmd}"
2431 );
2432
2433 let codex = get_runner("codex");
2435 let cmd = codex.build_command(None, "", sys, msg, &perms);
2436 assert!(
2437 cmd.contains("--dangerously-bypass-approvals-and-sandbox"),
2438 "codex full_access: expected dangerously-bypass, got: {cmd}"
2439 );
2440 }
2441
2442 #[test]
2444 fn codex_sandbox_none_uses_workspace_write() {
2445 let perms = PermissionRules {
2446 autonomous: true,
2447 sandbox: SandboxLevel::None,
2448 disallowed_tools: vec![],
2449 allowed_tools: vec![],
2450 allowed_edit_paths: vec![],
2451 deny_read_only: false,
2452 extra_writable_dirs: vec![],
2453 };
2454 let codex = get_runner("codex");
2455 let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2456 assert!(
2457 cmd.contains("--sandbox workspace-write"),
2458 "codex sandbox::none + autonomous: should use --sandbox workspace-write, got: {cmd}"
2459 );
2460 assert!(
2461 cmd.contains(r#"-c 'approval_policy="never"'"#),
2462 "codex sandbox::none + autonomous: should use -c approval_policy=never, got: {cmd}"
2463 );
2464 assert!(
2465 !cmd.contains("--ask-for-approval"),
2466 "codex sandbox::none: --ask-for-approval was removed in 0.133.0, got: {cmd}"
2467 );
2468 assert!(
2469 !cmd.contains("--full-auto"),
2470 "codex sandbox::none: --full-auto is deprecated and must not appear, got: {cmd}"
2471 );
2472 }
2473
2474 #[test]
2476 fn claude_allowed_edit_paths_scope_edit_write() {
2477 let perms = PermissionRules {
2478 autonomous: true,
2479 sandbox: SandboxLevel::WorkspaceWrite,
2480 disallowed_tools: vec![],
2481 allowed_tools: vec![
2482 "Edit".to_string(),
2483 "Write".to_string(),
2484 "Read".to_string(),
2485 "Bash".to_string(),
2486 ],
2487 allowed_edit_paths: vec![PathBuf::from("/home/user/worktree")],
2488 deny_read_only: false,
2489 extra_writable_dirs: vec![],
2490 };
2491 let claude = get_runner("claude");
2492 let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2493
2494 assert!(
2496 cmd.contains("Edit(/home/user/worktree/*)"),
2497 "missing scoped Edit, got: {cmd}"
2498 );
2499 assert!(
2500 cmd.contains("Write(/home/user/worktree/*)"),
2501 "missing scoped Write, got: {cmd}"
2502 );
2503 assert!(cmd.contains("Read"), "missing Read");
2505 }
2506
2507 #[test]
2509 fn codex_ignores_allowed_edit_paths() {
2510 let perms = PermissionRules {
2511 autonomous: true,
2512 sandbox: SandboxLevel::WorkspaceWrite,
2513 disallowed_tools: vec![],
2514 allowed_tools: vec![],
2515 allowed_edit_paths: vec![PathBuf::from("/home/user/project")],
2516 deny_read_only: false,
2517 extra_writable_dirs: vec![],
2518 };
2519 let codex = get_runner("codex");
2520 let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2521 assert!(
2522 !cmd.contains("/home/user/project"),
2523 "codex: should not reference blocked paths, got: {cmd}"
2524 );
2525 }
2526
2527 #[test]
2529 fn opencode_ignores_allowed_edit_paths() {
2530 let perms = PermissionRules {
2531 autonomous: true,
2532 sandbox: SandboxLevel::WorkspaceWrite,
2533 disallowed_tools: vec![],
2534 allowed_tools: vec![],
2535 allowed_edit_paths: vec![PathBuf::from("/home/user/project")],
2536 deny_read_only: false,
2537 extra_writable_dirs: vec![],
2538 };
2539 let opencode = get_runner("opencode");
2540 let cmd = opencode.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2541 assert!(
2542 !cmd.contains("/home/user/project"),
2543 "opencode: should not reference blocked paths, got: {cmd}"
2544 );
2545 }
2546
2547 #[test]
2549 fn claude_merges_disallowed_tools() {
2550 let perms = PermissionRules {
2551 autonomous: true,
2552 sandbox: SandboxLevel::WorkspaceWrite,
2553 disallowed_tools: vec![
2554 "Bash(rm *)".to_string(),
2555 "Bash(sudo *)".to_string(),
2556 "WebFetch".to_string(),
2557 ],
2558 allowed_tools: vec![],
2559 allowed_edit_paths: vec![],
2560 deny_read_only: false,
2561 extra_writable_dirs: vec![],
2562 };
2563 let claude = get_runner("claude");
2564 let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2565 assert!(cmd.contains("Bash(rm *)"), "missing rm disallow");
2566 assert!(cmd.contains("Bash(sudo *)"), "missing sudo disallow");
2567 assert!(cmd.contains("WebFetch"), "missing WebFetch disallow");
2568 }
2569
2570 #[test]
2572 fn codex_ignores_disallowed_tools() {
2573 let perms = PermissionRules {
2574 autonomous: true,
2575 sandbox: SandboxLevel::WorkspaceWrite,
2576 disallowed_tools: vec!["Bash(rm *)".to_string(), "WebFetch".to_string()],
2577 allowed_tools: vec![],
2578 allowed_edit_paths: vec![],
2579 deny_read_only: false,
2580 extra_writable_dirs: vec![],
2581 };
2582 let codex = get_runner("codex");
2583 let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2584 assert!(
2585 !cmd.contains("disallow"),
2586 "codex: should not have disallow flags, got: {cmd}"
2587 );
2588 }
2589
2590 #[test]
2592 fn claude_no_disallowed_flag_when_empty() {
2593 let perms = PermissionRules {
2594 autonomous: true,
2595 sandbox: SandboxLevel::WorkspaceWrite,
2596 disallowed_tools: vec![],
2597 allowed_tools: vec![],
2598 allowed_edit_paths: vec![],
2599 deny_read_only: false,
2600 extra_writable_dirs: vec![],
2601 };
2602 let claude = get_runner("claude");
2603 let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2604 assert!(
2605 !cmd.contains("--disallowedTools"),
2606 "claude: should have no disallowed flag when empty, got: {cmd}"
2607 );
2608 }
2609
2610 #[test]
2612 fn kimi_minimax_use_claude_permissions() {
2613 let perms = PermissionRules {
2614 autonomous: false,
2615 sandbox: SandboxLevel::WorkspaceWrite,
2616 disallowed_tools: vec!["Bash(rm *)".to_string()],
2617 allowed_tools: vec![],
2618 allowed_edit_paths: vec![],
2619 deny_read_only: false,
2620 extra_writable_dirs: vec![],
2621 };
2622 let sys = "/tmp/sys.md";
2623 let msg = "/tmp/msg.md";
2624
2625 for agent in &["kimi", "minimax"] {
2626 let runner = get_runner(agent);
2627 let cmd = runner.build_command(None, "", sys, msg, &perms);
2628 assert!(
2629 cmd.contains("--permission-mode acceptEdits"),
2630 "{agent}: expected acceptEdits"
2631 );
2632 assert!(
2633 cmd.contains("Bash(rm *)"),
2634 "{agent}: expected rm disallowed"
2635 );
2636 }
2637 }
2638
2639 #[test]
2641 fn kimi_minimax_use_allowed_tools() {
2642 let perms = PermissionRules {
2643 autonomous: true,
2644 sandbox: SandboxLevel::WorkspaceWrite,
2645 disallowed_tools: vec![],
2646 allowed_tools: vec!["Edit".to_string(), "Bash".to_string(), "git".to_string()],
2647 allowed_edit_paths: vec![],
2648 deny_read_only: false,
2649 extra_writable_dirs: vec![],
2650 };
2651
2652 for agent in &["kimi", "minimax"] {
2653 let runner = get_runner(agent);
2654 let cmd = runner.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2655 assert!(
2656 cmd.contains("--allowedTools"),
2657 "{agent}: expected --allowedTools, got: {cmd}"
2658 );
2659 assert!(
2660 cmd.contains("Bash(git *)"),
2661 "{agent}: expected Bash(git *) pattern, got: {cmd}"
2662 );
2663 }
2664 }
2665
2666 #[test]
2670 fn claude_allowed_tools_generates_allowedtools_flag() {
2671 let perms = PermissionRules {
2672 autonomous: true,
2673 sandbox: SandboxLevel::WorkspaceWrite,
2674 disallowed_tools: vec!["Bash(rm *)".to_string()],
2675 allowed_tools: vec![
2676 "Edit".to_string(),
2677 "Write".to_string(),
2678 "Read".to_string(),
2679 "Bash".to_string(),
2680 "git".to_string(),
2681 ],
2682 allowed_edit_paths: vec![],
2683 deny_read_only: false,
2684 extra_writable_dirs: vec![],
2685 };
2686
2687 let claude = get_runner("claude");
2688 let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2689 assert!(
2690 cmd.contains("--allowedTools"),
2691 "expected --allowedTools, got: {cmd}"
2692 );
2693 assert!(
2694 !cmd.contains("--disallowedTools"),
2695 "should not have --disallowedTools when allowed_tools is set"
2696 );
2697 }
2698
2699 #[test]
2701 fn codex_opencode_ignore_allowed_tools() {
2702 let perms = PermissionRules {
2703 autonomous: true,
2704 sandbox: SandboxLevel::WorkspaceWrite,
2705 disallowed_tools: vec![],
2706 allowed_tools: vec!["Edit".to_string(), "git".to_string()],
2707 allowed_edit_paths: vec![],
2708 deny_read_only: false,
2709 extra_writable_dirs: vec![],
2710 };
2711
2712 let codex = get_runner("codex");
2713 let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2714 assert!(
2715 !cmd.contains("--allowedTools"),
2716 "codex should not have --allowedTools, got: {cmd}"
2717 );
2718
2719 let opencode = get_runner("opencode");
2720 let cmd = opencode.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2721 assert!(
2722 !cmd.contains("--allowedTools"),
2723 "opencode should not have --allowedTools, got: {cmd}"
2724 );
2725 }
2726
2727 #[test]
2732 #[ignore = "reads the operator config"]
2733 fn integration_from_config_to_agent_commands() {
2734 let perms = PermissionRules::from_config();
2735
2736 assert!(
2738 perms.autonomous,
2739 "from_config: expected autonomous=true by default"
2740 );
2741
2742 for agent_name in &["claude", "codex", "opencode", "kimi", "minimax"] {
2744 let runner = get_runner(agent_name);
2745 let cmd =
2746 runner.build_command(None, "timeout 1800", "/tmp/sys.md", "/tmp/msg.md", &perms);
2747 assert!(
2748 !cmd.is_empty(),
2749 "{agent_name}: build_command returned empty string"
2750 );
2751 assert!(
2752 cmd.contains(agent_name) || *agent_name == "kimi" || *agent_name == "minimax",
2753 "{agent_name}: command should reference agent binary, got: {cmd}"
2754 );
2755 }
2756 }
2757
2758 #[test]
2761 #[ignore = "reads the operator config"]
2762 fn integration_supervised_config_translates_correctly() {
2763 let perms = PermissionRules::from_config();
2768
2769 let claude = get_runner("claude");
2770 let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2771
2772 if perms.autonomous {
2773 assert!(
2774 cmd.contains("bypassPermissions"),
2775 "autonomous config → bypassPermissions"
2776 );
2777 } else {
2778 assert!(
2779 cmd.contains("acceptEdits"),
2780 "supervised config → acceptEdits"
2781 );
2782 }
2783
2784 let codex = get_runner("codex");
2785 let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2786
2787 if perms.autonomous {
2788 assert!(
2790 cmd.contains("--sandbox workspace-write"),
2791 "autonomous config → --sandbox workspace-write, got: {cmd}"
2792 );
2793 assert!(
2794 cmd.contains(r#"-c 'approval_policy="never"'"#),
2795 "autonomous config → -c approval_policy=never, got: {cmd}"
2796 );
2797 } else {
2798 assert!(
2799 cmd.contains(r#"-c 'approval_policy="on-request"'"#),
2800 "supervised config → -c approval_policy=on-request, got: {cmd}"
2801 );
2802 }
2803 assert!(
2804 !cmd.contains("--ask-for-approval"),
2805 "--ask-for-approval was removed in codex 0.133.0 and must not appear, got: {cmd}"
2806 );
2807 }
2808
2809 #[test]
2813 fn deny_read_only_blocks_reading_tools() {
2814 let perms = PermissionRules::deny_read_only();
2815
2816 let read_tools = [
2817 "Bash(ls *)",
2818 "Bash(ls)",
2819 "Bash(find *)",
2820 "Bash(cat *)",
2821 "Bash(head *)",
2822 "Bash(tail *)",
2823 "Bash(fzf *)",
2824 "Bash(less *)",
2825 "Bash(more *)",
2826 "Read",
2827 "Glob",
2828 "Grep",
2829 ];
2830
2831 for tool in read_tools {
2832 assert!(
2833 perms.disallowed_tools.contains(&tool.to_string()),
2834 "deny_read_only should block {tool}, got: {:?}",
2835 perms.disallowed_tools
2836 );
2837 }
2838 }
2839
2840 #[test]
2842 fn deny_read_only_claude_command() {
2843 let perms = PermissionRules::deny_read_only();
2844 let claude = get_runner("claude");
2845 let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2846
2847 assert!(
2849 cmd.contains("Read"),
2850 "should block Read for control session"
2851 );
2852 assert!(
2853 cmd.contains("Glob"),
2854 "should block Glob for control session"
2855 );
2856 assert!(
2857 cmd.contains("Grep"),
2858 "should block Grep for control session"
2859 );
2860 assert!(
2862 cmd.contains("Bash(ls") || cmd.contains("Bash(ls *)"),
2863 "should block ls"
2864 );
2865 assert!(
2867 cmd.contains("--permission-mode bypassPermissions"),
2868 "should be autonomous (bypassPermissions)"
2869 );
2870 }
2871
2872 #[test]
2875 fn synthesize_extracts_file_paths() {
2876 let text = "Fixed the issue by modifying src/engine/runner/agents/mod.rs and tests/integration.rs.";
2877 let resp = synthesize_response_from_text(text).unwrap();
2878 assert!(
2879 resp.files
2880 .contains(&"src/engine/runner/agents/mod.rs".to_string()),
2881 "expected src/engine/runner/agents/mod.rs in files, got: {:?}",
2882 resp.files
2883 );
2884 assert!(
2885 resp.files.contains(&"tests/integration.rs".to_string()),
2886 "expected tests/integration.rs in files, got: {:?}",
2887 resp.files
2888 );
2889 }
2890
2891 #[test]
2892 fn synthesize_extracts_accomplished_bullets() {
2893 let text = "All tests pass.\n- Added logging to src/foo.rs\n- Updated migration file";
2894 let resp = synthesize_response_from_text(text).unwrap();
2895 assert_eq!(resp.status, "done");
2896 assert!(
2897 resp.accomplished
2898 .iter()
2899 .any(|a| a.contains("Added logging")),
2900 "expected accomplished bullet, got: {:?}",
2901 resp.accomplished
2902 );
2903 assert!(
2904 resp.accomplished
2905 .iter()
2906 .any(|a| a.contains("Updated migration")),
2907 "expected accomplished bullet, got: {:?}",
2908 resp.accomplished
2909 );
2910 }
2911
2912 #[test]
2913 fn synthesize_extracts_remaining_section() {
2914 let text = "Completed the main fix.\n- Patched src/lib.rs\n\nRemaining:\n- Write unit tests\n- Update docs";
2915 let resp = synthesize_response_from_text(text).unwrap();
2916 assert!(
2917 resp.remaining
2918 .iter()
2919 .any(|r| r.contains("Write unit tests")),
2920 "expected remaining item, got: {:?}",
2921 resp.remaining
2922 );
2923 assert!(
2924 resp.remaining.iter().any(|r| r.contains("Update docs")),
2925 "expected remaining item, got: {:?}",
2926 resp.remaining
2927 );
2928 assert!(
2929 resp.accomplished.iter().any(|a| a.contains("Patched")),
2930 "expected accomplished item, got: {:?}",
2931 resp.accomplished
2932 );
2933 }
2934
2935 #[test]
2936 fn synthesize_fixed_phrase_is_done() {
2937 let text = "Fixed. The bug no longer reproduces.";
2938 let resp = synthesize_response_from_text(text).unwrap();
2939 assert_eq!(resp.status, "done", "expected done for 'Fixed.' text");
2940 }
2941
2942 #[test]
2949 fn detect_rate_limit_fires_on_bare_429_in_token_count() {
2950 let payload = r#"{"type":"result","terminal_reason":"completed","outputTokens":429,"is_error":false}"#;
2954 assert!(
2955 patterns::detect_rate_limit(payload).is_some(),
2956 "detect_rate_limit must still fire on bare 429 so callers apply the guard"
2957 );
2958 }
2959
2960 #[test]
2961 fn detect_rate_limit_ignores_429_inside_longer_number() {
2962 let uuid = r#"{"type":"hook","uuid":"a1b2c3d4-4295-4e5f-8a9b-0c1d2e3f4a5b"}"#;
2963 assert!(
2964 patterns::detect_rate_limit(uuid).is_none(),
2965 "429 inside a UUID digit run must not match"
2966 );
2967 }
2968
2969 #[test]
2970 fn detect_rate_limit_ignores_429_in_uuid_hex_group() {
2971 let hook = r#"{"type":"system","subtype":"hook_response","hook_id":"18db61b6-7b72-429c-8279-fae3089bf565"}"#;
2972 assert!(patterns::detect_rate_limit(hook).is_none());
2973 }
2974
2975 #[test]
2976 fn detect_rate_limit_429_message_comes_from_matched_line() {
2977 let filler = "unrelated agent prose that is long enough to fill the window. ".repeat(20);
2978 let text = format!("HTTP 429 Too Many Requests\n{filler}");
2979 match patterns::detect_rate_limit(&text) {
2980 Some(AgentError::RateLimit { message }) => assert!(message.contains("429")),
2981 other => panic!("expected RateLimit, got {other:?}"),
2982 }
2983 }
2984
2985 #[test]
2989 fn terminal_reason_completed_guard_suppresses_false_rate_limit() {
2990 let raw_output = r#"{"type":"result","terminal_reason":"completed","outputTokens":429,"is_error":false}"#;
2991 let ndjson_completed = raw_output.contains("\"terminal_reason\":\"completed\"")
2992 && !raw_output.contains("\"is_error\":true");
2993 let detected = (!ndjson_completed)
2995 .then(|| patterns::detect_rate_limit(raw_output))
2996 .flatten();
2997 assert!(
2998 detected.is_none(),
2999 "guard must suppress rate-limit false positive from token-count 429 when terminal_reason:completed"
3000 );
3001 }
3002
3003 #[test]
3005 fn terminal_reason_completed_guard_passes_real_rate_limit() {
3006 let raw_output = "Error: 429 Too Many Requests — you have exceeded your quota";
3008 let ndjson_completed = raw_output.contains("\"terminal_reason\":\"completed\"")
3009 && !raw_output.contains("\"is_error\":true");
3010 let detected = (!ndjson_completed)
3011 .then(|| patterns::detect_rate_limit(raw_output))
3012 .flatten();
3013 assert!(
3014 detected.is_some(),
3015 "guard must NOT suppress a real rate-limit error"
3016 );
3017 }
3018
3019 #[test]
3020 fn synthesize_no_false_positive_file_paths() {
3021 let text = "See https://example.com/foo.rs for details. Version 1.2.3 is fine.";
3025 match synthesize_response_from_text(text) {
3026 None => {} Some(resp) => {
3028 assert!(
3029 resp.files.is_empty(),
3030 "expected no file paths extracted from URL text, got: {:?}",
3031 resp.files
3032 );
3033 }
3034 }
3035 }
3036
3037 #[test]
3042 fn synthesize_rejects_cli_parser_diagnostics_unexpected_argument() {
3043 let text = "error: unexpected argument '--ask-for-approval' found\n \
3045 tip: to pass '--ask-for-approval' as a value, use '-- --ask-for-approval'\n\
3046 Usage: codex exec [OPTIONS] [PROMPT]";
3047 assert!(
3048 synthesize_response_from_text(text).is_none(),
3049 "CLI parser diagnostic must not synthesize as agent response"
3050 );
3051 }
3052
3053 #[test]
3054 fn synthesize_rejects_cli_parser_diagnostics_usage_line() {
3055 let text = "Usage: mycommand [OPTIONS] <arg>";
3056 assert!(
3057 synthesize_response_from_text(text).is_none(),
3058 "Usage line must not synthesize as agent response"
3059 );
3060 }
3061
3062 #[test]
3063 fn synthesize_rejects_cli_parser_diagnostics_help_hint() {
3064 let text = "Error: unknown flag --foo\nFor more information, try '--help'";
3065 assert!(
3066 synthesize_response_from_text(text).is_none(),
3067 "Help hint must not synthesize as agent response"
3068 );
3069 }
3070
3071 #[test]
3072 fn synthesize_rejects_cli_parser_diagnostics_tip() {
3073 let text = "error: bad value\ntip: to pass '--flag' as a value, use '-- --flag'";
3074 assert!(
3075 synthesize_response_from_text(text).is_none(),
3076 "Clap tip must not synthesize as agent response"
3077 );
3078 }
3079
3080 #[test]
3081 fn synthesize_accepts_agent_error_messages_that_mention_error() {
3082 let text = "I tried to run the command but got an error: permission denied on that file.";
3085 let response =
3086 synthesize_response_from_text(text).expect("agent error message should synthesize");
3087 assert_eq!(response.status, "needs_review");
3088 assert!(response.error.is_some());
3089 }
3090
3091 #[test]
3096 fn synthesize_rejects_exact_codex_cli_error() {
3097 let stderr_from_codex = "error: unexpected argument '--ask-for-approval' found\n \
3098 tip: to pass '--ask-for-approval' as a value, use '-- --ask-for-approval'\n\
3099 Usage: codex exec [OPTIONS] [PROMPT]";
3100 assert!(
3101 synthesize_response_from_text(stderr_from_codex).is_none(),
3102 "exact codex CLI error from #3197 must not synthesize as agent response"
3103 );
3104 }
3105}