Skip to main content

orch/engine/runner/agents/
mod.rs

1//! Per-agent runner trait, error types, and agent registry.
2//!
3//! Each agent (Claude, Codex, OpenCode, Grok) has a different CLI invocation,
4//! output format, and error pattern. This module defines a common trait
5//! so the runner can delegate parsing and error classification to the
6//! correct implementation.
7
8#[macro_use]
9mod delegate;
10#[cfg(test)]
11pub(crate) mod fixture;
12/// Shared error pattern detection utilities used by multiple agent runners.
13pub(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/// Unified permission rules that each agent translates into its native flags.
34///
35/// Instead of hardcoding `--permission-mode bypassPermissions` for Claude and
36/// `--sandbox workspace-write` for Codex, we define a single set of rules and
37/// let each `AgentRunner` format them for its CLI.
38#[derive(Debug, Clone)]
39pub struct PermissionRules {
40    /// Whether the agent runs fully autonomous (no user prompts).
41    pub autonomous: bool,
42    /// Sandbox level for filesystem access.
43    pub sandbox: SandboxLevel,
44    /// Tool patterns to disallow (e.g., `["Bash(rm *)", "Bash(rm -*)"]`).
45    pub disallowed_tools: Vec<String>,
46    /// Tools to allow (whitelist). Overrides `disallowed_tools` when non-empty.
47    ///
48    /// Items are either agent-native tool names (e.g., "Edit", "Write", "Bash")
49    /// or CLI command names (e.g., "git", "npm") which get translated to
50    /// agent-specific patterns (e.g., `Bash(git*)` for Claude).
51    pub allowed_tools: Vec<String>,
52    /// Paths where the agent is allowed to edit files (worktree path).
53    /// When set, Edit/Write tools are scoped to these paths only.
54    /// Set dynamically per invocation (not from config).
55    pub allowed_edit_paths: Vec<PathBuf>,
56    /// Restrict to orchestration-only operations — denies Read, Glob, Grep,
57    /// and Bash commands for browsing/reading files (ls, cat, find, etc.).
58    /// Agents translate this into their native permission model.
59    pub deny_read_only: bool,
60    /// Additional directories that must be writable (e.g. the git common dir
61    /// when running inside a worktree whose `.git` metadata lives outside the
62    /// sandbox root). Codex translates these into `--add-dir` flags; other
63    /// agents ignore the field.
64    pub extra_writable_dirs: Vec<PathBuf>,
65}
66
67/// Sandbox level — how much filesystem access the agent gets.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub enum SandboxLevel {
70    /// Agent can only write within the workspace/worktree.
71    WorkspaceWrite,
72    /// Agent has full filesystem access (dangerous).
73    FullAccess,
74    /// No sandboxing (orch manages isolation externally).
75    None,
76    /// The OS sandbox from `workflow.sandbox: os` runs the agent, so the agent's own sandbox is off
77    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    /// Load permission rules from config, falling back to defaults.
100    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    /// Restriction preset for control sessions: denies Read, Glob, Grep, and
134    /// Bash commands that read files or list directories (ls, cat, find, etc.).
135    ///
136    /// The agent remains autonomous but is prevented from browsing or reading
137    /// arbitrary files on the host machine. Translation into agent-native flags
138    /// is handled by each `AgentRunner::build_command()` implementation.
139    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/// Structured result from per-agent NDJSON extraction.
169///
170/// Each agent emits a different NDJSON format. The per-agent `find_result`
171/// functions parse agent-specific envelopes and return a unified `AgentResult`
172/// so callers (review pipeline, response handler) don't need format knowledge.
173#[derive(Debug, Clone)]
174pub struct AgentResult {
175    /// Whether the agent reported an error (e.g. `is_error: true` in Claude).
176    pub is_error: bool,
177    /// The extracted result text (inner content, stripped of envelope).
178    pub result_text: String,
179    /// Input tokens consumed (if reported by the agent).
180    pub input_tokens: Option<u64>,
181    /// Output tokens consumed (if reported by the agent).
182    pub output_tokens: Option<u64>,
183    /// Total cost in USD (if reported by the agent).
184    pub cost_usd: Option<f64>,
185    /// Wall-clock duration in milliseconds (if reported by the agent).
186    pub duration_ms: Option<u64>,
187    /// True when the provider cut the response short by exceeding its
188    /// output/reasoning token budget (e.g. opencode's `step_finish` event
189    /// reporting `reason: "length"`), as opposed to producing malformed
190    /// output. Callers use this to distinguish a token-budget fluke from a
191    /// genuinely format-incapable model.
192    pub truncated_by_length: bool,
193}
194
195/// Concatenate text from all assistant-turn messages in the agent's NDJSON
196/// output stream.  Used as an intermediate fallback when the `type:result`
197/// envelope text is not valid AgentResponse JSON but an earlier assistant
198/// message in the conversation might contain it.
199pub fn collect_assistant_messages_text(_agent: &str, ndjson: &str) -> String {
200    claude::collect_assistant_messages_text(ndjson)
201}
202
203/// Dispatch to the appropriate per-agent result extractor.
204///
205/// Returns `None` if no structured result could be found in the output
206/// (e.g. plain text, empty output, or unrecognized format).
207pub 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, kimi, minimax and unknown agents all emit the claude format
213        _ => claude::find_claude_result(ndjson),
214    }
215}
216
217/// Parsed response from an agent, including metadata extracted from the
218/// agent-specific output envelope.
219#[derive(Debug, Clone)]
220pub struct ParsedResponse {
221    /// Normalized task response (status, summary, accomplished, etc.)
222    pub response: AgentResponse,
223    /// Input tokens consumed (if reported by the agent).
224    pub input_tokens: Option<u64>,
225    /// Output tokens consumed (if reported by the agent).
226    pub output_tokens: Option<u64>,
227    /// Cost in USD of this run, as the agent reported it.
228    pub cost_usd: Option<f64>,
229    /// Wall-clock duration in milliseconds (if reported by the agent).
230    pub duration_ms: Option<u64>,
231}
232
233/// Agent-specific error with enough detail for autonomous recovery.
234#[derive(Debug, Clone)]
235pub enum AgentError {
236    /// Rate/usage limit — reroute to different agent, cooldown current.
237    RateLimit { message: String },
238    /// Auth/billing/API key error — switch agent entirely.
239    Auth { message: String },
240    /// Requested model not available — try different model, then switch agent.
241    ModelUnavailable { message: String, model: String },
242    /// Context window exceeded — truncate and retry, then switch agent.
243    ContextOverflow { message: String },
244    /// Agent hit the task time limit. Retry without cooling the model
245    Timeout { elapsed: Duration },
246    /// Process exited with no result envelope, usually a kill rather than a model fault
247    Interrupted { message: String },
248    /// Required tool/binary missing from the environment.
249    MissingTool { tool: String },
250    /// Sandbox or filesystem permission denied.
251    PermissionDenied { message: String },
252    /// Agent is waiting for interactive input (e.g., 1Password, SSH).
253    WaitingForInput { message: String },
254    /// The agent's session ID is no longer valid (session expired or was cleared).
255    ///
256    /// Returned when Claude reports "No conversation found with session ID: <uuid>".
257    /// The caller should reset the stored UUID and retry with a fresh `--session-id`.
258    StaleSession { session_id: String },
259    /// Agent returned unparseable output.
260    InvalidResponse { raw: String },
261    /// Agent self-reported a failure in its response.
262    AgentFailed { message: String },
263    /// Transient network connectivity error — retry same agent, no failover.
264    NetworkError { message: String },
265    /// Thinking blocks cannot be modified (Claude extended-thinking + tool-use 400).
266    ///
267    /// Transient API incompatibility inside the Claude CLI's multi-turn tool-use
268    /// loop — the Anthropic API rejects the request when thinking blocks are altered
269    /// between turns. Not a model capacity problem: does NOT increment failure counts
270    /// or apply cooldowns. The task is rerouted to a different agent.
271    ThinkingBlockConflict { message: String },
272    /// Unclassified error.
273    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
311/// Return the variant name of an `AgentError` as a static string,
312/// for structured logging and `result.json` output.
313pub 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
333/// Extract file paths from free-form text.
334///
335/// Matches common source file patterns like `src/foo/bar.rs`, `tests/x.py`,
336/// `path/to/file.ts`, etc. Deduplicates and returns them sorted.
337fn extract_file_paths(text: &str) -> Vec<String> {
338    // Match path-like tokens: optional leading slash or no slash, at least one
339    // directory segment or a plain filename, with a recognised extension.
340    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        // Strip surrounding punctuation (backticks, quotes, parens, commas).
347        // We intentionally do NOT strip '.' here because it is part of file extensions.
348        let token = token.trim_matches(|c: char| {
349            matches!(
350                c,
351                '`' | '\'' | '"' | '(' | ')' | '[' | ']' | ',' | ':' | ';'
352            )
353        });
354        // Strip a lone trailing dot that ends a sentence (e.g. "src/foo.rs.").
355        // Only strip if the result still has a recognised extension — this avoids
356        // accidentally stripping the final dot of "src/foo.rs" when there is none.
357        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        // Must contain at least one slash (directory separator) or look like a
366        // root-relative path, and end with a known extension.
367        let has_ext = extensions
368            .iter()
369            .any(|ext| token.ends_with(&format!(".{ext}")));
370        if !has_ext {
371            continue;
372        }
373        // Accept tokens with at least one path separator, or starting with a
374        // known top-level directory name common in Rust/JS/Python projects.
375        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
389/// Split free-form text into accomplished and remaining bullet lists.
390///
391/// Lines under "remaining", "todo", "next steps", "still needed" headings are
392/// classified as `remaining`; all other bullet lines go into `accomplished`.
393fn 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        // Detect section headings: only lines with explicit heading markers.
417        // Require trailing ':' or '#'-prefix to avoid misclassifying continuation
418        // lines (e.g. explanatory text after a bullet) as headings, which would
419        // incorrectly reset `in_remaining_section`.
420        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        // Bullet lines: -, *, or numbered (1., 2.)
428        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        // Strip leading bullet character(s).
437        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
456/// Detect if text is a CLI/arg-parser diagnostic rather than an agent response.
457/// CLI diagnostics indicate process startup failure, not an agent answer.
458fn is_cli_parser_diagnostic(text: &str) -> bool {
459    let lower = text.to_lowercase();
460
461    // Clap-style error messages
462    if lower.contains("error: unexpected argument") {
463        return true;
464    }
465
466    // Usage/help text patterns
467    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    // Clap help/info hints
475    if lower.contains("for more information, try '--help'") {
476        return true;
477    }
478
479    // Clap "tip" messages about passing values
480    if lower.contains("tip: to pass '") {
481        return true;
482    }
483
484    false
485}
486
487/// Detect whether `text` looks like an NDJSON event stream emitted by an
488/// agent CLI (opencode/claude/codex). Returns true when the first non-empty
489/// line parses as a JSON object containing a `type` field with one of the
490/// known event-type strings.
491///
492/// This guard prevents raw NDJSON from being interpreted as agent prose and
493/// leaking into notification summaries.
494fn 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
524/// Build a synthetic agent response from plain text when structured parsing fails.
525///
526/// Returns `None` for empty/whitespace-only text so callers can preserve the
527/// original `InvalidResponse` behavior.
528pub fn synthesize_response_from_text(text: &str) -> Option<AgentResponse> {
529    // Returns true when `word` appears as a whole word in `text`
530    // (not preceded or followed by an ASCII alphanumeric character).
531    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    // Detect CLI/arg-parser diagnostics and reject them. These indicate the agent
555    // process failed to start properly (e.g. invalid flag), not that the agent
556    // produced a free-form answer. Clap-based CLIs emit patterns like:
557    //   "error: unexpected argument '--flag' found"
558    //   "Usage: command [OPTIONS]"
559    //   "For more information, try '--help'"
560    //   "tip: to pass '...' as a value, use '-- ...'"
561    if is_cli_parser_diagnostic(trimmed) {
562        return None;
563    }
564
565    // Detect NDJSON event streams (opencode/claude/codex stdout) and reject
566    // them. Raw NDJSON masquerading as prose would otherwise leak into
567    // notification summaries — the "completed" substring inside tool state
568    // JSON triggers a false "done" classification and the first 500 bytes of
569    // NDJSON become the user-visible summary.
570    if looks_like_ndjson_event_stream(trimmed) {
571        return None;
572    }
573
574    let lower = trimmed.to_lowercase();
575    // Also accept plain-language confirmations of performed actions (issue/PR
576    // creation, comments, etc.) as a successful "done" signal. This prevents
577    // tasks from being retried when an agent reports success in free-form
578    // text instead of returning structured JSON.
579
580    // Negation phrases that override a "done/completed" match.
581    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    // Strong explicit completion phrases. These are high-confidence indicators
596    // that the agent performed an action (filed issues, created commits, etc.).
597    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        // Action/issue completion phrases
609        "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        // Agent completion phrases (regression: #1362/#1363)
629        "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    // Conservative sentence-level heuristics for single-word signals like "done".
638    // Accept "done" only when it appears in a short, self-contained sentence
639    // without hedging language ("let me", "checking", "will", etc.). This
640    // reduces false-positives from exploratory prose that mentions "done"
641    // as part of a planning or investigatory sentence.
642    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        // short sentence heuristic
650        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        // Commit/concrete action heuristics: require explicit commit language
678        // rather than opportunistic mentions. Examples: "I've committed the changes",
679        // "changes committed", or "commit created".
680        if s_lower.contains("committed") || s_lower.contains("commit created") {
681            // Accept only if sentence also suggests the changes were actually written
682            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        // Past-tense action verb at sentence start indicates a completed action
693        // (e.g. "Added detect_rate_limit patterns", "Fixed the nil-pointer bug").
694        // Accept only for short sentences without hedging language to avoid matching
695        // prose like "I added a note that this might fail later".
696        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        // Agent explicitly stated the task is not complete — surface for human review.
740        "needs_review"
741    } else {
742        // Text is ambiguous: no error signal, no completion signal, no explicit negation.
743        // This happens when agents emit exploratory or startup text (e.g. "Let's go!",
744        // "I need to find where...") and exit without producing structured JSON.
745        // Returning None causes callers to treat this as an invalid response and reroute
746        // the task rather than falsely advancing it to needs_review / in_review.
747        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    // Extract structured fields from free-form text.
756    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
775/// Quote a string for safe insertion into a POSIX shell command.
776pub(crate) fn shell_single_quote(value: &str) -> String {
777    format!("'{}'", value.replace('\'', "'\\''"))
778}
779
780/// Find the largest byte index <= `max_bytes` that lies on a UTF-8 char
781/// boundary.  Used for safe string truncation in error messages.
782pub fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> usize {
783    if max_bytes >= s.len() {
784        return s.len();
785    }
786    // Walk backwards from max_bytes until we hit a char boundary
787    let mut end = max_bytes;
788    while end > 0 && !s.is_char_boundary(end) {
789        end -= 1;
790    }
791    end
792}
793
794/// One step of an agent's work, as `orch stream` shows it
795#[derive(Debug, Clone, PartialEq)]
796pub enum StreamEvent {
797    Started {
798        model: String,
799    },
800    Text(String),
801    Thinking(String),
802    /// `id` links the call to its result, empty when the agent has none
803    ToolCall {
804        id: String,
805        name: String,
806        input: serde_json::Value,
807    },
808    /// `name` is empty when only `id` names the call
809    ToolResult {
810        id: String,
811        name: String,
812        output: String,
813        is_error: bool,
814    },
815    Done(String),
816    Error(String),
817}
818
819/// String at a JSON pointer, empty when missing
820pub(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
826/// Error text from any of the shapes agents use: `message`, `error`, `error.message`, `error.data.message`
827pub(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/// Router stdout shape. Each runner reports its own
841#[derive(Debug, Clone, Copy, PartialEq, Eq)]
842pub enum RouterTranscript {
843    /// Claude Messages NDJSON (`type:result`)
844    Messages,
845    /// OpenCode NDJSON (`type:text`, `step_*`)
846    OpenCode,
847    /// Stdout is used as-is
848    Raw,
849}
850
851/// Per-agent runner trait.
852///
853/// Each agent implements this to handle its specific CLI invocation,
854/// output parsing, and error classification.
855pub trait AgentRunner: Send + Sync {
856    /// Agent name (e.g., "claude", "codex", "opencode"). Used in tests.
857    #[cfg(test)]
858    fn name(&self) -> &str;
859
860    /// Build the CLI command string for the legacy tmux runner.
861    ///
862    /// The returned string is embedded into a shell command that captures
863    /// output in the tmux session. The `permissions` struct carries unified
864    /// rules that each agent translates to its own CLI flags.
865    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    /// Parse raw stdout into a ParsedResponse.
875    ///
876    /// Returns `Ok(ParsedResponse)` on success, `Err(AgentError)` if the
877    /// output indicates an error or cannot be parsed.
878    fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError>;
879
880    /// Extract the raw inner text from an agent output envelope, without
881    /// attempting to parse it as an `AgentResponse`.
882    ///
883    /// Use this in the review pipeline so that a `ReviewResponse` JSON can be
884    /// recovered even when the text doesn't match the task `AgentResponse` schema.
885    ///
886    /// - For Claude/Kimi/MiniMax: strips the `--output-format stream-json` NDJSON
887    ///   wrapper and returns the `"result"` field of the final `"type":"result"` line.
888    /// - For Codex: returns the text of the last `agent_message` item.
889    /// - For OpenCode: concatenates all `text` events.
890    /// - Default: returns `raw` unchanged (safe fallback for unknown agents).
891    ///
892    /// Returns `Err(AgentError)` only for terminal errors (rate limit, auth, etc.)
893    /// that should abort the review pipeline entirely.
894    fn extract_text(&self, raw: &str) -> Result<String, AgentError> {
895        Ok(raw.to_string())
896    }
897
898    /// Transcript steps for one parsed line of this agent's NDJSON output
899    fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent>;
900
901    /// Classify an error from exit code + stdout + stderr into an AgentError.
902    ///
903    /// Called when the agent process exits with a non-zero code, or when
904    /// parse_response fails to find a valid result.
905    fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError;
906
907    /// Classify error with elapsed session time (for accurate timeout reporting).
908    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    /// Models available for this agent (for intra-agent failover).
925    fn available_models(&self) -> Vec<String> {
926        vec![]
927    }
928
929    /// Free/fallback models for last-resort failover.
930    fn free_models(&self) -> Vec<String> {
931        vec![]
932    }
933
934    /// Router stdout shape. The router matches on this instead of agent names
935    fn router_transcript(&self) -> RouterTranscript {
936        RouterTranscript::Raw
937    }
938
939    /// Build a minimal CLI command for LLM-based routing.
940    ///
941    /// The command should run the agent with `prompt` as the sole task and
942    /// return structured (JSON or NDJSON) output on stdout. Used by the router
943    /// to classify tasks without launching a full agent session.
944    fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command>;
945}
946
947/// Agents whose CLI takes `--session-id` for a new session and `--resume` to continue it
948pub fn supports_session(agent: &str) -> bool {
949    matches!(agent, "claude" | "kimi" | "minimax" | "grok")
950}
951
952/// Get the appropriate AgentRunner implementation for an agent name.
953pub fn get_runner(agent_name: &str) -> Box<dyn AgentRunner> {
954    // Agents that are known to be claude-compatible (same NDJSON output format)
955    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        // Unknown agents fall back to Claude-compatible parsing
965        other => {
966            // Only warn if the agent is not known to be claude-compatible
967            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
978/// Parse an NDJSON stream into a list of JSON values.
979///
980/// Shared by all agents that emit NDJSON output (Codex, OpenCode, etc.).
981/// Lines that are empty or unparseable are silently skipped with a debug log.
982///
983/// For fragmented streams where complete JSON objects span multiple lines,
984/// we also attempt to concatenate non-empty lines and parse them as a stream
985/// of JSON objects to handle edge cases where models emit partial NDJSON.
986pub(crate) fn parse_ndjson(raw: &str) -> Vec<serde_json::Value> {
987    // Fast path: try parsing each line individually (handles most cases)
988    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 we got events, return them. Otherwise, try the accumulation fallback
1001    // for edge cases where models emit fragmented JSON (e.g., partial objects
1002    // that get split across lines, or streams with embedded newlines in strings).
1003    if !events.is_empty() {
1004        return events;
1005    }
1006
1007    // Fallback: accumulate all non-empty, non-comment lines and try to extract
1008    // JSON objects by scanning for balanced braces. This handles edge cases like:
1009    // - Closing fence inside JSON strings: {"text": "```json\n{\"status\": \"done\"}\n```"}
1010    // - Fragmented NDJSON where incomplete objects span multiple lines
1011    // - Model outputs with embedded newlines in text fields
1012    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    // Fallback: try to parse the accumulated text directly as a JSON value.
1026    // This handles multi-line JSON objects that don't fit on single lines.
1027    if let Ok(val) = serde_json::from_str::<serde_json::Value>(acc.trim()) {
1028        // Check if stripping ALL whitespace makes it a single JSON object with
1029        // the same content. If so, the input was plain multi-line JSON (not
1030        // fragmented NDJSON), and we should return empty to preserve original
1031        // behavior — callers then treat it as plain text.
1032        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            // Only return empty if the stripped version parses identically,
1035            // meaning whitespace was insignificant. If they differ, whitespace
1036            // matters and this is likely fragmented input.
1037            if stripped_val == val {
1038                return Vec::new();
1039            }
1040        }
1041        return vec![val];
1042    }
1043
1044    // Direct parse failed — try to extract JSON objects by scanning for balanced
1045    // braces. This handles cases like embedded JSON within text:
1046    // `{"text": "```json\n{\"status\": \"done\"}\n```"}`
1047    extract_json_objects(&acc)
1048}
1049
1050/// Extract complete JSON objects from a string by scanning for balanced braces.
1051///
1052/// This is a fallback for fragmented NDJSON streams where complete objects
1053/// don't appear on single lines. Returns all parseable objects found.
1054fn 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        // olm and glm are claude-compatible and should return correct name
1160        assert_eq!(get_runner("olm").name(), "olm");
1161        assert_eq!(get_runner("glm").name(), "glm");
1162        // Unknown falls back to claude-compatible
1163        assert_eq!(get_runner("unknown-agent").name(), "unknown-agent");
1164    }
1165
1166    /// Regression test: known claude-compatible agents (including glm) must not
1167    /// emit "unknown agent" warnings when get_runner() is called.
1168    #[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        // Regression test for issue #3283: Claude "weekly limit" errors were
1245        // classified as `failed` instead of `rate_limit` because "weekly limit"
1246        // was not in the detect_rate_limit pattern list.
1247        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        // Regression test for issue #3302: "You have exceeded your monthly quota"
1270        // was not matched because detect_rate_limit only checked "quota exceeded"
1271        // (reversed word order), causing 4 immediate retries with no cooldown.
1272        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        // Regression test for issue #3361: Nvidia "ResourceExhausted: Worker local total
1282        // request limit reached" was classified as generic `failed` instead of `rate_limit`,
1283        // bypassing the cooldown path and weakening routing health signals.
1284        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        // Both sub-patterns must match independently.
1292        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        // classify_from_text must also route this to RateLimit (exercises the tail-scan path).
1303        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        // Simulate a long claude NDJSON output where the rate limit message is in
1313        // the middle and usage stats JSON is at the tail.
1314        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        // Bare "529" in various contexts should NOT trigger rate limit detection.
1334        // These are false positive cases we want to avoid.
1335        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        // But HTTP 529 status codes SHOULD match.
1352        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        // Bare numbers in JSON must NOT trigger auth classification.
1383        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        // JSON field with colon: "duration_api_ms": 4010292 — contains ": 401" as substring.
1391        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        // ": 401" at end-of-string or followed by non-digit must still match.
1399        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        // Regression test for issue #3642: "insufficient balance" (and by extension
1406        // "402 Payment Required: insufficient balance") must be detected as an auth
1407        // error so it routes through the credit exhaustion path, not the generic 5-min
1408        // backoff. This ensures the #3642 cooldown behavior is properly triggered.
1409        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        // The stored message should contain the matched pattern.
1418        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        // The message should be the line containing the auth error, not the tail.
1428        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        // Simulate real agent output: auth error appears early, NDJSON session
1438        // metadata at the end. Stored message must be the error line, not the
1439        // trailing JSON that agents emit at exit.
1440        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        // The message should be the line containing the auth error, not the tail.
1455        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        // Simulate real agent output: error appears early, unrelated stats JSON at the end.
1479        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        // Exact error message from Claude
1546        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        // Case-insensitive
1555        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        // Non-matching text
1559        assert!(patterns::detect_stale_session("all good").is_none());
1560        assert!(patterns::detect_stale_session("conversation started").is_none());
1561
1562        // Multi-byte UTF-8 characters before the match must not panic.
1563        // German ß lowercases to "ss" (1 byte → 2 bytes), so using a byte
1564        // offset from `lower` directly into `text` would be wrong.
1565        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        // Missing tool takes priority over rate limit patterns
1594        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        // Issue #3604: plain-text "model not found" errors (no structured
1607        // NDJSON event) must classify as ModelUnavailable, not fall through to
1608        // Unknown, so the agent-wide cooldown is not bumped for a bad model name.
1609        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        // Regression test for issue #1292: agent output containing rate-limit
1633        // keywords in code/diffs must not be misclassified as a rate limit error.
1634        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); // ~200 lines of work product — well over 3000 chars
1639        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        // A real rate-limit error printed at the end of the output must still
1651        // be detected, even if work product precedes it.
1652        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        // Regression test: non-ASCII characters before `rate_limit` that change
1677        // byte length when lowercased (e.g. İ 2→3 bytes, fl 3→2 bytes) must not
1678        // cause is_word_boundary to index text at an invalid byte offset.
1679        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        // Regression test for issue #3272: Claude session limit errors appear as
1690        // `type:system` NDJSON events early in the stream, not as `type:result`
1691        // lines. When the agent produces significant output after the error, the
1692        // system event is pushed out of the tail window and missed by tail-only
1693        // scanning. The head scan must catch it.
1694        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        // Generate enough work product (>3000 bytes) to push the system event
1696        // out of the tail window.
1697        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        // Verify the output is large enough that the event is not in the tail.
1701        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        // The message should contain the actual error, not unrelated tail content.
1711        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        // Regression test for issue #2126: auth keywords in agent work product
1721        // must not trigger auth classification when the real failure is
1722        // unrelated and appears at the end of the output.
1723        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        // Regression test for issue #2205: context overflow keywords in agent
1754        // work product must not trigger ContextOverflow when the real failure is
1755        // unrelated and appears at the end of the output.
1756        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        // Regression test for issue #2205: permission-related keywords in agent
1789        // work product must not trigger PermissionDenied when the real failure
1790        // is unrelated and appears at the end of the output.
1791        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        // Regression test for issue #2205: input-request keywords in agent work
1826        // product must not trigger WaitingForInput when the real failure is
1827        // unrelated and appears at the end of the output.
1828        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        // Regression test for issue #1800: classify_from_text must call
1881        // detect_stale_session to catch "No conversation found with session ID"
1882        // errors. Without this, the error would be misclassified as Unknown and
1883        // the control.rs recovery code would not trigger.
1884        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        // Verify the Display format matches what control.rs expects
1891        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        // Regression test for issue #3045: "socket connection was closed" must be
1900        // classified as NetworkError, not Unknown.
1901        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        // Regression test for issue #3541: kimi's "Response stalled mid-stream" must be
1940        // classified as NetworkError, not Unknown/AgentFailed.
1941        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        // Regression test for issue #3541: claude's "Connection closed mid-response" must be
1954        // classified as NetworkError, not Unknown/AgentFailed.
1955        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    /// Regression: raw NDJSON event streams (opencode/claude/codex stdout)
1998    /// must be rejected by the synthesizer. Without the guard, the
1999    /// "completed" substring inside tool state JSON triggers a false "done"
2000    /// classification and 500 bytes of raw NDJSON leak into the
2001    /// notification summary.
2002    #[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        // A JSON-like blob that does NOT match a known NDJSON event type
2022        // should still be allowed through to the regular synthesis path
2023        // (so the guard does not over-reach).
2024        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    // Regression: opencode/nemotron-3-super-free and similar models sometimes exit
2030    // with code 0 after emitting only exploratory or startup text (e.g. "Let's go!",
2031    // planning prose) without completing any work.  The synthesis must return None for
2032    // such ambiguous text so the runner treats the run as an invalid response and
2033    // reroutes the task instead of falsely advancing it to needs_review / in_review.
2034    // (Issues #2404, #2653, #2666)
2035    #[test]
2036    fn synthesize_response_returns_none_for_ambiguous_startup_text() {
2037        // Short greeting — not an error, not done, not an explicit negation.
2038        assert!(
2039            synthesize_response_from_text("Let's go!").is_none(),
2040            "startup greeting must not synthesize as needs_review"
2041        );
2042        // Exploratory planning prose — agent is thinking out loud, not reporting completion.
2043        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        // Regression test: ensure exploratory analysis that mentions "let me check"
2130        // or planning language is NOT synthesized into a "done" completion.
2131        // With the ambiguous-text fix, this text correctly returns None (treated as
2132        // an invalid response / reroute signal) rather than synthesizing needs_review.
2133        // Crucially, it must NOT be marked "done".
2134        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                // Ambiguous exploratory prose correctly returns None — not marked done.
2138            }
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    // ── Regression: #1362/#1363 — agent text misclassified as needs_review ──
2167
2168    #[test]
2169    fn synthesize_response_marks_done_for_fix_is_complete() {
2170        // Exact agent output from task 30203 (issue #1363).
2171        // "The fix is complete" was misclassified as needs_review because
2172        // the pattern list had "completed" but not "complete".
2173        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        // Exact agent output from task 30204 (issue #1362).
2189        // "All tests pass. The fix is clean and working." was misclassified
2190        // as needs_review because none of the looks_done patterns matched.
2191        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    // ── parse_ndjson edge cases ───────────────────────────────────
2205
2206    #[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        // Edge case: JSON with closing fence inside string field
2238        let raw =
2239            r#"text: {"text": "here is the result: ```json\n{\"status\":\"done\"}\n```"} more"#;
2240        let events = parse_ndjson(raw);
2241        // Should have extracted the embedded JSON object
2242        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        // Edge case: JSON object spread across multiple lines (fragmented NDJSON)
2251        let raw = r#"{"type": "text
2252", "content": "hello
2253world"}"#;
2254        let events = parse_ndjson(raw);
2255        // Should still extract the JSON via fallback
2256        assert!(!events.is_empty(), "should handle fragmented JSON");
2257    }
2258
2259    // ── PermissionRules defaults ────────────────────────────────
2260
2261    #[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    // ── Permission translation across all agents ────────────────
2291
2292    /// Test that all agents handle the default permission rules consistently.
2293    #[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        // Claude: should have bypassPermissions and rm disallowed
2300        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        // Codex: autonomous + workspace-write → --sandbox workspace-write -c 'approval_policy="never"'
2312        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        // OpenCode: autonomous dispatch passes --dangerously-skip-permissions
2332        // and writes no config file (relies on opencode's built-in flag).
2333        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 supervised mode translates correctly for each agent.
2354    #[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        // Claude: supervised → acceptEdits
2369        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        // Codex: supervised → on-request
2377        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 full access sandbox translates correctly for each agent.
2390    #[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        // Claude: ignores sandbox level (no --sandbox flag)
2405        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        // Codex: full access → --dangerously-bypass-approvals-and-sandbox
2413        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    /// SandboxLevel::None with autonomous uses --sandbox workspace-write (same as WorkspaceWrite).
2422    #[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 that allowed_edit_paths scopes Edit/Write when used with allowed_tools.
2454    #[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        // Edit/Write should be scoped to worktree path
2474        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        // Read should be unrestricted
2483        assert!(cmd.contains("Read"), "missing Read");
2484    }
2485
2486    /// Test that blocked paths don't affect Codex (it uses sandbox isolation).
2487    #[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 that blocked paths don't affect OpenCode.
2507    #[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 that disallowed tools merge correctly for Claude (defaults + custom).
2527    #[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 that Codex ignores disallowed tools (has no such flag).
2550    #[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 Claude with empty disallowed tools produces no --disallowedTools flag.
2570    #[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 Kimi/MiniMax aliases inherit Claude permission translation.
2590    #[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 kimi/minimax get --allowedTools when allowed_tools is set.
2619    #[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    // ── Allowed tools across agents ─────────────────────────────
2646
2647    /// Test that allowed_tools generates --allowedTools for Claude.
2648    #[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 that codex/opencode ignore allowed_tools (no equivalent flag).
2679    #[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    // ── Integration: from_config() → agent translation ──────────
2707
2708    /// Integration test: verify from_config() loads real config and agents
2709    /// translate it correctly. Requires ~/.orch/config.yml to exist.
2710    #[test]
2711    #[ignore = "reads the operator config"]
2712    fn integration_from_config_to_agent_commands() {
2713        let perms = PermissionRules::from_config();
2714
2715        // Verify defaults are reasonable
2716        assert!(
2717            perms.autonomous,
2718            "from_config: expected autonomous=true by default"
2719        );
2720
2721        // Verify each agent can build a command from the config-loaded rules
2722        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    /// Integration test: verify from_config() handles supervised mode.
2738    /// Requires config with workflow.permissions.mode = "supervised".
2739    #[test]
2740    #[ignore = "reads the operator config"]
2741    fn integration_supervised_config_translates_correctly() {
2742        // This test requires config to have:
2743        // workflow:
2744        //   permissions:
2745        //     mode: supervised
2746        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            // autonomous codex uses --sandbox workspace-write -c 'approval_policy="never"'
2768            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    // ── deny_read_only preset ───────────────────────────────────
2789
2790    /// Test that deny_read_only() sets the right disallowed tools for control sessions.
2791    #[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 that deny_read_only() produces correct Claude command for control session.
2820    #[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        // Should contain Read, Glob, Grep disallow patterns
2827        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        // Should block ls
2840        assert!(
2841            cmd.contains("Bash(ls") || cmd.contains("Bash(ls *)"),
2842            "should block ls"
2843        );
2844        // Should still have bypassPermissions (autonomous)
2845        assert!(
2846            cmd.contains("--permission-mode bypassPermissions"),
2847            "should be autonomous (bypassPermissions)"
2848        );
2849    }
2850
2851    // --- synthesize_response_from_text structured extraction ---
2852
2853    #[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    // ── detect_rate_limit false-positive guard ────────────────────────────
2922    // Regression: NDJSON telemetry blobs can contain "429" as a token count
2923    // (e.g. "outputTokens":429). `detect_rate_limit` should still flag those
2924    // because it cannot distinguish context without the terminal_reason guard.
2925    // The guard lives in review.rs, but here we verify the raw detector
2926    // behaviour so callers know they must apply the guard themselves.
2927    #[test]
2928    fn detect_rate_limit_fires_on_bare_429_in_token_count() {
2929        // This SHOULD return Some — the generic detector has no context.
2930        // The caller (review.rs) is responsible for suppressing it when
2931        // terminal_reason:completed is present.
2932        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    // Verify the guard logic that review.rs uses: when raw NDJSON has
2965    // terminal_reason:completed without is_error:true, the result of
2966    // detect_rate_limit should be suppressed.
2967    #[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        // Apply the same guard that review.rs now uses.
2973        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    // Verify the guard does NOT suppress a real rate-limit error.
2983    #[test]
2984    fn terminal_reason_completed_guard_passes_real_rate_limit() {
2985        // Real rate-limit output has no terminal_reason:completed.
2986        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        // URLs and version strings should not appear in files list.
3001        // The text is ambiguous (no error, no done signal, no explicit negation) so
3002        // synthesize_response_from_text returns None — no file extraction happens.
3003        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 => {} // Ambiguous text correctly returns None — no files extracted.
3006            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    // Regression: issue #3197 — CLI arg-parser diagnostics were being synthesized as
3017    // agent responses. When a process (e.g. codex) fails with an invalid CLI flag, it
3018    // exits non-zero with a clap/help diagnostic on stderr. This should be rejected
3019    // (return None) rather than synthesized as a "needs_review" response.
3020    #[test]
3021    fn synthesize_rejects_cli_parser_diagnostics_unexpected_argument() {
3022        // Real clap error from the bug report (codex exit 141)
3023        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        // Agent returning plain text that happens to contain "error:" but is an actual
3062        // agent message (e.g. summarizing what went wrong) should still synthesize.
3063        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    // Regression: Issue #3197 — exact clap error from bug report.
3071    // When codex fails with an invalid CLI flag (e.g., --ask-for-approval with old codex versions),
3072    // it should return None, not synthesize as "needs_review". Without this fix, the run
3073    // would be marked as success and advance to in_review, wasting resources.
3074    #[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}