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