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 build_command_with_effort(
892 &self,
893 model: Option<&str>,
894 _effort: Option<&str>,
895 timeout_cmd: &str,
896 sys_file: &str,
897 msg_file: &str,
898 permissions: &PermissionRules,
899 ) -> String {
900 self.build_command(model, timeout_cmd, sys_file, msg_file, permissions)
901 }
902
903 fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError>;
908
909 fn extract_text(&self, raw: &str) -> Result<String, AgentError> {
924 Ok(raw.to_string())
925 }
926
927 fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent>;
929
930 fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError;
935
936 fn classify_error_with_elapsed(
938 &self,
939 exit_code: i32,
940 stdout: &str,
941 stderr: &str,
942 elapsed_secs: Option<u64>,
943 ) -> AgentError {
944 let mut err = self.classify_error(exit_code, stdout, stderr);
945 if let AgentError::Timeout { elapsed } = &mut err
946 && let Some(actual_elapsed) = elapsed_secs
947 {
948 *elapsed = Duration::from_secs(actual_elapsed);
949 }
950 err
951 }
952
953 fn available_models(&self) -> Vec<String> {
955 vec![]
956 }
957
958 fn free_models(&self) -> Vec<String> {
960 vec![]
961 }
962
963 fn router_transcript(&self) -> RouterTranscript {
965 RouterTranscript::Raw
966 }
967
968 fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command>;
974}
975
976pub fn supports_session(agent: &str) -> bool {
978 matches!(agent, "claude" | "kimi" | "minimax" | "grok")
979}
980
981const CLAUDE_COMPATIBLE_AGENTS: &[&str] = &["claude", "kimi", "minimax", "olm", "glm"];
984
985pub fn is_claude_compatible(agent_name: &str) -> bool {
987 CLAUDE_COMPATIBLE_AGENTS.contains(&agent_name)
988}
989
990pub fn get_runner(agent_name: &str) -> Box<dyn AgentRunner> {
991 match agent_name {
992 "claude" => Box::new(claude::ClaudeRunner::new(agent_name)),
993 "kimi" => Box::new(kimi::KimiClaudeRunner::new()),
994 "minimax" => Box::new(minimax::MiniMaxClaudeRunner::new(agent_name)),
995 "codex" => Box::new(codex::CodexRunner),
996 "opencode" => Box::new(opencode::OpenCodeRunner::new()),
997 "grok" => Box::new(grok::GrokRunner),
998 other => {
1000 if !CLAUDE_COMPATIBLE_AGENTS.contains(&other) {
1002 tracing::warn!(
1003 agent = other,
1004 "unknown agent, using claude-compatible runner"
1005 );
1006 }
1007 Box::new(claude::ClaudeRunner::new(other))
1008 }
1009 }
1010}
1011
1012pub(crate) fn parse_ndjson(raw: &str) -> Vec<serde_json::Value> {
1021 let events: Vec<serde_json::Value> = raw
1023 .lines()
1024 .filter(|line| !line.trim().is_empty())
1025 .filter_map(|line| match serde_json::from_str(line) {
1026 Ok(val) => Some(val),
1027 Err(e) => {
1028 tracing::debug!(line, error = %e, "skipping unparseable NDJSON line");
1029 None
1030 }
1031 })
1032 .collect();
1033
1034 if !events.is_empty() {
1038 return events;
1039 }
1040
1041 let acc: String = raw
1047 .lines()
1048 .filter(|line| {
1049 let t = line.trim();
1050 !t.is_empty() && !t.starts_with("//") && !t.starts_with('#')
1051 })
1052 .collect::<Vec<_>>()
1053 .join(" ");
1054
1055 if acc.is_empty() {
1056 return Vec::new();
1057 }
1058
1059 if let Ok(val) = serde_json::from_str::<serde_json::Value>(acc.trim()) {
1062 let stripped: String = acc.chars().filter(|c| !c.is_ascii_whitespace()).collect();
1067 if let Ok(stripped_val) = serde_json::from_str::<serde_json::Value>(&stripped) {
1068 if stripped_val == val {
1072 return Vec::new();
1073 }
1074 }
1075 return vec![val];
1076 }
1077
1078 extract_json_objects(&acc)
1082}
1083
1084fn extract_json_objects(text: &str) -> Vec<serde_json::Value> {
1089 let mut results = Vec::new();
1090 let mut start: Option<usize> = None;
1091 let mut depth: i32 = 0;
1092 let mut in_string = false;
1093 let mut escape = false;
1094
1095 for (idx, ch) in text.char_indices() {
1096 if let Some(start_idx) = start {
1097 if in_string {
1098 if escape {
1099 escape = false;
1100 } else if ch == '\\' {
1101 escape = true;
1102 } else if ch == '"' {
1103 in_string = false;
1104 }
1105 continue;
1106 }
1107
1108 match ch {
1109 '"' => in_string = true,
1110 '{' => depth += 1,
1111 '}' => {
1112 depth -= 1;
1113 if depth == 0 {
1114 let candidate = &text[start_idx..=idx];
1115 if let Ok(val) = serde_json::from_str::<serde_json::Value>(candidate) {
1116 results.push(val);
1117 }
1118 start = None;
1119 }
1120 }
1121 _ => {}
1122 }
1123 continue;
1124 }
1125
1126 if ch == '{' {
1127 start = Some(idx);
1128 depth = 1;
1129 in_string = false;
1130 escape = false;
1131 }
1132 }
1133
1134 results
1135}
1136
1137#[cfg(test)]
1138mod tests {
1139 use tracing::Level;
1140 use tracing_subscriber::EnvFilter;
1141 use tracing_subscriber::fmt::writer::MakeWriter;
1142 use tracing_subscriber::util::SubscriberInitExt;
1143
1144 use std::io;
1145 use std::io::Write;
1146 use std::sync::Arc;
1147 use std::sync::Mutex;
1148
1149 use super::*;
1150
1151 #[test]
1152 fn get_runner_returns_correct_types() {
1153 assert_eq!(get_runner("claude").name(), "claude");
1154 assert_eq!(get_runner("kimi").name(), "kimi");
1155 assert_eq!(get_runner("minimax").name(), "minimax");
1156 assert_eq!(get_runner("codex").name(), "codex");
1157 assert_eq!(get_runner("opencode").name(), "opencode");
1158 assert_eq!(get_runner("grok").name(), "grok");
1159 assert_eq!(
1160 get_runner("claude").router_transcript(),
1161 RouterTranscript::Messages
1162 );
1163 assert_eq!(
1164 get_runner("kimi").router_transcript(),
1165 RouterTranscript::Messages
1166 );
1167 assert_eq!(
1168 get_runner("minimax").router_transcript(),
1169 RouterTranscript::Messages
1170 );
1171 assert_eq!(
1172 get_runner("grok").router_transcript(),
1173 RouterTranscript::Messages
1174 );
1175 assert_eq!(
1176 get_runner("glm").router_transcript(),
1177 RouterTranscript::Messages
1178 );
1179 assert_eq!(
1180 get_runner("olm").router_transcript(),
1181 RouterTranscript::Messages
1182 );
1183 assert_eq!(
1184 get_runner("opencode").router_transcript(),
1185 RouterTranscript::OpenCode
1186 );
1187 assert_eq!(
1188 get_runner("codex").router_transcript(),
1189 RouterTranscript::Raw
1190 );
1191 assert!(supports_session("grok"));
1192 assert!(!supports_session("codex"));
1193 assert_eq!(get_runner("olm").name(), "olm");
1195 assert_eq!(get_runner("glm").name(), "glm");
1196 assert_eq!(get_runner("unknown-agent").name(), "unknown-agent");
1198 }
1199
1200 #[test]
1203 fn get_runner_no_warning_for_claude_compatible_agents() {
1204 struct CaptureWriter(Arc<Mutex<Vec<u8>>>);
1205 impl Write for CaptureWriter {
1206 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1207 self.0.lock().unwrap().extend_from_slice(buf);
1208 Ok(buf.len())
1209 }
1210 fn flush(&mut self) -> io::Result<()> {
1211 Ok(())
1212 }
1213 }
1214 impl<'a> MakeWriter<'a> for CaptureWriter {
1215 type Writer = CaptureWriter;
1216 fn make_writer(&'a self) -> Self::Writer {
1217 CaptureWriter(Arc::clone(&self.0))
1218 }
1219 }
1220
1221 let output: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
1222 let output_clone = Arc::clone(&output);
1223
1224 tracing_subscriber::fmt()
1225 .with_env_filter(EnvFilter::from_default_env().add_directive(Level::WARN.into()))
1226 .with_writer(CaptureWriter(output_clone))
1227 .with_ansi(false)
1228 .finish()
1229 .init();
1230
1231 for agent in &["claude", "kimi", "minimax", "olm", "glm", "grok"] {
1232 get_runner(agent);
1233 }
1234
1235 let captured = {
1236 let guard = output.lock().unwrap();
1237 String::from_utf8_lossy(&guard).to_string()
1238 };
1239 assert!(
1240 !captured.contains("unknown agent"),
1241 "known claude-compatible agents must not emit 'unknown agent' warnings; got: {captured}"
1242 );
1243 }
1244
1245 #[test]
1246 fn agent_error_display() {
1247 let e = AgentError::RateLimit {
1248 message: "429 Too Many Requests".to_string(),
1249 };
1250 assert!(e.to_string().contains("rate limit"));
1251
1252 let e = AgentError::Timeout {
1253 elapsed: Duration::from_mins(30),
1254 };
1255 assert!(e.to_string().contains("1800"));
1256 }
1257
1258 #[test]
1259 fn pattern_detect_rate_limit() {
1260 assert!(patterns::detect_rate_limit("Error: rate limit exceeded").is_some());
1261 assert!(patterns::detect_rate_limit("HTTP 429 Too Many Requests").is_some());
1262 assert!(patterns::detect_rate_limit("You've hit your usage limit").is_some());
1263 assert!(
1264 patterns::detect_rate_limit(
1265 "You've hit your session limit · resets 10:30am (America/Sao_Paulo)"
1266 )
1267 .is_some()
1268 );
1269 assert!(patterns::detect_rate_limit(
1270 "Upstream error from Alibaba: Request rate increased too quickly. \
1271 To ensure system stability, please adjust your client logic to scale requests more smoothly over time."
1272 ).is_some());
1273 assert!(patterns::detect_rate_limit("all good").is_none());
1274 }
1275
1276 #[test]
1277 fn classify_from_text_detects_weekly_limit_as_rate_limit() {
1278 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)"}}"#;
1282 let work_product = "{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"Working on the task...\"}]}}\n"
1283 .repeat(200);
1284 let text = format!("{system_event}\n{work_product}");
1285 assert!(
1286 text.len() > 3000,
1287 "test output must exceed tail window to be meaningful"
1288 );
1289 let err = patterns::classify_from_text(1, &text);
1290 assert!(
1291 matches!(err, AgentError::RateLimit { .. }),
1292 "weekly limit as early system event must be detected via head scan, got: {err:?}"
1293 );
1294 let msg = err.to_string();
1295 assert!(
1296 msg.contains("weekly limit"),
1297 "error message should reference weekly limit, got: {msg}"
1298 );
1299 }
1300
1301 #[test]
1302 fn detect_rate_limit_github_copilot_monthly_quota() {
1303 let err = patterns::detect_rate_limit("You have exceeded your monthly quota");
1307 assert!(
1308 matches!(err, Some(AgentError::RateLimit { .. })),
1309 "monthly quota exhaustion must be detected as rate limit, got: {err:?}"
1310 );
1311 }
1312
1313 #[test]
1314 fn detect_rate_limit_nvidia_resourceexhausted() {
1315 let opencode_error = r#"opencode agent error: agent failed: "Upstream error from Nvidia: ResourceExhausted: Worker local total request limit reached (42/32)""#;
1319 let err = patterns::detect_rate_limit(opencode_error);
1320 assert!(
1321 matches!(err, Some(AgentError::RateLimit { .. })),
1322 "Nvidia ResourceExhausted must be detected as rate limit, got: {err:?}"
1323 );
1324
1325 assert!(
1327 patterns::detect_rate_limit("ResourceExhausted: some capacity error").is_some(),
1328 "bare ResourceExhausted must match"
1329 );
1330 assert!(
1331 patterns::detect_rate_limit("Worker local total request limit reached (10/8)")
1332 .is_some(),
1333 "worker local total request limit reached must match"
1334 );
1335
1336 let err = patterns::classify_from_text(1, opencode_error);
1338 assert!(
1339 matches!(err, AgentError::RateLimit { .. }),
1340 "classify_from_text must produce RateLimit for Nvidia ResourceExhausted, got: {err:?}"
1341 );
1342 }
1343
1344 #[test]
1345 fn detect_rate_limit_message_contains_context_not_tail() {
1346 let padding = "x".repeat(5000);
1349 let text = format!(
1350 "{padding}you've reached your usage limit for this billing cycle{padding}\
1351 {{\"web_fetch_requests\":0,\"service_tier\":\"standard\"}}"
1352 );
1353 let err = patterns::detect_rate_limit(&text).expect("should detect");
1354 let msg = err.to_string();
1355 assert!(
1356 msg.contains("usage limit"),
1357 "message should contain the actual error, got: {msg}"
1358 );
1359 assert!(
1360 !msg.contains("web_fetch_requests"),
1361 "message should not be the tail JSON, got: {msg}"
1362 );
1363 }
1364
1365 #[test]
1366 fn pattern_detect_rate_limit_529_not_bare() {
1367 assert!(
1370 patterns::detect_rate_limit("error on line 529").is_none(),
1371 "bare line number 529 should not match"
1372 );
1373 assert!(
1374 patterns::detect_rate_limit("file size 529 bytes").is_none(),
1375 "bare file size 529 should not match"
1376 );
1377 assert!(
1378 patterns::detect_rate_limit("port :5290 in config").is_none(),
1379 "port number containing 529 should not match"
1380 );
1381 assert!(
1382 patterns::detect_rate_limit("timeout after 5290ms").is_none(),
1383 "duration containing 529 should not match"
1384 );
1385 assert!(
1387 patterns::detect_rate_limit("HTTP 529 Service Unavailable").is_some(),
1388 "HTTP 529 status should match"
1389 );
1390 assert!(
1391 patterns::detect_rate_limit("http 529").is_some(),
1392 "http 529 should match"
1393 );
1394 assert!(
1395 patterns::detect_rate_limit("529 service unavailable").is_some(),
1396 "529 service unavailable should match"
1397 );
1398 assert!(
1399 patterns::detect_rate_limit("status: 529").is_some(),
1400 "status: 529 should match"
1401 );
1402 }
1403
1404 #[test]
1405 fn pattern_detect_auth() {
1406 assert!(patterns::detect_auth_error("401 Unauthorized").is_some());
1407 assert!(patterns::detect_auth_error("HTTP 401").is_some());
1408 assert!(patterns::detect_auth_error("error: 401").is_some());
1409 assert!(patterns::detect_auth_error("403 Forbidden").is_some());
1410 assert!(patterns::detect_auth_error("HTTP 403").is_some());
1411 assert!(patterns::detect_auth_error("HTTP 407 Authentication Required").is_some());
1412 assert!(patterns::detect_auth_error("407 Proxy Authentication Required").is_some());
1413 assert!(patterns::detect_auth_error("invalid api key").is_some());
1414 assert!(patterns::detect_auth_error("billing expired").is_some());
1415 assert!(patterns::detect_auth_error("task done").is_none());
1416 assert!(patterns::detect_auth_error("duration_api_ms 4010292").is_none());
1418 assert!(
1419 patterns::detect_auth_error(
1420 "API Error: Unable to connect to API (ConnectionRefused) duration_api_ms 4010292"
1421 )
1422 .is_none()
1423 );
1424 assert!(patterns::detect_auth_error(r#""duration_api_ms": 4010292"#).is_none());
1426 assert!(
1427 patterns::detect_auth_error(
1428 r#"{"error":"ConnectionRefused","duration_api_ms": 4010292}"#
1429 )
1430 .is_none()
1431 );
1432 assert!(patterns::detect_auth_error("status: 401").is_some());
1434 assert!(patterns::detect_auth_error("error: 403").is_some());
1435 }
1436
1437 #[test]
1438 fn pattern_detect_auth_insufficient_balance() {
1439 assert!(
1444 patterns::detect_auth_error("402 Payment Required: insufficient balance").is_some(),
1445 "insufficient balance must be detected as auth error"
1446 );
1447 assert!(
1448 patterns::detect_auth_error("insufficient balance").is_some(),
1449 "bare insufficient balance must be detected as auth error"
1450 );
1451 let err = patterns::detect_auth_error("402 Payment Required: insufficient balance")
1453 .expect("should detect auth error");
1454 let AgentError::Auth { message } = err else {
1455 panic!("expected Auth, got {err:?}");
1456 };
1457 assert!(
1458 message.to_lowercase().contains("insufficient balance"),
1459 "stored message should contain the matched pattern, got: {message}"
1460 );
1461 assert!(
1463 message.lines().count() <= 2,
1464 "message should be the auth line, not the full tail: {}",
1465 message.len()
1466 );
1467 }
1468
1469 #[test]
1470 fn auth_error_message_contains_match_not_tail() {
1471 let mut text = "some output\nunauthorized: your api key has expired\nx".repeat(400);
1475 text.push_str(r#","outputTokens":744,"cacheReadInputTokens":344785,"uuid":"86d13b1f-..."#);
1476 let err = patterns::detect_auth_error(&text).expect("should detect auth error");
1477 let AgentError::Auth { message } = err else {
1478 panic!("expected Auth, got {err:?}");
1479 };
1480 assert!(
1481 message.to_lowercase().contains("unauthorized"),
1482 "stored message should contain the matched pattern, got: {message}"
1483 );
1484 assert!(
1485 !message.contains("outputTokens"),
1486 "stored message must not be the trailing NDJSON, got: {message}"
1487 );
1488 assert!(
1490 message.lines().count() <= 2,
1491 "message should be the auth line, not the full tail: {}",
1492 message.len()
1493 );
1494 }
1495
1496 #[test]
1497 fn pattern_detect_network_error() {
1498 assert!(patterns::detect_network_error("connection refused").is_some());
1499 assert!(patterns::detect_network_error("ConnectionRefused").is_some());
1500 assert!(patterns::detect_network_error("Unable to connect to API").is_some());
1501 assert!(patterns::detect_network_error("ECONNREFUSED").is_some());
1502 assert!(patterns::detect_network_error("network unreachable").is_some());
1503 assert!(patterns::detect_network_error("Upstream idle timeout exceeded").is_some());
1504 assert!(patterns::detect_network_error("upstream idle timeout").is_some());
1505 assert!(patterns::detect_network_error("Streaming response failed").is_some());
1506 assert!(patterns::detect_network_error("Upstream request failed").is_some());
1507 assert!(patterns::detect_network_error("all systems operational").is_none());
1508 }
1509
1510 #[test]
1511 fn network_error_message_contains_match_not_tail() {
1512 let prefix = "connection refused connecting to api.anthropic.com:443 ";
1514 let mut suffix = "x".repeat(2000);
1515 suffix.push_str(r#"":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0}"#);
1516 let text = format!("{prefix}{suffix}");
1517
1518 let err = patterns::detect_network_error(&text).expect("should detect network error");
1519 let AgentError::NetworkError { message } = err else {
1520 panic!("expected NetworkError, got {err:?}");
1521 };
1522 assert!(
1523 message.to_lowercase().contains("connection refused"),
1524 "stored message should contain the matched pattern, got: {message}"
1525 );
1526 assert!(
1527 !message.contains("web_fetch_requests"),
1528 "stored message must not be the unrelated stats tail, got: {message}"
1529 );
1530 }
1531
1532 #[test]
1533 fn pattern_detect_context_overflow() {
1534 assert!(patterns::detect_context_overflow("context_length_exceeded").is_some());
1535 assert!(patterns::detect_context_overflow("too many tokens in prompt").is_some());
1536 assert!(patterns::detect_context_overflow("success").is_none());
1537 }
1538
1539 #[test]
1540 fn pattern_detect_worktree_missing() {
1541 assert!(
1542 patterns::detect_worktree_missing("worktree directory does not exist: /tmp/wt")
1543 .is_some()
1544 );
1545 assert!(patterns::detect_worktree_missing("all good").is_none());
1546 }
1547
1548 #[test]
1549 fn pattern_detect_missing_tool() {
1550 assert!(patterns::detect_missing_tool("bun: command not found").is_some());
1551 assert!(patterns::detect_missing_tool("env: anchor: no such file").is_some());
1552 assert!(patterns::detect_missing_tool("everything works").is_none());
1553 }
1554
1555 #[test]
1556 fn pattern_detect_permission_denied() {
1557 assert!(patterns::detect_permission_denied("permission denied: /etc/hosts").is_some());
1558 assert!(patterns::detect_permission_denied("sandbox violation detected").is_some());
1559 assert!(patterns::detect_permission_denied("disallowed tool: Bash(rm *)").is_some());
1560 assert!(patterns::detect_permission_denied("task completed").is_none());
1561 }
1562
1563 #[test]
1564 fn pattern_detect_waiting_for_input() {
1565 assert!(patterns::detect_waiting_for_input("Enter passphrase for key").is_some());
1566 assert!(patterns::detect_waiting_for_input("1Password CLI required").is_some());
1567 assert!(
1568 patterns::detect_waiting_for_input("SSH authentication required for deploy key")
1569 .is_some()
1570 );
1571 assert!(
1572 patterns::detect_waiting_for_input("HTTP 407 Proxy Authentication Required").is_none()
1573 );
1574 assert!(patterns::detect_waiting_for_input("done").is_none());
1575 }
1576
1577 #[test]
1578 fn pattern_detect_stale_session() {
1579 let err = patterns::detect_stale_session(
1581 "No conversation found with session ID: 2be572c4-57bb-4f86-bc03-b593c329177c",
1582 );
1583 assert!(err.is_some(), "should detect stale session");
1584 if let Some(AgentError::StaleSession { session_id }) = err {
1585 assert_eq!(session_id, "2be572c4-57bb-4f86-bc03-b593c329177c");
1586 }
1587
1588 let err = patterns::detect_stale_session("no conversation found with session id: abc-123");
1590 assert!(err.is_some(), "should detect lowercase variant");
1591
1592 assert!(patterns::detect_stale_session("all good").is_none());
1594 assert!(patterns::detect_stale_session("conversation started").is_none());
1595
1596 let multibyte = "Straße: No conversation found with session ID: dead-beef";
1600 let err = patterns::detect_stale_session(multibyte);
1601 assert!(
1602 err.is_some(),
1603 "should detect stale session after multi-byte chars"
1604 );
1605 if let Some(AgentError::StaleSession { session_id }) = err {
1606 assert_eq!(session_id, "dead-beef");
1607 }
1608 }
1609
1610 #[test]
1611 fn stale_session_display() {
1612 let e = AgentError::StaleSession {
1613 session_id: "abc-123".to_string(),
1614 };
1615 assert!(e.to_string().contains("stale session"));
1616 assert!(e.to_string().contains("abc-123"));
1617 }
1618
1619 #[test]
1620 fn classify_from_text_timeout() {
1621 let err = patterns::classify_from_text(124, "");
1622 assert!(matches!(err, AgentError::Timeout { .. }));
1623 }
1624
1625 #[test]
1626 fn classify_from_text_missing_tool_before_rate_limit() {
1627 let err = patterns::classify_from_text(1, "bun: command not found rate limit");
1629 assert!(matches!(err, AgentError::MissingTool { .. }));
1630 }
1631
1632 #[test]
1633 fn classify_from_text_worktree_missing() {
1634 let err = patterns::classify_from_text(1, "worktree directory does not exist: /tmp/wt");
1635 assert!(matches!(err, AgentError::AgentFailed { .. }));
1636 }
1637
1638 #[test]
1639 fn classify_from_text_model_not_found_backtick() {
1640 let text = "codex failed: model unavailable (gpt-5.5): Reconnecting... 2/5 \
1644 (unexpected status 404 Not Found: The model `gpt-5.5` does not exist \
1645 or you do not have access to it.)";
1646 let err = patterns::classify_from_text(1, text);
1647 match err {
1648 AgentError::ModelUnavailable { model, .. } => assert_eq!(model, "gpt-5.5"),
1649 other => panic!("expected ModelUnavailable, got: {other:?}"),
1650 }
1651 }
1652
1653 #[test]
1654 fn classify_from_text_model_metadata_not_found() {
1655 let text = "Model metadata for `gpt-5.4` not found. Defaulting to fallback \
1656 metadata; this can degrade performance and cause issues.";
1657 let err = patterns::classify_from_text(1, text);
1658 match err {
1659 AgentError::ModelUnavailable { model, .. } => assert_eq!(model, "gpt-5.4"),
1660 other => panic!("expected ModelUnavailable, got: {other:?}"),
1661 }
1662 }
1663
1664 #[test]
1665 fn classify_from_text_no_false_positive_from_work_product() {
1666 let work_product = "Added `is_copilot_model(model) -> bool` helper\n\
1669 - Added copilot quota patterns to `parse_retry_at`\n\
1670 fn detect_rate_limit(text: &str) -> Option<AgentError> {\n\
1671 quota exceeded handling for billing cycle\n"
1672 .repeat(50); let actual_error = "\nerror: command not found: cargo\n";
1674 let text = format!("{work_product}{actual_error}");
1675 let err = patterns::classify_from_text(1, &text);
1676 assert!(
1677 !matches!(err, AgentError::RateLimit { .. }),
1678 "work product keywords must not trigger rate limit, got: {err:?}"
1679 );
1680 }
1681
1682 #[test]
1683 fn classify_from_text_still_detects_real_rate_limit_at_tail() {
1684 let padding = "normal agent work output ".repeat(100);
1687 let text = format!("{padding}\nError: rate limit exceeded (429 Too Many Requests)\n");
1688 let err = patterns::classify_from_text(1, &text);
1689 assert!(
1690 matches!(err, AgentError::RateLimit { .. }),
1691 "real rate limit at tail must be detected, got: {err:?}"
1692 );
1693 }
1694
1695 #[test]
1696 fn classify_from_text_ignores_markdown_rate_limit_table_at_tail() {
1697 let padding = "normal agent work output ".repeat(250);
1698 let text = format!(
1699 "{padding}\n+| agent | model | outcome | count |\n+| codex | gpt-5.4 | failed | 1 |\n+| kimi | opus | rate_limit | 1 |\n"
1700 );
1701 let err = patterns::classify_from_text(1, &text);
1702 assert!(
1703 !matches!(err, AgentError::RateLimit { .. }),
1704 "markdown table cell must not trigger rate limit, got: {err:?}"
1705 );
1706 }
1707
1708 #[test]
1709 fn classify_from_text_rate_limit_non_ascii_prefix_does_not_panic() {
1710 let text = "Aflαβrate_limit error: too many requests";
1714 let err = patterns::classify_from_text(1, text);
1715 assert!(
1716 matches!(err, AgentError::RateLimit { .. }),
1717 "real rate_limit should still be detected with non-ASCII prefix, got: {err:?}"
1718 );
1719 }
1720
1721 #[test]
1722 fn classify_from_text_detects_session_limit_as_early_system_event() {
1723 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)"}}"#;
1729 let work_product = "{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"Working on the task...\"}]}}\n"
1732 .repeat(200);
1733 let text = format!("{system_event}\n{work_product}");
1734 assert!(
1736 text.len() > 3000,
1737 "test output must exceed tail window to be meaningful"
1738 );
1739 let err = patterns::classify_from_text(1, &text);
1740 assert!(
1741 matches!(err, AgentError::RateLimit { .. }),
1742 "session limit as early system event must be detected via head scan, got: {err:?}"
1743 );
1744 let msg = err.to_string();
1746 assert!(
1747 msg.contains("session limit"),
1748 "error message should contain the rate limit reason, got: {msg}"
1749 );
1750 }
1751
1752 #[test]
1753 fn classify_from_text_no_false_positive_auth_from_work_product() {
1754 let work_product = "if response.status == 401 { return Err(\"unauthorized\") }\n\
1758 // handle 403 forbidden errors\n\
1759 // billing checks happen elsewhere\n"
1760 .repeat(80);
1761 let actual_error = "\nerror: command not found: cargo\n";
1762 let text = format!("{work_product}{actual_error}");
1763 let err = patterns::classify_from_text(1, &text);
1764 assert!(
1765 !matches!(err, AgentError::Auth { .. }),
1766 "work product auth keywords must not trigger auth classification, got: {err:?}"
1767 );
1768 assert!(
1769 matches!(err, AgentError::MissingTool { .. }),
1770 "the real tail error should still win, got: {err:?}"
1771 );
1772 }
1773
1774 #[test]
1775 fn classify_from_text_still_detects_real_auth_at_tail() {
1776 let padding = "normal agent work output ".repeat(100);
1777 let text = format!("{padding}\nHTTP 401 Unauthorized\n");
1778 let err = patterns::classify_from_text(1, &text);
1779 assert!(
1780 matches!(err, AgentError::Auth { .. }),
1781 "real auth error at tail must be detected, got: {err:?}"
1782 );
1783 }
1784
1785 #[test]
1786 fn classify_from_text_no_false_positive_context_overflow_from_work_product() {
1787 let work_product = "const MAX_TOKEN_LIMIT = 10000;\n\
1791 // Ensure we don't exceed the token limit per request\n\
1792 fn check_token_limit(tokens: usize) { ... }\n\
1793 if total_tokens > MAX_TOKEN_LIMIT { ... }\n\
1794 // Note: too many tokens in the prompt causes context_length_exceeded\n"
1795 .repeat(80);
1796 let actual_error = "\nerror: command not found: cargo\n";
1797 let text = format!("{work_product}{actual_error}");
1798 let err = patterns::classify_from_text(1, &text);
1799 assert!(
1800 !matches!(err, AgentError::ContextOverflow { .. }),
1801 "work product context keywords must not trigger ContextOverflow, got: {err:?}"
1802 );
1803 assert!(
1804 matches!(err, AgentError::MissingTool { .. }),
1805 "the real tail error should still win, got: {err:?}"
1806 );
1807 }
1808
1809 #[test]
1810 fn classify_from_text_still_detects_real_context_overflow_at_tail() {
1811 let padding = "normal agent work output ".repeat(100);
1812 let text = format!("{padding}\nError: context_length_exceeded\n");
1813 let err = patterns::classify_from_text(1, &text);
1814 assert!(
1815 matches!(err, AgentError::ContextOverflow { .. }),
1816 "real context overflow at tail must be detected, got: {err:?}"
1817 );
1818 }
1819
1820 #[test]
1821 fn classify_from_text_no_false_positive_permission_denied_from_work_product() {
1822 let work_product = "match fs::metadata(path) {\n\
1826 Err(ref e) if e.kind() == ErrorKind::PermissionDenied => {\n\
1827 bail!(\"access denied: {path}\");\n\
1828 }\n\
1829 // Check if directory is writable\n\
1830 if !path.is_writable() { ... }\n\
1831 }\n"
1832 .repeat(80);
1833 let actual_error = "\nerror: command not found: cargo\n";
1834 let text = format!("{work_product}{actual_error}");
1835 let err = patterns::classify_from_text(1, &text);
1836 assert!(
1837 !matches!(err, AgentError::PermissionDenied { .. }),
1838 "work product permission keywords must not trigger PermissionDenied, got: {err:?}"
1839 );
1840 assert!(
1841 matches!(err, AgentError::MissingTool { .. }),
1842 "the real tail error should still win, got: {err:?}"
1843 );
1844 }
1845
1846 #[test]
1847 fn classify_from_text_still_detects_real_permission_denied_at_tail() {
1848 let padding = "normal agent work output ".repeat(100);
1849 let text = format!("{padding}\npermission denied: /etc/hosts\n");
1850 let err = patterns::classify_from_text(1, &text);
1851 assert!(
1852 matches!(err, AgentError::PermissionDenied { .. }),
1853 "real permission denied at tail must be detected, got: {err:?}"
1854 );
1855 }
1856
1857 #[test]
1858 fn classify_from_text_no_false_positive_waiting_for_input_from_work_product() {
1859 let work_product = "// Handle password prompts gracefully\n\
1863 if prompt.contains(\"password:\") {\n\
1864 log::warn!(\"Password prompt detected — skipping interactive step\");\n\
1865 }\n\
1866 // SSH agent will ask for the deploy key passphrase\n\
1867 fn handle_ssh_passphrase() { ... }\n\
1868 )\n"
1869 .repeat(80);
1870 let actual_error = "\nerror: command not found: cargo\n";
1871 let text = format!("{work_product}{actual_error}");
1872 let err = patterns::classify_from_text(1, &text);
1873 assert!(
1874 !matches!(err, AgentError::WaitingForInput { .. }),
1875 "work product input keywords must not trigger WaitingForInput, got: {err:?}"
1876 );
1877 assert!(
1878 matches!(err, AgentError::MissingTool { .. }),
1879 "the real tail error should still win, got: {err:?}"
1880 );
1881 }
1882
1883 #[test]
1884 fn classify_from_text_still_detects_real_waiting_for_input_at_tail() {
1885 let padding = "normal agent work output ".repeat(100);
1886 let text = format!("{padding}\nEnter passphrase for key:\n");
1887 let err = patterns::classify_from_text(1, &text);
1888 assert!(
1889 matches!(err, AgentError::WaitingForInput { .. }),
1890 "real waiting for input at tail must be detected, got: {err:?}"
1891 );
1892 }
1893
1894 #[test]
1895 fn classify_from_text_prefers_auth_over_permission_denied() {
1896 let err = patterns::classify_from_text(1, "HTTP 403 access denied: invalid token");
1897 assert!(
1898 matches!(err, AgentError::Auth { .. }),
1899 "auth errors must outrank permission denied, got: {err:?}"
1900 );
1901 }
1902
1903 #[test]
1904 fn classify_from_text_prefers_auth_over_waiting_for_input() {
1905 let err = patterns::classify_from_text(1, "HTTP 407 Proxy Authentication Required");
1906 assert!(
1907 matches!(err, AgentError::Auth { .. }),
1908 "HTTP auth failures must not be treated as waiting for input, got: {err:?}"
1909 );
1910 }
1911
1912 #[test]
1913 fn classify_from_text_detects_stale_session() {
1914 let text = "No conversation found with session ID: 2be572c4-57bb-4f86-bc03-b593c329177c";
1919 let err = patterns::classify_from_text(1, text);
1920 assert!(
1921 matches!(err, AgentError::StaleSession { .. }),
1922 "stale session must be detected via classify_from_text, got: {err:?}"
1923 );
1924 assert!(
1926 err.to_string().contains("stale session"),
1927 "error display must contain 'stale session' for recovery code to trigger"
1928 );
1929 }
1930
1931 #[test]
1932 fn classify_from_text_detects_socket_closed() {
1933 let text = "API Error: The socket connection was closed unexpectedly. \
1936 For more information, pass `verbose: true` in the second argument to fetch()";
1937 let err = patterns::classify_from_text(1, text);
1938 assert!(
1939 matches!(err, AgentError::NetworkError { .. }),
1940 "socket closed must be NetworkError, got: {err:?}"
1941 );
1942 }
1943
1944 #[test]
1945 fn classify_from_text_detects_socket_hang_up() {
1946 let err = patterns::classify_from_text(1, "Error: socket hang up");
1947 assert!(
1948 matches!(err, AgentError::NetworkError { .. }),
1949 "socket hang up must be NetworkError, got: {err:?}"
1950 );
1951 }
1952
1953 #[test]
1954 fn classify_from_text_detects_fetch_failed() {
1955 let err = patterns::classify_from_text(1, "TypeError: fetch failed");
1956 assert!(
1957 matches!(err, AgentError::NetworkError { .. }),
1958 "fetch failed must be NetworkError, got: {err:?}"
1959 );
1960 }
1961
1962 #[test]
1963 fn classify_from_text_detects_econnreset() {
1964 let err = patterns::classify_from_text(1, "read ECONNRESET");
1965 assert!(
1966 matches!(err, AgentError::NetworkError { .. }),
1967 "ECONNRESET must be NetworkError, got: {err:?}"
1968 );
1969 }
1970
1971 #[test]
1972 fn classify_from_text_detects_stalled_mid_stream() {
1973 let err = patterns::classify_from_text(
1976 1,
1977 "API Error: Response stalled mid-stream. The response above may be incomplete.",
1978 );
1979 assert!(
1980 matches!(err, AgentError::NetworkError { .. }),
1981 "stalled mid-stream must be NetworkError, got: {err:?}"
1982 );
1983 }
1984
1985 #[test]
1986 fn classify_from_text_detects_connection_closed_mid_response() {
1987 let err = patterns::classify_from_text(
1990 1,
1991 "API Error: Connection closed mid-response. The response above may be incomplete.",
1992 );
1993 assert!(
1994 matches!(err, AgentError::NetworkError { .. }),
1995 "connection closed mid-response must be NetworkError, got: {err:?}"
1996 );
1997 }
1998
1999 #[test]
2000 fn synthesize_response_marks_done_for_plain_text_no_op() {
2001 let response = synthesize_response_from_text(
2002 "No open positions, no trade executions, no conditions change. Full cash, holding.",
2003 )
2004 .unwrap();
2005
2006 assert_eq!(response.status, "done");
2007 assert_eq!(
2008 response.summary,
2009 "No open positions, no trade executions, no conditions change. Full cash, holding."
2010 );
2011 assert!(response.error.is_none());
2012 }
2013
2014 #[test]
2015 fn synthesize_response_marks_needs_review_for_plain_text_error() {
2016 let response =
2017 synthesize_response_from_text("Failed to update branch: permission denied").unwrap();
2018
2019 assert_eq!(response.status, "needs_review");
2020 assert_eq!(
2021 response.error.as_deref(),
2022 Some("agent returned plain text instead of JSON")
2023 );
2024 }
2025
2026 #[test]
2027 fn synthesize_response_rejects_empty_text() {
2028 assert!(synthesize_response_from_text(" \n\t ").is_none());
2029 }
2030
2031 #[test]
2037 fn synthesize_response_rejects_ndjson_event_stream() {
2038 let ndjson = r#"{"type":"step_start","timestamp":1,"part":{"type":"step-start"}}
2039{"type":"tool_use","timestamp":2,"name":"bash","input":{"cmd":"echo completed"}}
2040{"type":"step_finish","timestamp":3,"part":{"type":"step-finish","reason":"stop"}}"#;
2041 assert!(
2042 synthesize_response_from_text(ndjson).is_none(),
2043 "raw NDJSON must not be interpreted as agent prose"
2044 );
2045
2046 let single = r#"{"type":"step_finish","reason":"stop","completed":true}"#;
2047 assert!(
2048 synthesize_response_from_text(single).is_none(),
2049 "single-line NDJSON event must also be rejected"
2050 );
2051 }
2052
2053 #[test]
2054 fn synthesize_response_accepts_json_without_event_type() {
2055 let text = "The task is complete. Filed issue #1234 successfully.";
2059 let response = synthesize_response_from_text(text).expect("plain prose should synthesize");
2060 assert_eq!(response.status, "done");
2061 }
2062
2063 #[test]
2070 fn synthesize_response_returns_none_for_ambiguous_startup_text() {
2071 assert!(
2073 synthesize_response_from_text("Let's go!").is_none(),
2074 "startup greeting must not synthesize as needs_review"
2075 );
2076 assert!(
2078 synthesize_response_from_text(
2079 "I need to find where the stream command is implemented. \
2080 Looking at the CLI structure, it seems like the stream functionality \
2081 might be in the task module or another file. Let me check the CLI \
2082 command structure. First, let me look at the task module since stream \
2083 is related to tasks."
2084 )
2085 .is_none(),
2086 "exploratory prose must not synthesize as needs_review"
2087 );
2088 }
2089
2090 #[test]
2091 fn synthesize_response_does_not_mark_done_for_incomplete() {
2092 let response = synthesize_response_from_text("The task is incomplete").unwrap();
2093 assert_eq!(
2094 response.status, "needs_review",
2095 "\"incomplete\" should not match \"complete\""
2096 );
2097 }
2098
2099 #[test]
2100 fn synthesize_response_does_not_mark_done_for_not_done() {
2101 let response = synthesize_response_from_text("Changes are not done yet").unwrap();
2102 assert_eq!(
2103 response.status, "needs_review",
2104 "\"not done\" should not match bare \"done\""
2105 );
2106 }
2107
2108 #[test]
2109 fn synthesize_response_does_not_mark_done_for_not_complete() {
2110 let response = synthesize_response_from_text("Still in progress, not complete").unwrap();
2111 assert_eq!(
2112 response.status, "needs_review",
2113 "\"not complete\" should not match \"complete\""
2114 );
2115 }
2116
2117 #[test]
2118 fn synthesize_response_does_not_mark_done_for_not_yet_completed() {
2119 let response = synthesize_response_from_text("The task is not yet completed").unwrap();
2120 assert_eq!(
2121 response.status, "needs_review",
2122 "\"not yet completed\" should not match \"completed\""
2123 );
2124 }
2125
2126 #[test]
2127 fn synthesize_response_marks_done_for_completed() {
2128 let response =
2129 synthesize_response_from_text("Task has been completed successfully").unwrap();
2130 assert_eq!(response.status, "done");
2131 }
2132
2133 #[test]
2134 fn synthesize_response_marks_done_for_word_boundary_done() {
2135 let response = synthesize_response_from_text("All changes are done.").unwrap();
2136 assert_eq!(response.status, "done");
2137 }
2138
2139 #[test]
2140 fn synthesize_response_marks_done_for_issue_creation_text() {
2141 let response =
2142 synthesize_response_from_text("Filed 3 high-value GitHub issues: #1037, #1038, #1039")
2143 .unwrap();
2144
2145 assert_eq!(response.status, "done");
2146 assert!(response.error.is_none());
2147 assert!(
2148 response
2149 .summary
2150 .contains("Filed 3 high-value GitHub issues")
2151 );
2152 }
2153
2154 #[test]
2155 fn synthesize_response_marks_done_for_committed() {
2156 let response =
2157 synthesize_response_from_text("I've committed the changes to the repository").unwrap();
2158 assert_eq!(response.status, "done");
2159 }
2160
2161 #[test]
2162 fn synthesize_response_rejects_exploratory_prose() {
2163 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.";
2169 match synthesize_response_from_text(exploratory) {
2170 None => {
2171 }
2173 Some(resp) => {
2174 assert_ne!(
2175 resp.status, "done",
2176 "Exploratory prose must not be auto-marked done"
2177 );
2178 }
2179 }
2180 }
2181
2182 #[test]
2183 fn synthesize_response_marks_done_for_commit_created() {
2184 let response = synthesize_response_from_text(
2185 "Commit created locally. The push is being blocked by permissions.",
2186 )
2187 .unwrap();
2188 assert_eq!(response.status, "done");
2189 }
2190
2191 #[test]
2192 fn synthesize_response_does_not_mark_done_for_not_committed() {
2193 let response = synthesize_response_from_text("The changes are not committed yet").unwrap();
2194 assert_eq!(
2195 response.status, "needs_review",
2196 "\"not committed\" should not match \"committed\""
2197 );
2198 }
2199
2200 #[test]
2203 fn synthesize_response_marks_done_for_fix_is_complete() {
2204 let response = synthesize_response_from_text(
2208 "All 73 cooldown tests pass. The fix is complete.\n\n\
2209 **Summary of changes:**\n\n\
2210 1. **`src/store/kv.rs`** — Added `kv_increment()` method that uses a single \
2211 `INSERT … ON CONFLICT … DO UPDATE … RETURNING` SQL statement.",
2212 )
2213 .unwrap();
2214 assert_eq!(
2215 response.status, "done",
2216 "\"The fix is complete\" must be classified as done, not needs_review"
2217 );
2218 }
2219
2220 #[test]
2221 fn synthesize_response_marks_done_for_tests_pass_fix_working() {
2222 let response = synthesize_response_from_text(
2226 "All tests pass. The fix is clean and working.\n\n\
2227 **Summary of changes** to `src/engine/runner/response.rs:37`:\n\n\
2228 - **Before:** `capped + jitter` → range `[capped, 1.6*capped]`\n\
2229 - **After:** `capped.saturating_sub(jitter_range) + jitter` → range `[0.7*capped, 1.3*capped]`",
2230 )
2231 .unwrap();
2232 assert_eq!(
2233 response.status, "done",
2234 "\"All tests pass. The fix is clean and working.\" must be classified as done"
2235 );
2236 }
2237
2238 #[test]
2241 fn parse_ndjson_handles_standard_lines() {
2242 let raw = r#"{"type":"text","text":"hello"}
2243{"type":"text","text":"world"}"#;
2244 let events = parse_ndjson(raw);
2245 assert_eq!(events.len(), 2);
2246 assert_eq!(events[0].get("type").unwrap().as_str(), Some("text"));
2247 assert_eq!(events[1].get("type").unwrap().as_str(), Some("text"));
2248 }
2249
2250 #[test]
2251 fn parse_ndjson_skips_empty_lines() {
2252 let raw = r#"{"type":"text"}
2253
2254{"type":"text"}
2255"#;
2256 let events = parse_ndjson(raw);
2257 assert_eq!(events.len(), 2);
2258 }
2259
2260 #[test]
2261 fn parse_ndjson_skips_malformed_lines() {
2262 let raw = r#"{"type":"valid"}
2263not json at all
2264{"type":"also_valid"}"#;
2265 let events = parse_ndjson(raw);
2266 assert_eq!(events.len(), 2);
2267 }
2268
2269 #[test]
2270 fn parse_ndjson_fallback_extracts_embedded_json() {
2271 let raw =
2273 r#"text: {"text": "here is the result: ```json\n{\"status\":\"done\"}\n```"} more"#;
2274 let events = parse_ndjson(raw);
2275 assert!(
2277 !events.is_empty(),
2278 "should extract JSON objects via fallback"
2279 );
2280 }
2281
2282 #[test]
2283 fn parse_ndjson_fallback_handles_fragmented_objects() {
2284 let raw = r#"{"type": "text
2286", "content": "hello
2287world"}"#;
2288 let events = parse_ndjson(raw);
2289 assert!(!events.is_empty(), "should handle fragmented JSON");
2291 }
2292
2293 #[test]
2296 fn permission_rules_default_is_autonomous() {
2297 let rules = PermissionRules::default();
2298 assert!(rules.autonomous);
2299 }
2300
2301 #[test]
2302 fn permission_rules_default_sandbox_is_workspace_write() {
2303 let rules = PermissionRules::default();
2304 assert_eq!(rules.sandbox, SandboxLevel::WorkspaceWrite);
2305 }
2306
2307 #[test]
2308 fn permission_rules_default_disallows_rm() {
2309 let rules = PermissionRules::default();
2310 assert!(rules.disallowed_tools.contains(&"Bash(rm *)".to_string()));
2311 assert!(rules.disallowed_tools.contains(&"Bash(rm -*)".to_string()));
2312 }
2313
2314 #[test]
2315 fn permission_rules_default_no_allowed_edit_paths() {
2316 let rules = PermissionRules::default();
2317 assert!(
2318 rules.allowed_edit_paths.is_empty(),
2319 "{:?}",
2320 rules.allowed_edit_paths
2321 );
2322 }
2323
2324 #[test]
2328 fn all_agents_handle_default_permissions() {
2329 let perms = PermissionRules::default();
2330 let sys = "/tmp/sys.md";
2331 let msg = "/tmp/msg.md";
2332
2333 let claude = get_runner("claude");
2335 let cmd = claude.build_command(None, "", sys, msg, &perms);
2336 assert!(
2337 cmd.contains("--permission-mode bypassPermissions"),
2338 "claude default: expected bypassPermissions, got: {cmd}"
2339 );
2340 assert!(
2341 cmd.contains("Bash(rm *)"),
2342 "claude default: expected rm disallowed, got: {cmd}"
2343 );
2344
2345 let codex = get_runner("codex");
2347 let cmd = codex.build_command(None, "", sys, msg, &perms);
2348 assert!(
2349 cmd.contains("--sandbox workspace-write"),
2350 "codex default: expected --sandbox workspace-write, got: {cmd}"
2351 );
2352 assert!(
2353 cmd.contains(r#"-c 'approval_policy="never"'"#),
2354 "codex default: expected -c approval_policy=never, got: {cmd}"
2355 );
2356 assert!(
2357 !cmd.contains("--ask-for-approval"),
2358 "codex default: --ask-for-approval was removed in 0.133.0 and must not appear, got: {cmd}"
2359 );
2360 assert!(
2361 !cmd.contains("--full-auto"),
2362 "codex default: --full-auto is deprecated and must not appear, got: {cmd}"
2363 );
2364
2365 let opencode = get_runner("opencode");
2368 let cmd = opencode.build_command(None, "", sys, msg, &perms);
2369 assert!(
2370 cmd.contains("--dangerously-skip-permissions"),
2371 "opencode default: should pass --dangerously-skip-permissions, got: {cmd}"
2372 );
2373 assert!(
2374 !cmd.contains("opencode.json"),
2375 "opencode default: should not write a config file, got: {cmd}"
2376 );
2377 assert!(
2378 !cmd.contains("XDG_CONFIG_HOME"),
2379 "opencode default: should not override XDG_CONFIG_HOME, got: {cmd}"
2380 );
2381 assert!(
2382 !cmd.contains(".orch-opencode"),
2383 "opencode default: should not reference .orch-opencode, got: {cmd}"
2384 );
2385 }
2386
2387 #[test]
2389 fn all_agents_handle_supervised_mode() {
2390 let perms = PermissionRules {
2391 autonomous: false,
2392 sandbox: SandboxLevel::WorkspaceWrite,
2393 disallowed_tools: vec![],
2394 allowed_tools: vec![],
2395 allowed_edit_paths: vec![],
2396 deny_read_only: false,
2397 extra_writable_dirs: vec![],
2398 };
2399 let sys = "/tmp/sys.md";
2400 let msg = "/tmp/msg.md";
2401
2402 let claude = get_runner("claude");
2404 let cmd = claude.build_command(None, "", sys, msg, &perms);
2405 assert!(
2406 cmd.contains("--permission-mode acceptEdits"),
2407 "claude supervised: expected acceptEdits, got: {cmd}"
2408 );
2409
2410 let codex = get_runner("codex");
2412 let cmd = codex.build_command(None, "", sys, msg, &perms);
2413 assert!(
2414 cmd.contains(r#"-c 'approval_policy="on-request"'"#),
2415 "codex supervised: expected -c approval_policy=on-request, got: {cmd}"
2416 );
2417 assert!(
2418 !cmd.contains("--ask-for-approval"),
2419 "codex supervised: --ask-for-approval was removed in 0.133.0 and must not appear, got: {cmd}"
2420 );
2421 }
2422
2423 #[test]
2425 fn all_agents_handle_full_access_sandbox() {
2426 let perms = PermissionRules {
2427 autonomous: true,
2428 sandbox: SandboxLevel::FullAccess,
2429 disallowed_tools: vec![],
2430 allowed_tools: vec![],
2431 allowed_edit_paths: vec![],
2432 deny_read_only: false,
2433 extra_writable_dirs: vec![],
2434 };
2435 let sys = "/tmp/sys.md";
2436 let msg = "/tmp/msg.md";
2437
2438 let claude = get_runner("claude");
2440 let cmd = claude.build_command(None, "", sys, msg, &perms);
2441 assert!(
2442 !cmd.contains("--sandbox"),
2443 "claude full_access: should have no sandbox flag, got: {cmd}"
2444 );
2445
2446 let codex = get_runner("codex");
2448 let cmd = codex.build_command(None, "", sys, msg, &perms);
2449 assert!(
2450 cmd.contains("--dangerously-bypass-approvals-and-sandbox"),
2451 "codex full_access: expected dangerously-bypass, got: {cmd}"
2452 );
2453 }
2454
2455 #[test]
2457 fn codex_sandbox_none_uses_workspace_write() {
2458 let perms = PermissionRules {
2459 autonomous: true,
2460 sandbox: SandboxLevel::None,
2461 disallowed_tools: vec![],
2462 allowed_tools: vec![],
2463 allowed_edit_paths: vec![],
2464 deny_read_only: false,
2465 extra_writable_dirs: vec![],
2466 };
2467 let codex = get_runner("codex");
2468 let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2469 assert!(
2470 cmd.contains("--sandbox workspace-write"),
2471 "codex sandbox::none + autonomous: should use --sandbox workspace-write, got: {cmd}"
2472 );
2473 assert!(
2474 cmd.contains(r#"-c 'approval_policy="never"'"#),
2475 "codex sandbox::none + autonomous: should use -c approval_policy=never, got: {cmd}"
2476 );
2477 assert!(
2478 !cmd.contains("--ask-for-approval"),
2479 "codex sandbox::none: --ask-for-approval was removed in 0.133.0, got: {cmd}"
2480 );
2481 assert!(
2482 !cmd.contains("--full-auto"),
2483 "codex sandbox::none: --full-auto is deprecated and must not appear, got: {cmd}"
2484 );
2485 }
2486
2487 #[test]
2489 fn claude_allowed_edit_paths_scope_edit_write() {
2490 let perms = PermissionRules {
2491 autonomous: true,
2492 sandbox: SandboxLevel::WorkspaceWrite,
2493 disallowed_tools: vec![],
2494 allowed_tools: vec![
2495 "Edit".to_string(),
2496 "Write".to_string(),
2497 "Read".to_string(),
2498 "Bash".to_string(),
2499 ],
2500 allowed_edit_paths: vec![PathBuf::from("/home/user/worktree")],
2501 deny_read_only: false,
2502 extra_writable_dirs: vec![],
2503 };
2504 let claude = get_runner("claude");
2505 let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2506
2507 assert!(
2509 cmd.contains("Edit(/home/user/worktree/*)"),
2510 "missing scoped Edit, got: {cmd}"
2511 );
2512 assert!(
2513 cmd.contains("Write(/home/user/worktree/*)"),
2514 "missing scoped Write, got: {cmd}"
2515 );
2516 assert!(cmd.contains("Read"), "missing Read");
2518 }
2519
2520 #[test]
2522 fn codex_ignores_allowed_edit_paths() {
2523 let perms = PermissionRules {
2524 autonomous: true,
2525 sandbox: SandboxLevel::WorkspaceWrite,
2526 disallowed_tools: vec![],
2527 allowed_tools: vec![],
2528 allowed_edit_paths: vec![PathBuf::from("/home/user/project")],
2529 deny_read_only: false,
2530 extra_writable_dirs: vec![],
2531 };
2532 let codex = get_runner("codex");
2533 let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2534 assert!(
2535 !cmd.contains("/home/user/project"),
2536 "codex: should not reference blocked paths, got: {cmd}"
2537 );
2538 }
2539
2540 #[test]
2542 fn opencode_ignores_allowed_edit_paths() {
2543 let perms = PermissionRules {
2544 autonomous: true,
2545 sandbox: SandboxLevel::WorkspaceWrite,
2546 disallowed_tools: vec![],
2547 allowed_tools: vec![],
2548 allowed_edit_paths: vec![PathBuf::from("/home/user/project")],
2549 deny_read_only: false,
2550 extra_writable_dirs: vec![],
2551 };
2552 let opencode = get_runner("opencode");
2553 let cmd = opencode.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2554 assert!(
2555 !cmd.contains("/home/user/project"),
2556 "opencode: should not reference blocked paths, got: {cmd}"
2557 );
2558 }
2559
2560 #[test]
2562 fn claude_merges_disallowed_tools() {
2563 let perms = PermissionRules {
2564 autonomous: true,
2565 sandbox: SandboxLevel::WorkspaceWrite,
2566 disallowed_tools: vec![
2567 "Bash(rm *)".to_string(),
2568 "Bash(sudo *)".to_string(),
2569 "WebFetch".to_string(),
2570 ],
2571 allowed_tools: vec![],
2572 allowed_edit_paths: vec![],
2573 deny_read_only: false,
2574 extra_writable_dirs: vec![],
2575 };
2576 let claude = get_runner("claude");
2577 let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2578 assert!(cmd.contains("Bash(rm *)"), "missing rm disallow");
2579 assert!(cmd.contains("Bash(sudo *)"), "missing sudo disallow");
2580 assert!(cmd.contains("WebFetch"), "missing WebFetch disallow");
2581 }
2582
2583 #[test]
2585 fn codex_ignores_disallowed_tools() {
2586 let perms = PermissionRules {
2587 autonomous: true,
2588 sandbox: SandboxLevel::WorkspaceWrite,
2589 disallowed_tools: vec!["Bash(rm *)".to_string(), "WebFetch".to_string()],
2590 allowed_tools: vec![],
2591 allowed_edit_paths: vec![],
2592 deny_read_only: false,
2593 extra_writable_dirs: vec![],
2594 };
2595 let codex = get_runner("codex");
2596 let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2597 assert!(
2598 !cmd.contains("disallow"),
2599 "codex: should not have disallow flags, got: {cmd}"
2600 );
2601 }
2602
2603 #[test]
2605 fn claude_no_disallowed_flag_when_empty() {
2606 let perms = PermissionRules {
2607 autonomous: true,
2608 sandbox: SandboxLevel::WorkspaceWrite,
2609 disallowed_tools: vec![],
2610 allowed_tools: vec![],
2611 allowed_edit_paths: vec![],
2612 deny_read_only: false,
2613 extra_writable_dirs: vec![],
2614 };
2615 let claude = get_runner("claude");
2616 let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2617 assert!(
2618 !cmd.contains("--disallowedTools"),
2619 "claude: should have no disallowed flag when empty, got: {cmd}"
2620 );
2621 }
2622
2623 #[test]
2625 fn kimi_minimax_use_claude_permissions() {
2626 let perms = PermissionRules {
2627 autonomous: false,
2628 sandbox: SandboxLevel::WorkspaceWrite,
2629 disallowed_tools: vec!["Bash(rm *)".to_string()],
2630 allowed_tools: vec![],
2631 allowed_edit_paths: vec![],
2632 deny_read_only: false,
2633 extra_writable_dirs: vec![],
2634 };
2635 let sys = "/tmp/sys.md";
2636 let msg = "/tmp/msg.md";
2637
2638 for agent in &["kimi", "minimax"] {
2639 let runner = get_runner(agent);
2640 let cmd = runner.build_command(None, "", sys, msg, &perms);
2641 assert!(
2642 cmd.contains("--permission-mode acceptEdits"),
2643 "{agent}: expected acceptEdits"
2644 );
2645 assert!(
2646 cmd.contains("Bash(rm *)"),
2647 "{agent}: expected rm disallowed"
2648 );
2649 }
2650 }
2651
2652 #[test]
2654 fn kimi_minimax_use_allowed_tools() {
2655 let perms = PermissionRules {
2656 autonomous: true,
2657 sandbox: SandboxLevel::WorkspaceWrite,
2658 disallowed_tools: vec![],
2659 allowed_tools: vec!["Edit".to_string(), "Bash".to_string(), "git".to_string()],
2660 allowed_edit_paths: vec![],
2661 deny_read_only: false,
2662 extra_writable_dirs: vec![],
2663 };
2664
2665 for agent in &["kimi", "minimax"] {
2666 let runner = get_runner(agent);
2667 let cmd = runner.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2668 assert!(
2669 cmd.contains("--allowedTools"),
2670 "{agent}: expected --allowedTools, got: {cmd}"
2671 );
2672 assert!(
2673 cmd.contains("Bash(git *)"),
2674 "{agent}: expected Bash(git *) pattern, got: {cmd}"
2675 );
2676 }
2677 }
2678
2679 #[test]
2683 fn claude_allowed_tools_generates_allowedtools_flag() {
2684 let perms = PermissionRules {
2685 autonomous: true,
2686 sandbox: SandboxLevel::WorkspaceWrite,
2687 disallowed_tools: vec!["Bash(rm *)".to_string()],
2688 allowed_tools: vec![
2689 "Edit".to_string(),
2690 "Write".to_string(),
2691 "Read".to_string(),
2692 "Bash".to_string(),
2693 "git".to_string(),
2694 ],
2695 allowed_edit_paths: vec![],
2696 deny_read_only: false,
2697 extra_writable_dirs: vec![],
2698 };
2699
2700 let claude = get_runner("claude");
2701 let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2702 assert!(
2703 cmd.contains("--allowedTools"),
2704 "expected --allowedTools, got: {cmd}"
2705 );
2706 assert!(
2707 !cmd.contains("--disallowedTools"),
2708 "should not have --disallowedTools when allowed_tools is set"
2709 );
2710 }
2711
2712 #[test]
2714 fn codex_opencode_ignore_allowed_tools() {
2715 let perms = PermissionRules {
2716 autonomous: true,
2717 sandbox: SandboxLevel::WorkspaceWrite,
2718 disallowed_tools: vec![],
2719 allowed_tools: vec!["Edit".to_string(), "git".to_string()],
2720 allowed_edit_paths: vec![],
2721 deny_read_only: false,
2722 extra_writable_dirs: vec![],
2723 };
2724
2725 let codex = get_runner("codex");
2726 let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2727 assert!(
2728 !cmd.contains("--allowedTools"),
2729 "codex should not have --allowedTools, got: {cmd}"
2730 );
2731
2732 let opencode = get_runner("opencode");
2733 let cmd = opencode.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2734 assert!(
2735 !cmd.contains("--allowedTools"),
2736 "opencode should not have --allowedTools, got: {cmd}"
2737 );
2738 }
2739
2740 #[test]
2745 #[ignore = "reads the operator config"]
2746 fn integration_from_config_to_agent_commands() {
2747 let perms = PermissionRules::from_config();
2748
2749 assert!(
2751 perms.autonomous,
2752 "from_config: expected autonomous=true by default"
2753 );
2754
2755 for agent_name in &["claude", "codex", "opencode", "kimi", "minimax"] {
2757 let runner = get_runner(agent_name);
2758 let cmd =
2759 runner.build_command(None, "timeout 1800", "/tmp/sys.md", "/tmp/msg.md", &perms);
2760 assert!(
2761 !cmd.is_empty(),
2762 "{agent_name}: build_command returned empty string"
2763 );
2764 assert!(
2765 cmd.contains(agent_name) || *agent_name == "kimi" || *agent_name == "minimax",
2766 "{agent_name}: command should reference agent binary, got: {cmd}"
2767 );
2768 }
2769 }
2770
2771 #[test]
2774 #[ignore = "reads the operator config"]
2775 fn integration_supervised_config_translates_correctly() {
2776 let perms = PermissionRules::from_config();
2781
2782 let claude = get_runner("claude");
2783 let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2784
2785 if perms.autonomous {
2786 assert!(
2787 cmd.contains("bypassPermissions"),
2788 "autonomous config → bypassPermissions"
2789 );
2790 } else {
2791 assert!(
2792 cmd.contains("acceptEdits"),
2793 "supervised config → acceptEdits"
2794 );
2795 }
2796
2797 let codex = get_runner("codex");
2798 let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2799
2800 if perms.autonomous {
2801 assert!(
2803 cmd.contains("--sandbox workspace-write"),
2804 "autonomous config → --sandbox workspace-write, got: {cmd}"
2805 );
2806 assert!(
2807 cmd.contains(r#"-c 'approval_policy="never"'"#),
2808 "autonomous config → -c approval_policy=never, got: {cmd}"
2809 );
2810 } else {
2811 assert!(
2812 cmd.contains(r#"-c 'approval_policy="on-request"'"#),
2813 "supervised config → -c approval_policy=on-request, got: {cmd}"
2814 );
2815 }
2816 assert!(
2817 !cmd.contains("--ask-for-approval"),
2818 "--ask-for-approval was removed in codex 0.133.0 and must not appear, got: {cmd}"
2819 );
2820 }
2821
2822 #[test]
2826 fn deny_read_only_blocks_reading_tools() {
2827 let perms = PermissionRules::deny_read_only();
2828
2829 let read_tools = [
2830 "Bash(ls *)",
2831 "Bash(ls)",
2832 "Bash(find *)",
2833 "Bash(cat *)",
2834 "Bash(head *)",
2835 "Bash(tail *)",
2836 "Bash(fzf *)",
2837 "Bash(less *)",
2838 "Bash(more *)",
2839 "Read",
2840 "Glob",
2841 "Grep",
2842 ];
2843
2844 for tool in read_tools {
2845 assert!(
2846 perms.disallowed_tools.contains(&tool.to_string()),
2847 "deny_read_only should block {tool}, got: {:?}",
2848 perms.disallowed_tools
2849 );
2850 }
2851 }
2852
2853 #[test]
2855 fn deny_read_only_claude_command() {
2856 let perms = PermissionRules::deny_read_only();
2857 let claude = get_runner("claude");
2858 let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2859
2860 assert!(
2862 cmd.contains("Read"),
2863 "should block Read for control session"
2864 );
2865 assert!(
2866 cmd.contains("Glob"),
2867 "should block Glob for control session"
2868 );
2869 assert!(
2870 cmd.contains("Grep"),
2871 "should block Grep for control session"
2872 );
2873 assert!(
2875 cmd.contains("Bash(ls") || cmd.contains("Bash(ls *)"),
2876 "should block ls"
2877 );
2878 assert!(
2880 cmd.contains("--permission-mode bypassPermissions"),
2881 "should be autonomous (bypassPermissions)"
2882 );
2883 }
2884
2885 #[test]
2888 fn synthesize_extracts_file_paths() {
2889 let text = "Fixed the issue by modifying src/engine/runner/agents/mod.rs and tests/integration.rs.";
2890 let resp = synthesize_response_from_text(text).unwrap();
2891 assert!(
2892 resp.files
2893 .contains(&"src/engine/runner/agents/mod.rs".to_string()),
2894 "expected src/engine/runner/agents/mod.rs in files, got: {:?}",
2895 resp.files
2896 );
2897 assert!(
2898 resp.files.contains(&"tests/integration.rs".to_string()),
2899 "expected tests/integration.rs in files, got: {:?}",
2900 resp.files
2901 );
2902 }
2903
2904 #[test]
2905 fn synthesize_extracts_accomplished_bullets() {
2906 let text = "All tests pass.\n- Added logging to src/foo.rs\n- Updated migration file";
2907 let resp = synthesize_response_from_text(text).unwrap();
2908 assert_eq!(resp.status, "done");
2909 assert!(
2910 resp.accomplished
2911 .iter()
2912 .any(|a| a.contains("Added logging")),
2913 "expected accomplished bullet, got: {:?}",
2914 resp.accomplished
2915 );
2916 assert!(
2917 resp.accomplished
2918 .iter()
2919 .any(|a| a.contains("Updated migration")),
2920 "expected accomplished bullet, got: {:?}",
2921 resp.accomplished
2922 );
2923 }
2924
2925 #[test]
2926 fn synthesize_extracts_remaining_section() {
2927 let text = "Completed the main fix.\n- Patched src/lib.rs\n\nRemaining:\n- Write unit tests\n- Update docs";
2928 let resp = synthesize_response_from_text(text).unwrap();
2929 assert!(
2930 resp.remaining
2931 .iter()
2932 .any(|r| r.contains("Write unit tests")),
2933 "expected remaining item, got: {:?}",
2934 resp.remaining
2935 );
2936 assert!(
2937 resp.remaining.iter().any(|r| r.contains("Update docs")),
2938 "expected remaining item, got: {:?}",
2939 resp.remaining
2940 );
2941 assert!(
2942 resp.accomplished.iter().any(|a| a.contains("Patched")),
2943 "expected accomplished item, got: {:?}",
2944 resp.accomplished
2945 );
2946 }
2947
2948 #[test]
2949 fn synthesize_fixed_phrase_is_done() {
2950 let text = "Fixed. The bug no longer reproduces.";
2951 let resp = synthesize_response_from_text(text).unwrap();
2952 assert_eq!(resp.status, "done", "expected done for 'Fixed.' text");
2953 }
2954
2955 #[test]
2962 fn detect_rate_limit_fires_on_bare_429_in_token_count() {
2963 let payload = r#"{"type":"result","terminal_reason":"completed","outputTokens":429,"is_error":false}"#;
2967 assert!(
2968 patterns::detect_rate_limit(payload).is_some(),
2969 "detect_rate_limit must still fire on bare 429 so callers apply the guard"
2970 );
2971 }
2972
2973 #[test]
2974 fn detect_rate_limit_ignores_429_inside_longer_number() {
2975 let uuid = r#"{"type":"hook","uuid":"a1b2c3d4-4295-4e5f-8a9b-0c1d2e3f4a5b"}"#;
2976 assert!(
2977 patterns::detect_rate_limit(uuid).is_none(),
2978 "429 inside a UUID digit run must not match"
2979 );
2980 }
2981
2982 #[test]
2983 fn detect_rate_limit_ignores_429_in_uuid_hex_group() {
2984 let hook = r#"{"type":"system","subtype":"hook_response","hook_id":"18db61b6-7b72-429c-8279-fae3089bf565"}"#;
2985 assert!(patterns::detect_rate_limit(hook).is_none());
2986 }
2987
2988 #[test]
2989 fn detect_rate_limit_429_message_comes_from_matched_line() {
2990 let filler = "unrelated agent prose that is long enough to fill the window. ".repeat(20);
2991 let text = format!("HTTP 429 Too Many Requests\n{filler}");
2992 match patterns::detect_rate_limit(&text) {
2993 Some(AgentError::RateLimit { message }) => assert!(message.contains("429")),
2994 other => panic!("expected RateLimit, got {other:?}"),
2995 }
2996 }
2997
2998 #[test]
3002 fn terminal_reason_completed_guard_suppresses_false_rate_limit() {
3003 let raw_output = r#"{"type":"result","terminal_reason":"completed","outputTokens":429,"is_error":false}"#;
3004 let ndjson_completed = raw_output.contains("\"terminal_reason\":\"completed\"")
3005 && !raw_output.contains("\"is_error\":true");
3006 let detected = (!ndjson_completed)
3008 .then(|| patterns::detect_rate_limit(raw_output))
3009 .flatten();
3010 assert!(
3011 detected.is_none(),
3012 "guard must suppress rate-limit false positive from token-count 429 when terminal_reason:completed"
3013 );
3014 }
3015
3016 #[test]
3018 fn terminal_reason_completed_guard_passes_real_rate_limit() {
3019 let raw_output = "Error: 429 Too Many Requests — you have exceeded your quota";
3021 let ndjson_completed = raw_output.contains("\"terminal_reason\":\"completed\"")
3022 && !raw_output.contains("\"is_error\":true");
3023 let detected = (!ndjson_completed)
3024 .then(|| patterns::detect_rate_limit(raw_output))
3025 .flatten();
3026 assert!(
3027 detected.is_some(),
3028 "guard must NOT suppress a real rate-limit error"
3029 );
3030 }
3031
3032 #[test]
3033 fn synthesize_no_false_positive_file_paths() {
3034 let text = "See https://example.com/foo.rs for details. Version 1.2.3 is fine.";
3038 match synthesize_response_from_text(text) {
3039 None => {} Some(resp) => {
3041 assert!(
3042 resp.files.is_empty(),
3043 "expected no file paths extracted from URL text, got: {:?}",
3044 resp.files
3045 );
3046 }
3047 }
3048 }
3049
3050 #[test]
3055 fn synthesize_rejects_cli_parser_diagnostics_unexpected_argument() {
3056 let text = "error: unexpected argument '--ask-for-approval' found\n \
3058 tip: to pass '--ask-for-approval' as a value, use '-- --ask-for-approval'\n\
3059 Usage: codex exec [OPTIONS] [PROMPT]";
3060 assert!(
3061 synthesize_response_from_text(text).is_none(),
3062 "CLI parser diagnostic must not synthesize as agent response"
3063 );
3064 }
3065
3066 #[test]
3067 fn synthesize_rejects_cli_parser_diagnostics_usage_line() {
3068 let text = "Usage: mycommand [OPTIONS] <arg>";
3069 assert!(
3070 synthesize_response_from_text(text).is_none(),
3071 "Usage line must not synthesize as agent response"
3072 );
3073 }
3074
3075 #[test]
3076 fn synthesize_rejects_cli_parser_diagnostics_help_hint() {
3077 let text = "Error: unknown flag --foo\nFor more information, try '--help'";
3078 assert!(
3079 synthesize_response_from_text(text).is_none(),
3080 "Help hint must not synthesize as agent response"
3081 );
3082 }
3083
3084 #[test]
3085 fn synthesize_rejects_cli_parser_diagnostics_tip() {
3086 let text = "error: bad value\ntip: to pass '--flag' as a value, use '-- --flag'";
3087 assert!(
3088 synthesize_response_from_text(text).is_none(),
3089 "Clap tip must not synthesize as agent response"
3090 );
3091 }
3092
3093 #[test]
3094 fn synthesize_accepts_agent_error_messages_that_mention_error() {
3095 let text = "I tried to run the command but got an error: permission denied on that file.";
3098 let response =
3099 synthesize_response_from_text(text).expect("agent error message should synthesize");
3100 assert_eq!(response.status, "needs_review");
3101 assert!(response.error.is_some());
3102 }
3103
3104 #[test]
3109 fn synthesize_rejects_exact_codex_cli_error() {
3110 let stderr_from_codex = "error: unexpected argument '--ask-for-approval' found\n \
3111 tip: to pass '--ask-for-approval' as a value, use '-- --ask-for-approval'\n\
3112 Usage: codex exec [OPTIONS] [PROMPT]";
3113 assert!(
3114 synthesize_response_from_text(stderr_from_codex).is_none(),
3115 "exact codex CLI error from #3197 must not synthesize as agent response"
3116 );
3117 }
3118}