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