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