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    /// Reads only, and runs `allowed_tools` and nothing else, refused without a prompt. For a chat
79    /// whose context holds text anyone can write
80    ReadOnly,
81}
82
83impl Default for PermissionRules {
84    fn default() -> Self {
85        Self {
86            autonomous: true,
87            sandbox: SandboxLevel::WorkspaceWrite,
88            disallowed_tools: vec![
89                "Bash(rm *)".to_string(),
90                "Bash(rm -*)".to_string(),
91                "Bash(git push*)".to_string(),
92            ],
93            allowed_tools: vec![],
94            allowed_edit_paths: vec![],
95            deny_read_only: false,
96            extra_writable_dirs: vec![],
97        }
98    }
99}
100
101impl PermissionRules {
102    /// Load permission rules from config, falling back to defaults.
103    pub fn from_config() -> Self {
104        let mut rules = Self::default();
105
106        if let Ok(mode) = config::get("workflow.permissions.mode") {
107            rules.autonomous = mode != "supervised";
108        }
109
110        if let Ok(sandbox) = config::get("workflow.permissions.sandbox") {
111            rules.sandbox = match sandbox.as_str() {
112                "full-access" | "danger-full-access" => SandboxLevel::FullAccess,
113                "none" => SandboxLevel::None,
114                _ => SandboxLevel::WorkspaceWrite,
115            };
116        }
117
118        if let Ok(tools) = config::get("workflow.disallowed_tools") {
119            let parsed: Vec<String> = tools
120                .split(',')
121                .map(|s| s.trim().to_string())
122                .filter(|s| !s.is_empty())
123                .collect();
124            if !parsed.is_empty() {
125                rules.disallowed_tools = parsed;
126            }
127        }
128
129        if let Ok(tools) = config::get_list("workflow.allowed_tools") {
130            rules.allowed_tools = tools;
131        }
132
133        rules
134    }
135
136    /// Restriction preset for control sessions: denies Read, Glob, Grep, and
137    /// Bash commands that read files or list directories (ls, cat, find, etc.).
138    ///
139    /// The agent remains autonomous but is prevented from browsing or reading
140    /// arbitrary files on the host machine. Translation into agent-native flags
141    /// is handled by each `AgentRunner::build_command()` implementation.
142    /// A chat that may read and run `allowed`, and is refused everything else
143    pub fn read_only(allowed: Vec<String>) -> Self {
144        Self {
145            autonomous: false,
146            sandbox: SandboxLevel::ReadOnly,
147            disallowed_tools: vec![],
148            allowed_tools: allowed,
149            allowed_edit_paths: vec![],
150            deny_read_only: false,
151            extra_writable_dirs: vec![],
152        }
153    }
154
155    pub fn deny_read_only() -> Self {
156        Self {
157            autonomous: true,
158            sandbox: SandboxLevel::WorkspaceWrite,
159            disallowed_tools: vec![
160                "Bash(rm *)".to_string(),
161                "Bash(rm -*)".to_string(),
162                "Bash(git push*)".to_string(),
163                "Bash(ls *)".to_string(),
164                "Bash(ls)".to_string(),
165                "Bash(find *)".to_string(),
166                "Bash(cat *)".to_string(),
167                "Bash(head *)".to_string(),
168                "Bash(tail *)".to_string(),
169                "Bash(fzf *)".to_string(),
170                "Bash(less *)".to_string(),
171                "Bash(more *)".to_string(),
172                "Read".to_string(),
173                "Glob".to_string(),
174                "Grep".to_string(),
175            ],
176            allowed_tools: vec![],
177            allowed_edit_paths: vec![],
178            deny_read_only: true,
179            extra_writable_dirs: vec![],
180        }
181    }
182}
183
184/// Structured result from per-agent NDJSON extraction.
185///
186/// Each agent emits a different NDJSON format. The per-agent `find_result`
187/// functions parse agent-specific envelopes and return a unified `AgentResult`
188/// so callers (review pipeline, response handler) don't need format knowledge.
189#[derive(Debug, Clone)]
190pub struct AgentResult {
191    /// Whether the agent reported an error (e.g. `is_error: true` in Claude).
192    pub is_error: bool,
193    /// The extracted result text (inner content, stripped of envelope).
194    pub result_text: String,
195    /// Input tokens consumed (if reported by the agent).
196    pub input_tokens: Option<u64>,
197    /// Output tokens consumed (if reported by the agent).
198    pub output_tokens: Option<u64>,
199    /// Total cost in USD (if reported by the agent).
200    pub cost_usd: Option<f64>,
201    /// Wall-clock duration in milliseconds (if reported by the agent).
202    pub duration_ms: Option<u64>,
203    /// True when the provider cut the response short by exceeding its
204    /// output/reasoning token budget (e.g. opencode's `step_finish` event
205    /// reporting `reason: "length"`), as opposed to producing malformed
206    /// output. Callers use this to distinguish a token-budget fluke from a
207    /// genuinely format-incapable model.
208    pub truncated_by_length: bool,
209}
210
211/// Concatenate text from all assistant-turn messages in the agent's NDJSON
212/// output stream.  Used as an intermediate fallback when the `type:result`
213/// envelope text is not valid AgentResponse JSON but an earlier assistant
214/// message in the conversation might contain it.
215pub fn collect_assistant_messages_text(_agent: &str, ndjson: &str) -> String {
216    claude::collect_assistant_messages_text(ndjson)
217}
218
219/// Dispatch to the appropriate per-agent result extractor.
220///
221/// Returns `None` if no structured result could be found in the output
222/// (e.g. plain text, empty output, or unrecognized format).
223pub fn find_agent_result(agent: &str, ndjson: &str) -> Option<AgentResult> {
224    match agent {
225        "grok" => grok::find_grok_result(ndjson),
226        "opencode" => opencode::find_opencode_result(ndjson),
227        "codex" => codex::find_codex_result(ndjson),
228        // claude, kimi, minimax and unknown agents all emit the claude format
229        _ => claude::find_claude_result(ndjson),
230    }
231}
232
233/// Parsed response from an agent, including metadata extracted from the
234/// agent-specific output envelope.
235#[derive(Debug, Clone)]
236pub struct ParsedResponse {
237    /// Normalized task response (status, summary, accomplished, etc.)
238    pub response: AgentResponse,
239    /// Input tokens consumed (if reported by the agent).
240    pub input_tokens: Option<u64>,
241    /// Output tokens consumed (if reported by the agent).
242    pub output_tokens: Option<u64>,
243    /// Cost in USD of this run, as the agent reported it.
244    pub cost_usd: Option<f64>,
245    /// Wall-clock duration in milliseconds (if reported by the agent).
246    pub duration_ms: Option<u64>,
247}
248
249/// Agent-specific error with enough detail for autonomous recovery.
250#[derive(Debug, Clone)]
251pub enum AgentError {
252    /// Rate/usage limit — reroute to different agent, cooldown current.
253    RateLimit { message: String },
254    /// Auth/billing/API key error — switch agent entirely.
255    Auth { message: String },
256    /// Requested model not available — try different model, then switch agent.
257    ModelUnavailable { message: String, model: String },
258    /// Context window exceeded — truncate and retry, then switch agent.
259    ContextOverflow { message: String },
260    /// Agent hit the task time limit. Retry without cooling the model
261    Timeout { elapsed: Duration },
262    /// Process exited with no result envelope, usually a kill rather than a model fault
263    Interrupted { message: String },
264    /// Required tool/binary missing from the environment.
265    MissingTool { tool: String },
266    /// Sandbox or filesystem permission denied.
267    PermissionDenied { message: String },
268    /// Agent is waiting for interactive input (e.g., 1Password, SSH).
269    WaitingForInput { message: String },
270    /// The agent's session ID is no longer valid (session expired or was cleared).
271    ///
272    /// Returned when Claude reports "No conversation found with session ID: <uuid>".
273    /// The caller should reset the stored UUID and retry with a fresh `--session-id`.
274    StaleSession { session_id: String },
275    /// Agent returned unparseable output.
276    InvalidResponse { raw: String },
277    /// Agent self-reported a failure in its response.
278    AgentFailed { message: String },
279    /// Transient network connectivity error — retry same agent, no failover.
280    NetworkError { message: String },
281    /// Thinking blocks cannot be modified (Claude extended-thinking + tool-use 400).
282    ///
283    /// Transient API incompatibility inside the Claude CLI's multi-turn tool-use
284    /// loop — the Anthropic API rejects the request when thinking blocks are altered
285    /// between turns. Not a model capacity problem: does NOT increment failure counts
286    /// or apply cooldowns. The task is rerouted to a different agent.
287    ThinkingBlockConflict { message: String },
288    /// Unclassified error.
289    Unknown { exit_code: i32, message: String },
290}
291
292impl Display for AgentError {
293    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
294        match self {
295            Self::RateLimit { message, .. } => write!(f, "rate limit: {message}"),
296            Self::Auth { message } => write!(f, "auth error: {message}"),
297            Self::ModelUnavailable { message, model } => {
298                write!(f, "model unavailable ({model}): {message}")
299            }
300            Self::ContextOverflow { message, .. } => write!(f, "context overflow: {message}"),
301            Self::Timeout { elapsed } => write!(f, "timeout after {}s", elapsed.as_secs()),
302            Self::Interrupted { message } => write!(f, "interrupted: {message}"),
303            Self::MissingTool { tool } => write!(f, "missing tool: {tool}"),
304            Self::PermissionDenied { message } => write!(f, "permission denied: {message}"),
305            Self::WaitingForInput { message } => write!(f, "waiting for input: {message}"),
306            Self::StaleSession { session_id } => {
307                write!(f, "stale session (session expired): {session_id}")
308            }
309            Self::InvalidResponse { raw } => {
310                let end = truncate_at_char_boundary(raw, 200);
311                write!(f, "invalid response: {}", &raw[..end])
312            }
313            Self::AgentFailed { message } => write!(f, "agent failed: {message}"),
314            Self::NetworkError { message } => write!(f, "network error: {message}"),
315            Self::ThinkingBlockConflict { message } => {
316                write!(f, "thinking block conflict: {message}")
317            }
318            Self::Unknown { exit_code, message } => {
319                write!(f, "unknown error (exit {exit_code}): {message}")
320            }
321        }
322    }
323}
324
325impl error::Error for AgentError {}
326
327/// Return the variant name of an `AgentError` as a static string,
328/// for structured logging and `result.json` output.
329pub fn error_class_name(err: &AgentError) -> &'static str {
330    match err {
331        AgentError::RateLimit { .. } => "RateLimit",
332        AgentError::Auth { .. } => "Auth",
333        AgentError::ModelUnavailable { .. } => "ModelUnavailable",
334        AgentError::ContextOverflow { .. } => "ContextOverflow",
335        AgentError::Timeout { .. } => "Timeout",
336        AgentError::Interrupted { .. } => "Interrupted",
337        AgentError::MissingTool { .. } => "MissingTool",
338        AgentError::PermissionDenied { .. } => "PermissionDenied",
339        AgentError::WaitingForInput { .. } => "WaitingForInput",
340        AgentError::StaleSession { .. } => "StaleSession",
341        AgentError::InvalidResponse { .. } => "InvalidResponse",
342        AgentError::AgentFailed { .. } => "AgentFailed",
343        AgentError::NetworkError { .. } => "NetworkError",
344        AgentError::ThinkingBlockConflict { .. } => "ThinkingBlockConflict",
345        AgentError::Unknown { .. } => "Unknown",
346    }
347}
348
349/// Extract file paths from free-form text.
350///
351/// Matches common source file patterns like `src/foo/bar.rs`, `tests/x.py`,
352/// `path/to/file.ts`, etc. Deduplicates and returns them sorted.
353fn extract_file_paths(text: &str) -> Vec<String> {
354    // Match path-like tokens: optional leading slash or no slash, at least one
355    // directory segment or a plain filename, with a recognised extension.
356    let extensions = [
357        "rs", "py", "ts", "tsx", "js", "jsx", "go", "java", "c", "cpp", "h", "hpp", "rb", "sh",
358        "md", "toml", "yaml", "yml", "json", "sql", "html", "css", "swift", "kt",
359    ];
360    let mut found: BTreeSet<String> = BTreeSet::new();
361    for token in text.split_whitespace() {
362        // Strip surrounding punctuation (backticks, quotes, parens, commas).
363        // We intentionally do NOT strip '.' here because it is part of file extensions.
364        let token = token.trim_matches(|c: char| {
365            matches!(
366                c,
367                '`' | '\'' | '"' | '(' | ')' | '[' | ']' | ',' | ':' | ';'
368            )
369        });
370        // Strip a lone trailing dot that ends a sentence (e.g. "src/foo.rs.").
371        // Only strip if the result still has a recognised extension — this avoids
372        // accidentally stripping the final dot of "src/foo.rs" when there is none.
373        let token = if let Some(without) = token.strip_suffix('.') {
374            let still_has_ext = extensions
375                .iter()
376                .any(|ext| without.ends_with(&format!(".{ext}")));
377            if still_has_ext { without } else { token }
378        } else {
379            token
380        };
381        // Must contain at least one slash (directory separator) or look like a
382        // root-relative path, and end with a known extension.
383        let has_ext = extensions
384            .iter()
385            .any(|ext| token.ends_with(&format!(".{ext}")));
386        if !has_ext {
387            continue;
388        }
389        // Accept tokens with at least one path separator, or starting with a
390        // known top-level directory name common in Rust/JS/Python projects.
391        let path_like = token.contains('/')
392            || token.starts_with("src")
393            || token.starts_with("tests")
394            || token.starts_with("lib")
395            || token.starts_with("bin")
396            || token.starts_with("prompts")
397            || token.starts_with("migrations");
398        if path_like && token.len() >= 4 && !token.contains("://") {
399            found.insert(token.to_string());
400        }
401    }
402    found.into_iter().collect()
403}
404
405/// Split free-form text into accomplished and remaining bullet lists.
406///
407/// Lines under "remaining", "todo", "next steps", "still needed" headings are
408/// classified as `remaining`; all other bullet lines go into `accomplished`.
409fn extract_bullet_sections(text: &str) -> (Vec<String>, Vec<String>) {
410    let remaining_headers = [
411        "remaining",
412        "todo",
413        "to do",
414        "next steps",
415        "still needed",
416        "left to do",
417        "not done",
418        "outstanding",
419    ];
420
421    let mut accomplished: Vec<String> = vec![];
422    let mut remaining: Vec<String> = vec![];
423    let mut in_remaining_section = false;
424
425    for line in text.lines() {
426        let trimmed = line.trim();
427        if trimmed.is_empty() {
428            continue;
429        }
430        let lower = trimmed.to_lowercase();
431
432        // Detect section headings: only lines with explicit heading markers.
433        // Require trailing ':' or '#'-prefix to avoid misclassifying continuation
434        // lines (e.g. explanatory text after a bullet) as headings, which would
435        // incorrectly reset `in_remaining_section`.
436        let is_heading = trimmed.ends_with(':') || trimmed.starts_with('#');
437
438        if is_heading {
439            in_remaining_section = remaining_headers.iter().any(|h| lower.contains(h));
440            continue;
441        }
442
443        // Bullet lines: -, *, or numbered (1., 2.)
444        let is_bullet = trimmed.starts_with('-')
445            || trimmed.starts_with('*')
446            || trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains('.');
447
448        if !is_bullet {
449            continue;
450        }
451
452        // Strip leading bullet character(s).
453        let content = trimmed
454            .trim_start_matches(|c: char| c == '-' || c == '*' || c.is_ascii_digit() || c == '.')
455            .trim()
456            .to_string();
457
458        if content.is_empty() {
459            continue;
460        }
461
462        if in_remaining_section {
463            remaining.push(content);
464        } else {
465            accomplished.push(content);
466        }
467    }
468
469    (accomplished, remaining)
470}
471
472/// Detect if text is a CLI/arg-parser diagnostic rather than an agent response.
473/// CLI diagnostics indicate process startup failure, not an agent answer.
474fn is_cli_parser_diagnostic(text: &str) -> bool {
475    let lower = text.to_lowercase();
476
477    // Clap-style error messages
478    if lower.contains("error: unexpected argument") {
479        return true;
480    }
481
482    // Usage/help text patterns
483    if text.lines().any(|line| {
484        let trimmed = line.trim();
485        trimmed.starts_with("Usage:") || trimmed.starts_with("usage:")
486    }) {
487        return true;
488    }
489
490    // Clap help/info hints
491    if lower.contains("for more information, try '--help'") {
492        return true;
493    }
494
495    // Clap "tip" messages about passing values
496    if lower.contains("tip: to pass '") {
497        return true;
498    }
499
500    false
501}
502
503/// Detect whether `text` looks like an NDJSON event stream emitted by an
504/// agent CLI (opencode/claude/codex). Returns true when the first non-empty
505/// line parses as a JSON object containing a `type` field with one of the
506/// known event-type strings.
507///
508/// This guard prevents raw NDJSON from being interpreted as agent prose and
509/// leaking into notification summaries.
510fn looks_like_ndjson_event_stream(text: &str) -> bool {
511    let Some(first_line) = text.lines().map(str::trim).find(|l| !l.is_empty()) else {
512        return false;
513    };
514
515    if !first_line.starts_with('{') {
516        return false;
517    }
518
519    let Ok(value) = serde_json::from_str::<serde_json::Value>(first_line) else {
520        return false;
521    };
522
523    let Some(event_type) = value.get("type").and_then(|v| v.as_str()) else {
524        return false;
525    };
526
527    matches!(
528        event_type,
529        "step_start"
530            | "step_finish"
531            | "tool_use"
532            | "tool_result"
533            | "assistant"
534            | "system"
535            | "message"
536            | "text"
537    )
538}
539
540/// Build a synthetic agent response from plain text when structured parsing fails.
541///
542/// Returns `None` for empty/whitespace-only text so callers can preserve the
543/// original `InvalidResponse` behavior.
544pub fn synthesize_response_from_text(text: &str) -> Option<AgentResponse> {
545    // Returns true when `word` appears as a whole word in `text`
546    // (not preceded or followed by an ASCII alphanumeric character).
547    fn contains_word(text: &str, word: &str) -> bool {
548        let mut start = 0;
549        while let Some(pos) = text[start..].find(word) {
550            let abs = start + pos;
551            let before_ok = abs == 0 || !text.as_bytes()[abs - 1].is_ascii_alphanumeric();
552            let after_ok = abs + word.len() >= text.len()
553                || !text.as_bytes()[abs + word.len()].is_ascii_alphanumeric();
554            if before_ok && after_ok {
555                return true;
556            }
557            start = abs + 1;
558            if start >= text.len() {
559                break;
560            }
561        }
562        false
563    }
564
565    let trimmed = text.trim();
566    if trimmed.is_empty() {
567        return None;
568    }
569
570    // Detect CLI/arg-parser diagnostics and reject them. These indicate the agent
571    // process failed to start properly (e.g. invalid flag), not that the agent
572    // produced a free-form answer. Clap-based CLIs emit patterns like:
573    //   "error: unexpected argument '--flag' found"
574    //   "Usage: command [OPTIONS]"
575    //   "For more information, try '--help'"
576    //   "tip: to pass '...' as a value, use '-- ...'"
577    if is_cli_parser_diagnostic(trimmed) {
578        return None;
579    }
580
581    // Detect NDJSON event streams (opencode/claude/codex stdout) and reject
582    // them. Raw NDJSON masquerading as prose would otherwise leak into
583    // notification summaries — the "completed" substring inside tool state
584    // JSON triggers a false "done" classification and the first 500 bytes of
585    // NDJSON become the user-visible summary.
586    if looks_like_ndjson_event_stream(trimmed) {
587        return None;
588    }
589
590    let lower = trimmed.to_lowercase();
591    // Also accept plain-language confirmations of performed actions (issue/PR
592    // creation, comments, etc.) as a successful "done" signal. This prevents
593    // tasks from being retried when an agent reports success in free-form
594    // text instead of returning structured JSON.
595
596    // Negation phrases that override a "done/completed" match.
597    let looks_negative = [
598        "not done",
599        "not yet done",
600        "not complete",
601        "not yet complete",
602        "not completed",
603        "not yet completed",
604        "not committed",
605        "incomplete",
606        "undone",
607    ]
608    .iter()
609    .any(|needle| lower.contains(needle));
610
611    // Strong explicit completion phrases. These are high-confidence indicators
612    // that the agent performed an action (filed issues, created commits, etc.).
613    let explicit_done = [
614        "nothing to",
615        "nothing to do",
616        "nothing to execute",
617        "no positions",
618        "no open positions",
619        "no trades",
620        "no trade",
621        "no action needed",
622        "no changes to commit",
623        "completed",
624        // Action/issue completion phrases
625        "filed",
626        "filed issue",
627        "filed issues",
628        "created issue",
629        "created issues",
630        "opened issue",
631        "opened issues",
632        "issue created",
633        "issues created",
634        "issues filed",
635        "task created",
636        "posted comment",
637        "comment posted",
638        "changes committed",
639        "commit created",
640        "fixed.",
641        "has been fixed",
642        "the fix has been applied",
643        "the fix has already been applied",
644        // Agent completion phrases (regression: #1362/#1363)
645        "the fix is complete",
646        "fix is working",
647        "all tests pass",
648        "tests pass.",
649    ]
650    .iter()
651    .any(|needle| lower.contains(needle));
652
653    // Conservative sentence-level heuristics for single-word signals like "done".
654    // Accept "done" only when it appears in a short, self-contained sentence
655    // without hedging language ("let me", "checking", "will", etc.). This
656    // reduces false-positives from exploratory prose that mentions "done"
657    // as part of a planning or investigatory sentence.
658    let mut done_confident = false;
659    for sentence in trimmed
660        .split(['.', '!', '?', '\n'])
661        .map(str::trim)
662        .filter(|s| !s.is_empty())
663    {
664        let s_lower = sentence.to_lowercase();
665        // short sentence heuristic
666        let word_count = sentence.split_whitespace().count();
667        let hedging = [
668            "let",
669            "let me",
670            "check",
671            "checking",
672            "will",
673            "i'll",
674            "i will",
675            "trying",
676            "try",
677            "investigat",
678            "maybe",
679            "could",
680            "should",
681            "might",
682            "if ",
683            "plan",
684            "planning",
685        ];
686        let contains_hedge = hedging.iter().any(|h| s_lower.contains(h));
687
688        if contains_word(&s_lower, "done") && word_count <= 8 && !contains_hedge {
689            done_confident = true;
690            break;
691        }
692
693        // Commit/concrete action heuristics: require explicit commit language
694        // rather than opportunistic mentions. Examples: "I've committed the changes",
695        // "changes committed", or "commit created".
696        if s_lower.contains("committed") || s_lower.contains("commit created") {
697            // Accept only if sentence also suggests the changes were actually written
698            if s_lower.contains("changes")
699                || s_lower.contains("i've")
700                || s_lower.contains("i have")
701                || s_lower.contains("the commit")
702            {
703                done_confident = true;
704                break;
705            }
706        }
707
708        // Past-tense action verb at sentence start indicates a completed action
709        // (e.g. "Added detect_rate_limit patterns", "Fixed the nil-pointer bug").
710        // Accept only for short sentences without hedging language to avoid matching
711        // prose like "I added a note that this might fail later".
712        let past_tense_actions = [
713            "added ",
714            "fixed ",
715            "updated ",
716            "implemented ",
717            "created ",
718            "removed ",
719            "changed ",
720            "deleted ",
721            "applied ",
722            "resolved ",
723            "patched ",
724            "refactored ",
725            "merged ",
726            "pushed ",
727            "deployed ",
728        ];
729        if !contains_hedge
730            && word_count <= 12
731            && past_tense_actions.iter().any(|v| s_lower.starts_with(v))
732        {
733            done_confident = true;
734            break;
735        }
736    }
737
738    let looks_done = !looks_negative && (explicit_done || done_confident);
739
740    let looks_error = [
741        "error:",
742        "failed to",
743        "cannot",
744        "permission denied",
745        "unable to",
746    ]
747    .iter()
748    .any(|needle| lower.contains(needle));
749
750    let status = if looks_error {
751        "needs_review"
752    } else if looks_done {
753        "done"
754    } else if looks_negative {
755        // Agent explicitly stated the task is not complete — surface for human review.
756        "needs_review"
757    } else {
758        // Text is ambiguous: no error signal, no completion signal, no explicit negation.
759        // This happens when agents emit exploratory or startup text (e.g. "Let's go!",
760        // "I need to find where...") and exit without producing structured JSON.
761        // Returning None causes callers to treat this as an invalid response and reroute
762        // the task rather than falsely advancing it to needs_review / in_review.
763        return None;
764    };
765
766    let summary_end = truncate_at_char_boundary(trimmed, 500);
767    let summary = trimmed[..summary_end].to_string();
768    let error =
769        (status == "needs_review").then(|| "agent returned plain text instead of JSON".to_string());
770
771    // Extract structured fields from free-form text.
772    let files = extract_file_paths(trimmed);
773    let (accomplished, remaining) = extract_bullet_sections(trimmed);
774
775    Some(AgentResponse {
776        status: status.to_string(),
777        summary,
778        accomplished,
779        remaining,
780        files,
781        error,
782        input_tokens: None,
783        output_tokens: None,
784        learnings: vec![],
785        delegations: vec![],
786        screenshots: vec![],
787        screenshot_note: None,
788    })
789}
790
791/// Quote a string for safe insertion into a POSIX shell command.
792pub(crate) fn shell_single_quote(value: &str) -> String {
793    format!("'{}'", value.replace('\'', "'\\''"))
794}
795
796/// Find the largest byte index <= `max_bytes` that lies on a UTF-8 char
797/// boundary.  Used for safe string truncation in error messages.
798pub fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> usize {
799    if max_bytes >= s.len() {
800        return s.len();
801    }
802    // Walk backwards from max_bytes until we hit a char boundary
803    let mut end = max_bytes;
804    while end > 0 && !s.is_char_boundary(end) {
805        end -= 1;
806    }
807    end
808}
809
810/// One step of an agent's work, as `orch stream` shows it
811#[derive(Debug, Clone, PartialEq)]
812pub enum StreamEvent {
813    Started {
814        model: String,
815    },
816    Text(String),
817    Thinking(String),
818    /// `id` links the call to its result, empty when the agent has none
819    ToolCall {
820        id: String,
821        name: String,
822        input: serde_json::Value,
823    },
824    /// `name` is empty when only `id` names the call
825    ToolResult {
826        id: String,
827        name: String,
828        output: String,
829        is_error: bool,
830    },
831    Done(String),
832    Error(String),
833}
834
835/// String at a JSON pointer, empty when missing
836pub(crate) fn json_str<'a>(v: &'a serde_json::Value, pointer: &str) -> &'a str {
837    v.pointer(pointer)
838        .and_then(serde_json::Value::as_str)
839        .unwrap_or("")
840}
841
842/// Error text from any of the shapes agents use: `message`, `error`, `error.message`, `error.data.message`
843pub(crate) fn json_error_message(v: &serde_json::Value) -> String {
844    [
845        "/message",
846        "/error",
847        "/error/message",
848        "/error/data/message",
849    ]
850    .iter()
851    .find_map(|p| v.pointer(p).and_then(serde_json::Value::as_str))
852    .unwrap_or("unknown error")
853    .to_string()
854}
855
856/// Router stdout shape. Each runner reports its own
857#[derive(Debug, Clone, Copy, PartialEq, Eq)]
858pub enum RouterTranscript {
859    /// Claude Messages NDJSON (`type:result`)
860    Messages,
861    /// OpenCode NDJSON (`type:text`, `step_*`)
862    OpenCode,
863    /// Stdout is used as-is
864    Raw,
865}
866
867/// Per-agent runner trait.
868///
869/// Each agent implements this to handle its specific CLI invocation,
870/// output parsing, and error classification.
871pub trait AgentRunner: Send + Sync {
872    /// Agent name (e.g., "claude", "codex", "opencode"). Used in tests.
873    #[cfg(test)]
874    fn name(&self) -> &str;
875
876    /// Build the CLI command string for the legacy tmux runner.
877    ///
878    /// The returned string is embedded into a shell command that captures
879    /// output in the tmux session. The `permissions` struct carries unified
880    /// rules that each agent translates to its own CLI flags.
881    fn build_command(
882        &self,
883        model: Option<&str>,
884        timeout_cmd: &str,
885        sys_file: &str,
886        msg_file: &str,
887        permissions: &PermissionRules,
888    ) -> String;
889
890    /// Build a routed invocation with an optional native reasoning effort.
891    fn build_command_with_effort(
892        &self,
893        model: Option<&str>,
894        _effort: Option<&str>,
895        timeout_cmd: &str,
896        sys_file: &str,
897        msg_file: &str,
898        permissions: &PermissionRules,
899    ) -> String {
900        self.build_command(model, timeout_cmd, sys_file, msg_file, permissions)
901    }
902
903    /// Parse raw stdout into a ParsedResponse.
904    ///
905    /// Returns `Ok(ParsedResponse)` on success, `Err(AgentError)` if the
906    /// output indicates an error or cannot be parsed.
907    fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError>;
908
909    /// Extract the raw inner text from an agent output envelope, without
910    /// attempting to parse it as an `AgentResponse`.
911    ///
912    /// Use this in the review pipeline so that a `ReviewResponse` JSON can be
913    /// recovered even when the text doesn't match the task `AgentResponse` schema.
914    ///
915    /// - For Claude/Kimi/MiniMax: strips the `--output-format stream-json` NDJSON
916    ///   wrapper and returns the `"result"` field of the final `"type":"result"` line.
917    /// - For Codex: returns the text of the last `agent_message` item.
918    /// - For OpenCode: concatenates all `text` events.
919    /// - Default: returns `raw` unchanged (safe fallback for unknown agents).
920    ///
921    /// Returns `Err(AgentError)` only for terminal errors (rate limit, auth, etc.)
922    /// that should abort the review pipeline entirely.
923    fn extract_text(&self, raw: &str) -> Result<String, AgentError> {
924        Ok(raw.to_string())
925    }
926
927    /// Transcript steps for one parsed line of this agent's NDJSON output
928    fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent>;
929
930    /// Classify an error from exit code + stdout + stderr into an AgentError.
931    ///
932    /// Called when the agent process exits with a non-zero code, or when
933    /// parse_response fails to find a valid result.
934    fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError;
935
936    /// Classify error with elapsed session time (for accurate timeout reporting).
937    fn classify_error_with_elapsed(
938        &self,
939        exit_code: i32,
940        stdout: &str,
941        stderr: &str,
942        elapsed_secs: Option<u64>,
943    ) -> AgentError {
944        let mut err = self.classify_error(exit_code, stdout, stderr);
945        if let AgentError::Timeout { elapsed } = &mut err
946            && let Some(actual_elapsed) = elapsed_secs
947        {
948            *elapsed = Duration::from_secs(actual_elapsed);
949        }
950        err
951    }
952
953    /// Models available for this agent (for intra-agent failover).
954    fn available_models(&self) -> Vec<String> {
955        vec![]
956    }
957
958    /// Free/fallback models for last-resort failover.
959    fn free_models(&self) -> Vec<String> {
960        vec![]
961    }
962
963    /// Router stdout shape. The router matches on this instead of agent names
964    fn router_transcript(&self) -> RouterTranscript {
965        RouterTranscript::Raw
966    }
967
968    /// Build a minimal CLI command for LLM-based routing.
969    ///
970    /// The command should run the agent with `prompt` as the sole task and
971    /// return structured (JSON or NDJSON) output on stdout. Used by the router
972    /// to classify tasks without launching a full agent session.
973    fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command>;
974}
975
976/// Agents whose CLI takes `--session-id` for a new session and `--resume` to continue it
977pub fn supports_session(agent: &str) -> bool {
978    matches!(agent, "claude" | "kimi" | "minimax" | "grok")
979}
980
981/// Get the appropriate AgentRunner implementation for an agent name.
982/// Agents that are known to be claude-compatible (same NDJSON output format and flags)
983const CLAUDE_COMPATIBLE_AGENTS: &[&str] = &["claude", "kimi", "minimax", "olm", "glm"];
984
985/// Whether the agent runs Claude Code's CLI, and so honours a tool allowlist
986pub fn is_claude_compatible(agent_name: &str) -> bool {
987    CLAUDE_COMPATIBLE_AGENTS.contains(&agent_name)
988}
989
990pub fn get_runner(agent_name: &str) -> Box<dyn AgentRunner> {
991    match agent_name {
992        "claude" => Box::new(claude::ClaudeRunner::new(agent_name)),
993        "kimi" => Box::new(kimi::KimiClaudeRunner::new()),
994        "minimax" => Box::new(minimax::MiniMaxClaudeRunner::new(agent_name)),
995        "codex" => Box::new(codex::CodexRunner),
996        "opencode" => Box::new(opencode::OpenCodeRunner::new()),
997        "grok" => Box::new(grok::GrokRunner),
998        // Unknown agents fall back to Claude-compatible parsing
999        other => {
1000            // Only warn if the agent is not known to be claude-compatible
1001            if !CLAUDE_COMPATIBLE_AGENTS.contains(&other) {
1002                tracing::warn!(
1003                    agent = other,
1004                    "unknown agent, using claude-compatible runner"
1005                );
1006            }
1007            Box::new(claude::ClaudeRunner::new(other))
1008        }
1009    }
1010}
1011
1012/// Parse an NDJSON stream into a list of JSON values.
1013///
1014/// Shared by all agents that emit NDJSON output (Codex, OpenCode, etc.).
1015/// Lines that are empty or unparseable are silently skipped with a debug log.
1016///
1017/// For fragmented streams where complete JSON objects span multiple lines,
1018/// we also attempt to concatenate non-empty lines and parse them as a stream
1019/// of JSON objects to handle edge cases where models emit partial NDJSON.
1020pub(crate) fn parse_ndjson(raw: &str) -> Vec<serde_json::Value> {
1021    // Fast path: try parsing each line individually (handles most cases)
1022    let events: Vec<serde_json::Value> = raw
1023        .lines()
1024        .filter(|line| !line.trim().is_empty())
1025        .filter_map(|line| match serde_json::from_str(line) {
1026            Ok(val) => Some(val),
1027            Err(e) => {
1028                tracing::debug!(line, error = %e, "skipping unparseable NDJSON line");
1029                None
1030            }
1031        })
1032        .collect();
1033
1034    // If we got events, return them. Otherwise, try the accumulation fallback
1035    // for edge cases where models emit fragmented JSON (e.g., partial objects
1036    // that get split across lines, or streams with embedded newlines in strings).
1037    if !events.is_empty() {
1038        return events;
1039    }
1040
1041    // Fallback: accumulate all non-empty, non-comment lines and try to extract
1042    // JSON objects by scanning for balanced braces. This handles edge cases like:
1043    // - Closing fence inside JSON strings: {"text": "```json\n{\"status\": \"done\"}\n```"}
1044    // - Fragmented NDJSON where incomplete objects span multiple lines
1045    // - Model outputs with embedded newlines in text fields
1046    let acc: String = raw
1047        .lines()
1048        .filter(|line| {
1049            let t = line.trim();
1050            !t.is_empty() && !t.starts_with("//") && !t.starts_with('#')
1051        })
1052        .collect::<Vec<_>>()
1053        .join(" ");
1054
1055    if acc.is_empty() {
1056        return Vec::new();
1057    }
1058
1059    // Fallback: try to parse the accumulated text directly as a JSON value.
1060    // This handles multi-line JSON objects that don't fit on single lines.
1061    if let Ok(val) = serde_json::from_str::<serde_json::Value>(acc.trim()) {
1062        // Check if stripping ALL whitespace makes it a single JSON object with
1063        // the same content. If so, the input was plain multi-line JSON (not
1064        // fragmented NDJSON), and we should return empty to preserve original
1065        // behavior — callers then treat it as plain text.
1066        let stripped: String = acc.chars().filter(|c| !c.is_ascii_whitespace()).collect();
1067        if let Ok(stripped_val) = serde_json::from_str::<serde_json::Value>(&stripped) {
1068            // Only return empty if the stripped version parses identically,
1069            // meaning whitespace was insignificant. If they differ, whitespace
1070            // matters and this is likely fragmented input.
1071            if stripped_val == val {
1072                return Vec::new();
1073            }
1074        }
1075        return vec![val];
1076    }
1077
1078    // Direct parse failed — try to extract JSON objects by scanning for balanced
1079    // braces. This handles cases like embedded JSON within text:
1080    // `{"text": "```json\n{\"status\": \"done\"}\n```"}`
1081    extract_json_objects(&acc)
1082}
1083
1084/// Extract complete JSON objects from a string by scanning for balanced braces.
1085///
1086/// This is a fallback for fragmented NDJSON streams where complete objects
1087/// don't appear on single lines. Returns all parseable objects found.
1088fn extract_json_objects(text: &str) -> Vec<serde_json::Value> {
1089    let mut results = Vec::new();
1090    let mut start: Option<usize> = None;
1091    let mut depth: i32 = 0;
1092    let mut in_string = false;
1093    let mut escape = false;
1094
1095    for (idx, ch) in text.char_indices() {
1096        if let Some(start_idx) = start {
1097            if in_string {
1098                if escape {
1099                    escape = false;
1100                } else if ch == '\\' {
1101                    escape = true;
1102                } else if ch == '"' {
1103                    in_string = false;
1104                }
1105                continue;
1106            }
1107
1108            match ch {
1109                '"' => in_string = true,
1110                '{' => depth += 1,
1111                '}' => {
1112                    depth -= 1;
1113                    if depth == 0 {
1114                        let candidate = &text[start_idx..=idx];
1115                        if let Ok(val) = serde_json::from_str::<serde_json::Value>(candidate) {
1116                            results.push(val);
1117                        }
1118                        start = None;
1119                    }
1120                }
1121                _ => {}
1122            }
1123            continue;
1124        }
1125
1126        if ch == '{' {
1127            start = Some(idx);
1128            depth = 1;
1129            in_string = false;
1130            escape = false;
1131        }
1132    }
1133
1134    results
1135}
1136
1137#[cfg(test)]
1138mod tests {
1139    use tracing::Level;
1140    use tracing_subscriber::EnvFilter;
1141    use tracing_subscriber::fmt::writer::MakeWriter;
1142    use tracing_subscriber::util::SubscriberInitExt;
1143
1144    use std::io;
1145    use std::io::Write;
1146    use std::sync::Arc;
1147    use std::sync::Mutex;
1148
1149    use super::*;
1150
1151    #[test]
1152    fn get_runner_returns_correct_types() {
1153        assert_eq!(get_runner("claude").name(), "claude");
1154        assert_eq!(get_runner("kimi").name(), "kimi");
1155        assert_eq!(get_runner("minimax").name(), "minimax");
1156        assert_eq!(get_runner("codex").name(), "codex");
1157        assert_eq!(get_runner("opencode").name(), "opencode");
1158        assert_eq!(get_runner("grok").name(), "grok");
1159        assert_eq!(
1160            get_runner("claude").router_transcript(),
1161            RouterTranscript::Messages
1162        );
1163        assert_eq!(
1164            get_runner("kimi").router_transcript(),
1165            RouterTranscript::Messages
1166        );
1167        assert_eq!(
1168            get_runner("minimax").router_transcript(),
1169            RouterTranscript::Messages
1170        );
1171        assert_eq!(
1172            get_runner("grok").router_transcript(),
1173            RouterTranscript::Messages
1174        );
1175        assert_eq!(
1176            get_runner("glm").router_transcript(),
1177            RouterTranscript::Messages
1178        );
1179        assert_eq!(
1180            get_runner("olm").router_transcript(),
1181            RouterTranscript::Messages
1182        );
1183        assert_eq!(
1184            get_runner("opencode").router_transcript(),
1185            RouterTranscript::OpenCode
1186        );
1187        assert_eq!(
1188            get_runner("codex").router_transcript(),
1189            RouterTranscript::Raw
1190        );
1191        assert!(supports_session("grok"));
1192        assert!(!supports_session("codex"));
1193        // olm and glm are claude-compatible and should return correct name
1194        assert_eq!(get_runner("olm").name(), "olm");
1195        assert_eq!(get_runner("glm").name(), "glm");
1196        // Unknown falls back to claude-compatible
1197        assert_eq!(get_runner("unknown-agent").name(), "unknown-agent");
1198    }
1199
1200    /// Regression test: known claude-compatible agents (including glm) must not
1201    /// emit "unknown agent" warnings when get_runner() is called.
1202    #[test]
1203    fn get_runner_no_warning_for_claude_compatible_agents() {
1204        struct CaptureWriter(Arc<Mutex<Vec<u8>>>);
1205        impl Write for CaptureWriter {
1206            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1207                self.0.lock().unwrap().extend_from_slice(buf);
1208                Ok(buf.len())
1209            }
1210            fn flush(&mut self) -> io::Result<()> {
1211                Ok(())
1212            }
1213        }
1214        impl<'a> MakeWriter<'a> for CaptureWriter {
1215            type Writer = CaptureWriter;
1216            fn make_writer(&'a self) -> Self::Writer {
1217                CaptureWriter(Arc::clone(&self.0))
1218            }
1219        }
1220
1221        let output: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
1222        let output_clone = Arc::clone(&output);
1223
1224        tracing_subscriber::fmt()
1225            .with_env_filter(EnvFilter::from_default_env().add_directive(Level::WARN.into()))
1226            .with_writer(CaptureWriter(output_clone))
1227            .with_ansi(false)
1228            .finish()
1229            .init();
1230
1231        for agent in &["claude", "kimi", "minimax", "olm", "glm", "grok"] {
1232            get_runner(agent);
1233        }
1234
1235        let captured = {
1236            let guard = output.lock().unwrap();
1237            String::from_utf8_lossy(&guard).to_string()
1238        };
1239        assert!(
1240            !captured.contains("unknown agent"),
1241            "known claude-compatible agents must not emit 'unknown agent' warnings; got: {captured}"
1242        );
1243    }
1244
1245    #[test]
1246    fn agent_error_display() {
1247        let e = AgentError::RateLimit {
1248            message: "429 Too Many Requests".to_string(),
1249        };
1250        assert!(e.to_string().contains("rate limit"));
1251
1252        let e = AgentError::Timeout {
1253            elapsed: Duration::from_mins(30),
1254        };
1255        assert!(e.to_string().contains("1800"));
1256    }
1257
1258    #[test]
1259    fn pattern_detect_rate_limit() {
1260        assert!(patterns::detect_rate_limit("Error: rate limit exceeded").is_some());
1261        assert!(patterns::detect_rate_limit("HTTP 429 Too Many Requests").is_some());
1262        assert!(patterns::detect_rate_limit("You've hit your usage limit").is_some());
1263        assert!(
1264            patterns::detect_rate_limit(
1265                "You've hit your session limit · resets 10:30am (America/Sao_Paulo)"
1266            )
1267            .is_some()
1268        );
1269        assert!(patterns::detect_rate_limit(
1270            "Upstream error from Alibaba: Request rate increased too quickly. \
1271             To ensure system stability, please adjust your client logic to scale requests more smoothly over time."
1272        ).is_some());
1273        assert!(patterns::detect_rate_limit("all good").is_none());
1274    }
1275
1276    #[test]
1277    fn classify_from_text_detects_weekly_limit_as_rate_limit() {
1278        // Regression test for issue #3283: Claude "weekly limit" errors were
1279        // classified as `failed` instead of `rate_limit` because "weekly limit"
1280        // was not in the detect_rate_limit pattern list.
1281        let system_event = r#"{"type":"system","subtype":"error","error":{"type":"weekly_limit","message":"You've hit your weekly limit · resets Jun 9 at 1am (America/Sao_Paulo)"}}"#;
1282        let work_product = "{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"Working on the task...\"}]}}\n"
1283            .repeat(200);
1284        let text = format!("{system_event}\n{work_product}");
1285        assert!(
1286            text.len() > 3000,
1287            "test output must exceed tail window to be meaningful"
1288        );
1289        let err = patterns::classify_from_text(1, &text);
1290        assert!(
1291            matches!(err, AgentError::RateLimit { .. }),
1292            "weekly limit as early system event must be detected via head scan, got: {err:?}"
1293        );
1294        let msg = err.to_string();
1295        assert!(
1296            msg.contains("weekly limit"),
1297            "error message should reference weekly limit, got: {msg}"
1298        );
1299    }
1300
1301    #[test]
1302    fn detect_rate_limit_github_copilot_monthly_quota() {
1303        // Regression test for issue #3302: "You have exceeded your monthly quota"
1304        // was not matched because detect_rate_limit only checked "quota exceeded"
1305        // (reversed word order), causing 4 immediate retries with no cooldown.
1306        let err = patterns::detect_rate_limit("You have exceeded your monthly quota");
1307        assert!(
1308            matches!(err, Some(AgentError::RateLimit { .. })),
1309            "monthly quota exhaustion must be detected as rate limit, got: {err:?}"
1310        );
1311    }
1312
1313    #[test]
1314    fn detect_rate_limit_nvidia_resourceexhausted() {
1315        // Regression test for issue #3361: Nvidia "ResourceExhausted: Worker local total
1316        // request limit reached" was classified as generic `failed` instead of `rate_limit`,
1317        // bypassing the cooldown path and weakening routing health signals.
1318        let opencode_error = r#"opencode agent error: agent failed: "Upstream error from Nvidia: ResourceExhausted: Worker local total request limit reached (42/32)""#;
1319        let err = patterns::detect_rate_limit(opencode_error);
1320        assert!(
1321            matches!(err, Some(AgentError::RateLimit { .. })),
1322            "Nvidia ResourceExhausted must be detected as rate limit, got: {err:?}"
1323        );
1324
1325        // Both sub-patterns must match independently.
1326        assert!(
1327            patterns::detect_rate_limit("ResourceExhausted: some capacity error").is_some(),
1328            "bare ResourceExhausted must match"
1329        );
1330        assert!(
1331            patterns::detect_rate_limit("Worker local total request limit reached (10/8)")
1332                .is_some(),
1333            "worker local total request limit reached must match"
1334        );
1335
1336        // classify_from_text must also route this to RateLimit (exercises the tail-scan path).
1337        let err = patterns::classify_from_text(1, opencode_error);
1338        assert!(
1339            matches!(err, AgentError::RateLimit { .. }),
1340            "classify_from_text must produce RateLimit for Nvidia ResourceExhausted, got: {err:?}"
1341        );
1342    }
1343
1344    #[test]
1345    fn detect_rate_limit_message_contains_context_not_tail() {
1346        // Simulate a long claude NDJSON output where the rate limit message is in
1347        // the middle and usage stats JSON is at the tail.
1348        let padding = "x".repeat(5000);
1349        let text = format!(
1350            "{padding}you've reached your usage limit for this billing cycle{padding}\
1351             {{\"web_fetch_requests\":0,\"service_tier\":\"standard\"}}"
1352        );
1353        let err = patterns::detect_rate_limit(&text).expect("should detect");
1354        let msg = err.to_string();
1355        assert!(
1356            msg.contains("usage limit"),
1357            "message should contain the actual error, got: {msg}"
1358        );
1359        assert!(
1360            !msg.contains("web_fetch_requests"),
1361            "message should not be the tail JSON, got: {msg}"
1362        );
1363    }
1364
1365    #[test]
1366    fn pattern_detect_rate_limit_529_not_bare() {
1367        // Bare "529" in various contexts should NOT trigger rate limit detection.
1368        // These are false positive cases we want to avoid.
1369        assert!(
1370            patterns::detect_rate_limit("error on line 529").is_none(),
1371            "bare line number 529 should not match"
1372        );
1373        assert!(
1374            patterns::detect_rate_limit("file size 529 bytes").is_none(),
1375            "bare file size 529 should not match"
1376        );
1377        assert!(
1378            patterns::detect_rate_limit("port :5290 in config").is_none(),
1379            "port number containing 529 should not match"
1380        );
1381        assert!(
1382            patterns::detect_rate_limit("timeout after 5290ms").is_none(),
1383            "duration containing 529 should not match"
1384        );
1385        // But HTTP 529 status codes SHOULD match.
1386        assert!(
1387            patterns::detect_rate_limit("HTTP 529 Service Unavailable").is_some(),
1388            "HTTP 529 status should match"
1389        );
1390        assert!(
1391            patterns::detect_rate_limit("http 529").is_some(),
1392            "http 529 should match"
1393        );
1394        assert!(
1395            patterns::detect_rate_limit("529 service unavailable").is_some(),
1396            "529 service unavailable should match"
1397        );
1398        assert!(
1399            patterns::detect_rate_limit("status: 529").is_some(),
1400            "status: 529 should match"
1401        );
1402    }
1403
1404    #[test]
1405    fn pattern_detect_auth() {
1406        assert!(patterns::detect_auth_error("401 Unauthorized").is_some());
1407        assert!(patterns::detect_auth_error("HTTP 401").is_some());
1408        assert!(patterns::detect_auth_error("error: 401").is_some());
1409        assert!(patterns::detect_auth_error("403 Forbidden").is_some());
1410        assert!(patterns::detect_auth_error("HTTP 403").is_some());
1411        assert!(patterns::detect_auth_error("HTTP 407 Authentication Required").is_some());
1412        assert!(patterns::detect_auth_error("407 Proxy Authentication Required").is_some());
1413        assert!(patterns::detect_auth_error("invalid api key").is_some());
1414        assert!(patterns::detect_auth_error("billing expired").is_some());
1415        assert!(patterns::detect_auth_error("task done").is_none());
1416        // Bare numbers in JSON must NOT trigger auth classification.
1417        assert!(patterns::detect_auth_error("duration_api_ms 4010292").is_none());
1418        assert!(
1419            patterns::detect_auth_error(
1420                "API Error: Unable to connect to API (ConnectionRefused) duration_api_ms 4010292"
1421            )
1422            .is_none()
1423        );
1424        // JSON field with colon: "duration_api_ms": 4010292 — contains ": 401" as substring.
1425        assert!(patterns::detect_auth_error(r#""duration_api_ms": 4010292"#).is_none());
1426        assert!(
1427            patterns::detect_auth_error(
1428                r#"{"error":"ConnectionRefused","duration_api_ms": 4010292}"#
1429            )
1430            .is_none()
1431        );
1432        // ": 401" at end-of-string or followed by non-digit must still match.
1433        assert!(patterns::detect_auth_error("status: 401").is_some());
1434        assert!(patterns::detect_auth_error("error: 403").is_some());
1435    }
1436
1437    #[test]
1438    fn pattern_detect_auth_insufficient_balance() {
1439        // Regression test for issue #3642: "insufficient balance" (and by extension
1440        // "402 Payment Required: insufficient balance") must be detected as an auth
1441        // error so it routes through the credit exhaustion path, not the generic 5-min
1442        // backoff. This ensures the #3642 cooldown behavior is properly triggered.
1443        assert!(
1444            patterns::detect_auth_error("402 Payment Required: insufficient balance").is_some(),
1445            "insufficient balance must be detected as auth error"
1446        );
1447        assert!(
1448            patterns::detect_auth_error("insufficient balance").is_some(),
1449            "bare insufficient balance must be detected as auth error"
1450        );
1451        // The stored message should contain the matched pattern.
1452        let err = patterns::detect_auth_error("402 Payment Required: insufficient balance")
1453            .expect("should detect auth error");
1454        let AgentError::Auth { message } = err else {
1455            panic!("expected Auth, got {err:?}");
1456        };
1457        assert!(
1458            message.to_lowercase().contains("insufficient balance"),
1459            "stored message should contain the matched pattern, got: {message}"
1460        );
1461        // The message should be the line containing the auth error, not the tail.
1462        assert!(
1463            message.lines().count() <= 2,
1464            "message should be the auth line, not the full tail: {}",
1465            message.len()
1466        );
1467    }
1468
1469    #[test]
1470    fn auth_error_message_contains_match_not_tail() {
1471        // Simulate real agent output: auth error appears early, NDJSON session
1472        // metadata at the end. Stored message must be the error line, not the
1473        // trailing JSON that agents emit at exit.
1474        let mut text = "some output\nunauthorized: your api key has expired\nx".repeat(400);
1475        text.push_str(r#","outputTokens":744,"cacheReadInputTokens":344785,"uuid":"86d13b1f-..."#);
1476        let err = patterns::detect_auth_error(&text).expect("should detect auth error");
1477        let AgentError::Auth { message } = err else {
1478            panic!("expected Auth, got {err:?}");
1479        };
1480        assert!(
1481            message.to_lowercase().contains("unauthorized"),
1482            "stored message should contain the matched pattern, got: {message}"
1483        );
1484        assert!(
1485            !message.contains("outputTokens"),
1486            "stored message must not be the trailing NDJSON, got: {message}"
1487        );
1488        // The message should be the line containing the auth error, not the tail.
1489        assert!(
1490            message.lines().count() <= 2,
1491            "message should be the auth line, not the full tail: {}",
1492            message.len()
1493        );
1494    }
1495
1496    #[test]
1497    fn pattern_detect_network_error() {
1498        assert!(patterns::detect_network_error("connection refused").is_some());
1499        assert!(patterns::detect_network_error("ConnectionRefused").is_some());
1500        assert!(patterns::detect_network_error("Unable to connect to API").is_some());
1501        assert!(patterns::detect_network_error("ECONNREFUSED").is_some());
1502        assert!(patterns::detect_network_error("network unreachable").is_some());
1503        assert!(patterns::detect_network_error("Upstream idle timeout exceeded").is_some());
1504        assert!(patterns::detect_network_error("upstream idle timeout").is_some());
1505        assert!(patterns::detect_network_error("Streaming response failed").is_some());
1506        assert!(patterns::detect_network_error("Upstream request failed").is_some());
1507        assert!(patterns::detect_network_error("all systems operational").is_none());
1508    }
1509
1510    #[test]
1511    fn network_error_message_contains_match_not_tail() {
1512        // Simulate real agent output: error appears early, unrelated stats JSON at the end.
1513        let prefix = "connection refused connecting to api.anthropic.com:443 ";
1514        let mut suffix = "x".repeat(2000);
1515        suffix.push_str(r#"":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0}"#);
1516        let text = format!("{prefix}{suffix}");
1517
1518        let err = patterns::detect_network_error(&text).expect("should detect network error");
1519        let AgentError::NetworkError { message } = err else {
1520            panic!("expected NetworkError, got {err:?}");
1521        };
1522        assert!(
1523            message.to_lowercase().contains("connection refused"),
1524            "stored message should contain the matched pattern, got: {message}"
1525        );
1526        assert!(
1527            !message.contains("web_fetch_requests"),
1528            "stored message must not be the unrelated stats tail, got: {message}"
1529        );
1530    }
1531
1532    #[test]
1533    fn pattern_detect_context_overflow() {
1534        assert!(patterns::detect_context_overflow("context_length_exceeded").is_some());
1535        assert!(patterns::detect_context_overflow("too many tokens in prompt").is_some());
1536        assert!(patterns::detect_context_overflow("success").is_none());
1537    }
1538
1539    #[test]
1540    fn pattern_detect_worktree_missing() {
1541        assert!(
1542            patterns::detect_worktree_missing("worktree directory does not exist: /tmp/wt")
1543                .is_some()
1544        );
1545        assert!(patterns::detect_worktree_missing("all good").is_none());
1546    }
1547
1548    #[test]
1549    fn pattern_detect_missing_tool() {
1550        assert!(patterns::detect_missing_tool("bun: command not found").is_some());
1551        assert!(patterns::detect_missing_tool("env: anchor: no such file").is_some());
1552        assert!(patterns::detect_missing_tool("everything works").is_none());
1553    }
1554
1555    #[test]
1556    fn pattern_detect_permission_denied() {
1557        assert!(patterns::detect_permission_denied("permission denied: /etc/hosts").is_some());
1558        assert!(patterns::detect_permission_denied("sandbox violation detected").is_some());
1559        assert!(patterns::detect_permission_denied("disallowed tool: Bash(rm *)").is_some());
1560        assert!(patterns::detect_permission_denied("task completed").is_none());
1561    }
1562
1563    #[test]
1564    fn pattern_detect_waiting_for_input() {
1565        assert!(patterns::detect_waiting_for_input("Enter passphrase for key").is_some());
1566        assert!(patterns::detect_waiting_for_input("1Password CLI required").is_some());
1567        assert!(
1568            patterns::detect_waiting_for_input("SSH authentication required for deploy key")
1569                .is_some()
1570        );
1571        assert!(
1572            patterns::detect_waiting_for_input("HTTP 407 Proxy Authentication Required").is_none()
1573        );
1574        assert!(patterns::detect_waiting_for_input("done").is_none());
1575    }
1576
1577    #[test]
1578    fn pattern_detect_stale_session() {
1579        // Exact error message from Claude
1580        let err = patterns::detect_stale_session(
1581            "No conversation found with session ID: 2be572c4-57bb-4f86-bc03-b593c329177c",
1582        );
1583        assert!(err.is_some(), "should detect stale session");
1584        if let Some(AgentError::StaleSession { session_id }) = err {
1585            assert_eq!(session_id, "2be572c4-57bb-4f86-bc03-b593c329177c");
1586        }
1587
1588        // Case-insensitive
1589        let err = patterns::detect_stale_session("no conversation found with session id: abc-123");
1590        assert!(err.is_some(), "should detect lowercase variant");
1591
1592        // Non-matching text
1593        assert!(patterns::detect_stale_session("all good").is_none());
1594        assert!(patterns::detect_stale_session("conversation started").is_none());
1595
1596        // Multi-byte UTF-8 characters before the match must not panic.
1597        // German ß lowercases to "ss" (1 byte → 2 bytes), so using a byte
1598        // offset from `lower` directly into `text` would be wrong.
1599        let multibyte = "Straße: No conversation found with session ID: dead-beef";
1600        let err = patterns::detect_stale_session(multibyte);
1601        assert!(
1602            err.is_some(),
1603            "should detect stale session after multi-byte chars"
1604        );
1605        if let Some(AgentError::StaleSession { session_id }) = err {
1606            assert_eq!(session_id, "dead-beef");
1607        }
1608    }
1609
1610    #[test]
1611    fn stale_session_display() {
1612        let e = AgentError::StaleSession {
1613            session_id: "abc-123".to_string(),
1614        };
1615        assert!(e.to_string().contains("stale session"));
1616        assert!(e.to_string().contains("abc-123"));
1617    }
1618
1619    #[test]
1620    fn classify_from_text_timeout() {
1621        let err = patterns::classify_from_text(124, "");
1622        assert!(matches!(err, AgentError::Timeout { .. }));
1623    }
1624
1625    #[test]
1626    fn classify_from_text_missing_tool_before_rate_limit() {
1627        // Missing tool takes priority over rate limit patterns
1628        let err = patterns::classify_from_text(1, "bun: command not found rate limit");
1629        assert!(matches!(err, AgentError::MissingTool { .. }));
1630    }
1631
1632    #[test]
1633    fn classify_from_text_worktree_missing() {
1634        let err = patterns::classify_from_text(1, "worktree directory does not exist: /tmp/wt");
1635        assert!(matches!(err, AgentError::AgentFailed { .. }));
1636    }
1637
1638    #[test]
1639    fn classify_from_text_model_not_found_backtick() {
1640        // Issue #3604: plain-text "model not found" errors (no structured
1641        // NDJSON event) must classify as ModelUnavailable, not fall through to
1642        // Unknown, so the agent-wide cooldown is not bumped for a bad model name.
1643        let text = "codex failed: model unavailable (gpt-5.5): Reconnecting... 2/5 \
1644            (unexpected status 404 Not Found: The model `gpt-5.5` does not exist \
1645            or you do not have access to it.)";
1646        let err = patterns::classify_from_text(1, text);
1647        match err {
1648            AgentError::ModelUnavailable { model, .. } => assert_eq!(model, "gpt-5.5"),
1649            other => panic!("expected ModelUnavailable, got: {other:?}"),
1650        }
1651    }
1652
1653    #[test]
1654    fn classify_from_text_model_metadata_not_found() {
1655        let text = "Model metadata for `gpt-5.4` not found. Defaulting to fallback \
1656            metadata; this can degrade performance and cause issues.";
1657        let err = patterns::classify_from_text(1, text);
1658        match err {
1659            AgentError::ModelUnavailable { model, .. } => assert_eq!(model, "gpt-5.4"),
1660            other => panic!("expected ModelUnavailable, got: {other:?}"),
1661        }
1662    }
1663
1664    #[test]
1665    fn classify_from_text_no_false_positive_from_work_product() {
1666        // Regression test for issue #1292: agent output containing rate-limit
1667        // keywords in code/diffs must not be misclassified as a rate limit error.
1668        let work_product = "Added `is_copilot_model(model) -> bool` helper\n\
1669             - Added copilot quota patterns to `parse_retry_at`\n\
1670             fn detect_rate_limit(text: &str) -> Option<AgentError> {\n\
1671             quota exceeded handling for billing cycle\n"
1672            .repeat(50); // ~200 lines of work product — well over 3000 chars
1673        let actual_error = "\nerror: command not found: cargo\n";
1674        let text = format!("{work_product}{actual_error}");
1675        let err = patterns::classify_from_text(1, &text);
1676        assert!(
1677            !matches!(err, AgentError::RateLimit { .. }),
1678            "work product keywords must not trigger rate limit, got: {err:?}"
1679        );
1680    }
1681
1682    #[test]
1683    fn classify_from_text_still_detects_real_rate_limit_at_tail() {
1684        // A real rate-limit error printed at the end of the output must still
1685        // be detected, even if work product precedes it.
1686        let padding = "normal agent work output ".repeat(100);
1687        let text = format!("{padding}\nError: rate limit exceeded (429 Too Many Requests)\n");
1688        let err = patterns::classify_from_text(1, &text);
1689        assert!(
1690            matches!(err, AgentError::RateLimit { .. }),
1691            "real rate limit at tail must be detected, got: {err:?}"
1692        );
1693    }
1694
1695    #[test]
1696    fn classify_from_text_ignores_markdown_rate_limit_table_at_tail() {
1697        let padding = "normal agent work output ".repeat(250);
1698        let text = format!(
1699            "{padding}\n+| agent | model | outcome | count |\n+| codex | gpt-5.4 | failed | 1 |\n+| kimi | opus | rate_limit | 1 |\n"
1700        );
1701        let err = patterns::classify_from_text(1, &text);
1702        assert!(
1703            !matches!(err, AgentError::RateLimit { .. }),
1704            "markdown table cell must not trigger rate limit, got: {err:?}"
1705        );
1706    }
1707
1708    #[test]
1709    fn classify_from_text_rate_limit_non_ascii_prefix_does_not_panic() {
1710        // Regression test: non-ASCII characters before `rate_limit` that change
1711        // byte length when lowercased (e.g. İ 2→3 bytes, fl 3→2 bytes) must not
1712        // cause is_word_boundary to index text at an invalid byte offset.
1713        let text = "Aflαβrate_limit error: too many requests";
1714        let err = patterns::classify_from_text(1, text);
1715        assert!(
1716            matches!(err, AgentError::RateLimit { .. }),
1717            "real rate_limit should still be detected with non-ASCII prefix, got: {err:?}"
1718        );
1719    }
1720
1721    #[test]
1722    fn classify_from_text_detects_session_limit_as_early_system_event() {
1723        // Regression test for issue #3272: Claude session limit errors appear as
1724        // `type:system` NDJSON events early in the stream, not as `type:result`
1725        // lines. When the agent produces significant output after the error, the
1726        // system event is pushed out of the tail window and missed by tail-only
1727        // scanning. The head scan must catch it.
1728        let system_event = r#"{"type":"system","subtype":"error","error":{"type":"session_limit","message":"You've hit your session limit · resets 4:10am (America/Sao_Paulo)"}}"#;
1729        // Generate enough work product (>3000 bytes) to push the system event
1730        // out of the tail window.
1731        let work_product = "{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"Working on the task...\"}]}}\n"
1732            .repeat(200);
1733        let text = format!("{system_event}\n{work_product}");
1734        // Verify the output is large enough that the event is not in the tail.
1735        assert!(
1736            text.len() > 3000,
1737            "test output must exceed tail window to be meaningful"
1738        );
1739        let err = patterns::classify_from_text(1, &text);
1740        assert!(
1741            matches!(err, AgentError::RateLimit { .. }),
1742            "session limit as early system event must be detected via head scan, got: {err:?}"
1743        );
1744        // The message should contain the actual error, not unrelated tail content.
1745        let msg = err.to_string();
1746        assert!(
1747            msg.contains("session limit"),
1748            "error message should contain the rate limit reason, got: {msg}"
1749        );
1750    }
1751
1752    #[test]
1753    fn classify_from_text_no_false_positive_auth_from_work_product() {
1754        // Regression test for issue #2126: auth keywords in agent work product
1755        // must not trigger auth classification when the real failure is
1756        // unrelated and appears at the end of the output.
1757        let work_product = "if response.status == 401 { return Err(\"unauthorized\") }\n\
1758             // handle 403 forbidden errors\n\
1759             // billing checks happen elsewhere\n"
1760            .repeat(80);
1761        let actual_error = "\nerror: command not found: cargo\n";
1762        let text = format!("{work_product}{actual_error}");
1763        let err = patterns::classify_from_text(1, &text);
1764        assert!(
1765            !matches!(err, AgentError::Auth { .. }),
1766            "work product auth keywords must not trigger auth classification, got: {err:?}"
1767        );
1768        assert!(
1769            matches!(err, AgentError::MissingTool { .. }),
1770            "the real tail error should still win, got: {err:?}"
1771        );
1772    }
1773
1774    #[test]
1775    fn classify_from_text_still_detects_real_auth_at_tail() {
1776        let padding = "normal agent work output ".repeat(100);
1777        let text = format!("{padding}\nHTTP 401 Unauthorized\n");
1778        let err = patterns::classify_from_text(1, &text);
1779        assert!(
1780            matches!(err, AgentError::Auth { .. }),
1781            "real auth error at tail must be detected, got: {err:?}"
1782        );
1783    }
1784
1785    #[test]
1786    fn classify_from_text_no_false_positive_context_overflow_from_work_product() {
1787        // Regression test for issue #2205: context overflow keywords in agent
1788        // work product must not trigger ContextOverflow when the real failure is
1789        // unrelated and appears at the end of the output.
1790        let work_product = "const MAX_TOKEN_LIMIT = 10000;\n\
1791             // Ensure we don't exceed the token limit per request\n\
1792             fn check_token_limit(tokens: usize) { ... }\n\
1793             if total_tokens > MAX_TOKEN_LIMIT { ... }\n\
1794             // Note: too many tokens in the prompt causes context_length_exceeded\n"
1795            .repeat(80);
1796        let actual_error = "\nerror: command not found: cargo\n";
1797        let text = format!("{work_product}{actual_error}");
1798        let err = patterns::classify_from_text(1, &text);
1799        assert!(
1800            !matches!(err, AgentError::ContextOverflow { .. }),
1801            "work product context keywords must not trigger ContextOverflow, got: {err:?}"
1802        );
1803        assert!(
1804            matches!(err, AgentError::MissingTool { .. }),
1805            "the real tail error should still win, got: {err:?}"
1806        );
1807    }
1808
1809    #[test]
1810    fn classify_from_text_still_detects_real_context_overflow_at_tail() {
1811        let padding = "normal agent work output ".repeat(100);
1812        let text = format!("{padding}\nError: context_length_exceeded\n");
1813        let err = patterns::classify_from_text(1, &text);
1814        assert!(
1815            matches!(err, AgentError::ContextOverflow { .. }),
1816            "real context overflow at tail must be detected, got: {err:?}"
1817        );
1818    }
1819
1820    #[test]
1821    fn classify_from_text_no_false_positive_permission_denied_from_work_product() {
1822        // Regression test for issue #2205: permission-related keywords in agent
1823        // work product must not trigger PermissionDenied when the real failure
1824        // is unrelated and appears at the end of the output.
1825        let work_product = "match fs::metadata(path) {\n\
1826             Err(ref e) if e.kind() == ErrorKind::PermissionDenied => {\n\
1827                 bail!(\"access denied: {path}\");\n\
1828             }\n\
1829             // Check if directory is writable\n\
1830             if !path.is_writable() { ... }\n\
1831             }\n"
1832        .repeat(80);
1833        let actual_error = "\nerror: command not found: cargo\n";
1834        let text = format!("{work_product}{actual_error}");
1835        let err = patterns::classify_from_text(1, &text);
1836        assert!(
1837            !matches!(err, AgentError::PermissionDenied { .. }),
1838            "work product permission keywords must not trigger PermissionDenied, got: {err:?}"
1839        );
1840        assert!(
1841            matches!(err, AgentError::MissingTool { .. }),
1842            "the real tail error should still win, got: {err:?}"
1843        );
1844    }
1845
1846    #[test]
1847    fn classify_from_text_still_detects_real_permission_denied_at_tail() {
1848        let padding = "normal agent work output ".repeat(100);
1849        let text = format!("{padding}\npermission denied: /etc/hosts\n");
1850        let err = patterns::classify_from_text(1, &text);
1851        assert!(
1852            matches!(err, AgentError::PermissionDenied { .. }),
1853            "real permission denied at tail must be detected, got: {err:?}"
1854        );
1855    }
1856
1857    #[test]
1858    fn classify_from_text_no_false_positive_waiting_for_input_from_work_product() {
1859        // Regression test for issue #2205: input-request keywords in agent work
1860        // product must not trigger WaitingForInput when the real failure is
1861        // unrelated and appears at the end of the output.
1862        let work_product = "// Handle password prompts gracefully\n\
1863             if prompt.contains(\"password:\") {\n\
1864                 log::warn!(\"Password prompt detected — skipping interactive step\");\n\
1865             }\n\
1866             // SSH agent will ask for the deploy key passphrase\n\
1867             fn handle_ssh_passphrase() { ... }\n\
1868             )\n"
1869        .repeat(80);
1870        let actual_error = "\nerror: command not found: cargo\n";
1871        let text = format!("{work_product}{actual_error}");
1872        let err = patterns::classify_from_text(1, &text);
1873        assert!(
1874            !matches!(err, AgentError::WaitingForInput { .. }),
1875            "work product input keywords must not trigger WaitingForInput, got: {err:?}"
1876        );
1877        assert!(
1878            matches!(err, AgentError::MissingTool { .. }),
1879            "the real tail error should still win, got: {err:?}"
1880        );
1881    }
1882
1883    #[test]
1884    fn classify_from_text_still_detects_real_waiting_for_input_at_tail() {
1885        let padding = "normal agent work output ".repeat(100);
1886        let text = format!("{padding}\nEnter passphrase for key:\n");
1887        let err = patterns::classify_from_text(1, &text);
1888        assert!(
1889            matches!(err, AgentError::WaitingForInput { .. }),
1890            "real waiting for input at tail must be detected, got: {err:?}"
1891        );
1892    }
1893
1894    #[test]
1895    fn classify_from_text_prefers_auth_over_permission_denied() {
1896        let err = patterns::classify_from_text(1, "HTTP 403 access denied: invalid token");
1897        assert!(
1898            matches!(err, AgentError::Auth { .. }),
1899            "auth errors must outrank permission denied, got: {err:?}"
1900        );
1901    }
1902
1903    #[test]
1904    fn classify_from_text_prefers_auth_over_waiting_for_input() {
1905        let err = patterns::classify_from_text(1, "HTTP 407 Proxy Authentication Required");
1906        assert!(
1907            matches!(err, AgentError::Auth { .. }),
1908            "HTTP auth failures must not be treated as waiting for input, got: {err:?}"
1909        );
1910    }
1911
1912    #[test]
1913    fn classify_from_text_detects_stale_session() {
1914        // Regression test for issue #1800: classify_from_text must call
1915        // detect_stale_session to catch "No conversation found with session ID"
1916        // errors. Without this, the error would be misclassified as Unknown and
1917        // the control.rs recovery code would not trigger.
1918        let text = "No conversation found with session ID: 2be572c4-57bb-4f86-bc03-b593c329177c";
1919        let err = patterns::classify_from_text(1, text);
1920        assert!(
1921            matches!(err, AgentError::StaleSession { .. }),
1922            "stale session must be detected via classify_from_text, got: {err:?}"
1923        );
1924        // Verify the Display format matches what control.rs expects
1925        assert!(
1926            err.to_string().contains("stale session"),
1927            "error display must contain 'stale session' for recovery code to trigger"
1928        );
1929    }
1930
1931    #[test]
1932    fn classify_from_text_detects_socket_closed() {
1933        // Regression test for issue #3045: "socket connection was closed" must be
1934        // classified as NetworkError, not Unknown.
1935        let text = "API Error: The socket connection was closed unexpectedly. \
1936             For more information, pass `verbose: true` in the second argument to fetch()";
1937        let err = patterns::classify_from_text(1, text);
1938        assert!(
1939            matches!(err, AgentError::NetworkError { .. }),
1940            "socket closed must be NetworkError, got: {err:?}"
1941        );
1942    }
1943
1944    #[test]
1945    fn classify_from_text_detects_socket_hang_up() {
1946        let err = patterns::classify_from_text(1, "Error: socket hang up");
1947        assert!(
1948            matches!(err, AgentError::NetworkError { .. }),
1949            "socket hang up must be NetworkError, got: {err:?}"
1950        );
1951    }
1952
1953    #[test]
1954    fn classify_from_text_detects_fetch_failed() {
1955        let err = patterns::classify_from_text(1, "TypeError: fetch failed");
1956        assert!(
1957            matches!(err, AgentError::NetworkError { .. }),
1958            "fetch failed must be NetworkError, got: {err:?}"
1959        );
1960    }
1961
1962    #[test]
1963    fn classify_from_text_detects_econnreset() {
1964        let err = patterns::classify_from_text(1, "read ECONNRESET");
1965        assert!(
1966            matches!(err, AgentError::NetworkError { .. }),
1967            "ECONNRESET must be NetworkError, got: {err:?}"
1968        );
1969    }
1970
1971    #[test]
1972    fn classify_from_text_detects_stalled_mid_stream() {
1973        // Regression test for issue #3541: kimi's "Response stalled mid-stream" must be
1974        // classified as NetworkError, not Unknown/AgentFailed.
1975        let err = patterns::classify_from_text(
1976            1,
1977            "API Error: Response stalled mid-stream. The response above may be incomplete.",
1978        );
1979        assert!(
1980            matches!(err, AgentError::NetworkError { .. }),
1981            "stalled mid-stream must be NetworkError, got: {err:?}"
1982        );
1983    }
1984
1985    #[test]
1986    fn classify_from_text_detects_connection_closed_mid_response() {
1987        // Regression test for issue #3541: claude's "Connection closed mid-response" must be
1988        // classified as NetworkError, not Unknown/AgentFailed.
1989        let err = patterns::classify_from_text(
1990            1,
1991            "API Error: Connection closed mid-response. The response above may be incomplete.",
1992        );
1993        assert!(
1994            matches!(err, AgentError::NetworkError { .. }),
1995            "connection closed mid-response must be NetworkError, got: {err:?}"
1996        );
1997    }
1998
1999    #[test]
2000    fn synthesize_response_marks_done_for_plain_text_no_op() {
2001        let response = synthesize_response_from_text(
2002            "No open positions, no trade executions, no conditions change. Full cash, holding.",
2003        )
2004        .unwrap();
2005
2006        assert_eq!(response.status, "done");
2007        assert_eq!(
2008            response.summary,
2009            "No open positions, no trade executions, no conditions change. Full cash, holding."
2010        );
2011        assert!(response.error.is_none());
2012    }
2013
2014    #[test]
2015    fn synthesize_response_marks_needs_review_for_plain_text_error() {
2016        let response =
2017            synthesize_response_from_text("Failed to update branch: permission denied").unwrap();
2018
2019        assert_eq!(response.status, "needs_review");
2020        assert_eq!(
2021            response.error.as_deref(),
2022            Some("agent returned plain text instead of JSON")
2023        );
2024    }
2025
2026    #[test]
2027    fn synthesize_response_rejects_empty_text() {
2028        assert!(synthesize_response_from_text("   \n\t  ").is_none());
2029    }
2030
2031    /// Regression: raw NDJSON event streams (opencode/claude/codex stdout)
2032    /// must be rejected by the synthesizer. Without the guard, the
2033    /// "completed" substring inside tool state JSON triggers a false "done"
2034    /// classification and 500 bytes of raw NDJSON leak into the
2035    /// notification summary.
2036    #[test]
2037    fn synthesize_response_rejects_ndjson_event_stream() {
2038        let ndjson = r#"{"type":"step_start","timestamp":1,"part":{"type":"step-start"}}
2039{"type":"tool_use","timestamp":2,"name":"bash","input":{"cmd":"echo completed"}}
2040{"type":"step_finish","timestamp":3,"part":{"type":"step-finish","reason":"stop"}}"#;
2041        assert!(
2042            synthesize_response_from_text(ndjson).is_none(),
2043            "raw NDJSON must not be interpreted as agent prose"
2044        );
2045
2046        let single = r#"{"type":"step_finish","reason":"stop","completed":true}"#;
2047        assert!(
2048            synthesize_response_from_text(single).is_none(),
2049            "single-line NDJSON event must also be rejected"
2050        );
2051    }
2052
2053    #[test]
2054    fn synthesize_response_accepts_json_without_event_type() {
2055        // A JSON-like blob that does NOT match a known NDJSON event type
2056        // should still be allowed through to the regular synthesis path
2057        // (so the guard does not over-reach).
2058        let text = "The task is complete. Filed issue #1234 successfully.";
2059        let response = synthesize_response_from_text(text).expect("plain prose should synthesize");
2060        assert_eq!(response.status, "done");
2061    }
2062
2063    // Regression: opencode/nemotron-3-super-free and similar models sometimes exit
2064    // with code 0 after emitting only exploratory or startup text (e.g. "Let's go!",
2065    // planning prose) without completing any work.  The synthesis must return None for
2066    // such ambiguous text so the runner treats the run as an invalid response and
2067    // reroutes the task instead of falsely advancing it to needs_review / in_review.
2068    // (Issues #2404, #2653, #2666)
2069    #[test]
2070    fn synthesize_response_returns_none_for_ambiguous_startup_text() {
2071        // Short greeting — not an error, not done, not an explicit negation.
2072        assert!(
2073            synthesize_response_from_text("Let's go!").is_none(),
2074            "startup greeting must not synthesize as needs_review"
2075        );
2076        // Exploratory planning prose — agent is thinking out loud, not reporting completion.
2077        assert!(
2078            synthesize_response_from_text(
2079                "I need to find where the stream command is implemented. \
2080                 Looking at the CLI structure, it seems like the stream functionality \
2081                 might be in the task module or another file. Let me check the CLI \
2082                 command structure. First, let me look at the task module since stream \
2083                 is related to tasks."
2084            )
2085            .is_none(),
2086            "exploratory prose must not synthesize as needs_review"
2087        );
2088    }
2089
2090    #[test]
2091    fn synthesize_response_does_not_mark_done_for_incomplete() {
2092        let response = synthesize_response_from_text("The task is incomplete").unwrap();
2093        assert_eq!(
2094            response.status, "needs_review",
2095            "\"incomplete\" should not match \"complete\""
2096        );
2097    }
2098
2099    #[test]
2100    fn synthesize_response_does_not_mark_done_for_not_done() {
2101        let response = synthesize_response_from_text("Changes are not done yet").unwrap();
2102        assert_eq!(
2103            response.status, "needs_review",
2104            "\"not done\" should not match bare \"done\""
2105        );
2106    }
2107
2108    #[test]
2109    fn synthesize_response_does_not_mark_done_for_not_complete() {
2110        let response = synthesize_response_from_text("Still in progress, not complete").unwrap();
2111        assert_eq!(
2112            response.status, "needs_review",
2113            "\"not complete\" should not match \"complete\""
2114        );
2115    }
2116
2117    #[test]
2118    fn synthesize_response_does_not_mark_done_for_not_yet_completed() {
2119        let response = synthesize_response_from_text("The task is not yet completed").unwrap();
2120        assert_eq!(
2121            response.status, "needs_review",
2122            "\"not yet completed\" should not match \"completed\""
2123        );
2124    }
2125
2126    #[test]
2127    fn synthesize_response_marks_done_for_completed() {
2128        let response =
2129            synthesize_response_from_text("Task has been completed successfully").unwrap();
2130        assert_eq!(response.status, "done");
2131    }
2132
2133    #[test]
2134    fn synthesize_response_marks_done_for_word_boundary_done() {
2135        let response = synthesize_response_from_text("All changes are done.").unwrap();
2136        assert_eq!(response.status, "done");
2137    }
2138
2139    #[test]
2140    fn synthesize_response_marks_done_for_issue_creation_text() {
2141        let response =
2142            synthesize_response_from_text("Filed 3 high-value GitHub issues: #1037, #1038, #1039")
2143                .unwrap();
2144
2145        assert_eq!(response.status, "done");
2146        assert!(response.error.is_none());
2147        assert!(
2148            response
2149                .summary
2150                .contains("Filed 3 high-value GitHub issues")
2151        );
2152    }
2153
2154    #[test]
2155    fn synthesize_response_marks_done_for_committed() {
2156        let response =
2157            synthesize_response_from_text("I've committed the changes to the repository").unwrap();
2158        assert_eq!(response.status, "done");
2159    }
2160
2161    #[test]
2162    fn synthesize_response_rejects_exploratory_prose() {
2163        // Regression test: ensure exploratory analysis that mentions "let me check"
2164        // or planning language is NOT synthesized into a "done" completion.
2165        // With the ambiguous-text fix, this text correctly returns None (treated as
2166        // an invalid response / reroute signal) rather than synthesizing needs_review.
2167        // Crucially, it must NOT be marked "done".
2168        let exploratory = "I explored the codebase and found several .expect()/.unwrap() uses.\n\nLet me check each occurrence directly and run the tests to be sure. I may commit fixes afterwards.";
2169        match synthesize_response_from_text(exploratory) {
2170            None => {
2171                // Ambiguous exploratory prose correctly returns None — not marked done.
2172            }
2173            Some(resp) => {
2174                assert_ne!(
2175                    resp.status, "done",
2176                    "Exploratory prose must not be auto-marked done"
2177                );
2178            }
2179        }
2180    }
2181
2182    #[test]
2183    fn synthesize_response_marks_done_for_commit_created() {
2184        let response = synthesize_response_from_text(
2185            "Commit created locally. The push is being blocked by permissions.",
2186        )
2187        .unwrap();
2188        assert_eq!(response.status, "done");
2189    }
2190
2191    #[test]
2192    fn synthesize_response_does_not_mark_done_for_not_committed() {
2193        let response = synthesize_response_from_text("The changes are not committed yet").unwrap();
2194        assert_eq!(
2195            response.status, "needs_review",
2196            "\"not committed\" should not match \"committed\""
2197        );
2198    }
2199
2200    // ── Regression: #1362/#1363 — agent text misclassified as needs_review ──
2201
2202    #[test]
2203    fn synthesize_response_marks_done_for_fix_is_complete() {
2204        // Exact agent output from task 30203 (issue #1363).
2205        // "The fix is complete" was misclassified as needs_review because
2206        // the pattern list had "completed" but not "complete".
2207        let response = synthesize_response_from_text(
2208            "All 73 cooldown tests pass. The fix is complete.\n\n\
2209             **Summary of changes:**\n\n\
2210             1. **`src/store/kv.rs`** — Added `kv_increment()` method that uses a single \
2211             `INSERT … ON CONFLICT … DO UPDATE … RETURNING` SQL statement.",
2212        )
2213        .unwrap();
2214        assert_eq!(
2215            response.status, "done",
2216            "\"The fix is complete\" must be classified as done, not needs_review"
2217        );
2218    }
2219
2220    #[test]
2221    fn synthesize_response_marks_done_for_tests_pass_fix_working() {
2222        // Exact agent output from task 30204 (issue #1362).
2223        // "All tests pass. The fix is clean and working." was misclassified
2224        // as needs_review because none of the looks_done patterns matched.
2225        let response = synthesize_response_from_text(
2226            "All tests pass. The fix is clean and working.\n\n\
2227             **Summary of changes** to `src/engine/runner/response.rs:37`:\n\n\
2228             - **Before:** `capped + jitter` → range `[capped, 1.6*capped]`\n\
2229             - **After:** `capped.saturating_sub(jitter_range) + jitter` → range `[0.7*capped, 1.3*capped]`",
2230        )
2231        .unwrap();
2232        assert_eq!(
2233            response.status, "done",
2234            "\"All tests pass. The fix is clean and working.\" must be classified as done"
2235        );
2236    }
2237
2238    // ── parse_ndjson edge cases ───────────────────────────────────
2239
2240    #[test]
2241    fn parse_ndjson_handles_standard_lines() {
2242        let raw = r#"{"type":"text","text":"hello"}
2243{"type":"text","text":"world"}"#;
2244        let events = parse_ndjson(raw);
2245        assert_eq!(events.len(), 2);
2246        assert_eq!(events[0].get("type").unwrap().as_str(), Some("text"));
2247        assert_eq!(events[1].get("type").unwrap().as_str(), Some("text"));
2248    }
2249
2250    #[test]
2251    fn parse_ndjson_skips_empty_lines() {
2252        let raw = r#"{"type":"text"}
2253
2254{"type":"text"}
2255"#;
2256        let events = parse_ndjson(raw);
2257        assert_eq!(events.len(), 2);
2258    }
2259
2260    #[test]
2261    fn parse_ndjson_skips_malformed_lines() {
2262        let raw = r#"{"type":"valid"}
2263not json at all
2264{"type":"also_valid"}"#;
2265        let events = parse_ndjson(raw);
2266        assert_eq!(events.len(), 2);
2267    }
2268
2269    #[test]
2270    fn parse_ndjson_fallback_extracts_embedded_json() {
2271        // Edge case: JSON with closing fence inside string field
2272        let raw =
2273            r#"text: {"text": "here is the result: ```json\n{\"status\":\"done\"}\n```"} more"#;
2274        let events = parse_ndjson(raw);
2275        // Should have extracted the embedded JSON object
2276        assert!(
2277            !events.is_empty(),
2278            "should extract JSON objects via fallback"
2279        );
2280    }
2281
2282    #[test]
2283    fn parse_ndjson_fallback_handles_fragmented_objects() {
2284        // Edge case: JSON object spread across multiple lines (fragmented NDJSON)
2285        let raw = r#"{"type": "text
2286", "content": "hello
2287world"}"#;
2288        let events = parse_ndjson(raw);
2289        // Should still extract the JSON via fallback
2290        assert!(!events.is_empty(), "should handle fragmented JSON");
2291    }
2292
2293    // ── PermissionRules defaults ────────────────────────────────
2294
2295    #[test]
2296    fn permission_rules_default_is_autonomous() {
2297        let rules = PermissionRules::default();
2298        assert!(rules.autonomous);
2299    }
2300
2301    #[test]
2302    fn permission_rules_default_sandbox_is_workspace_write() {
2303        let rules = PermissionRules::default();
2304        assert_eq!(rules.sandbox, SandboxLevel::WorkspaceWrite);
2305    }
2306
2307    #[test]
2308    fn permission_rules_default_disallows_rm() {
2309        let rules = PermissionRules::default();
2310        assert!(rules.disallowed_tools.contains(&"Bash(rm *)".to_string()));
2311        assert!(rules.disallowed_tools.contains(&"Bash(rm -*)".to_string()));
2312    }
2313
2314    #[test]
2315    fn permission_rules_default_no_allowed_edit_paths() {
2316        let rules = PermissionRules::default();
2317        assert!(
2318            rules.allowed_edit_paths.is_empty(),
2319            "{:?}",
2320            rules.allowed_edit_paths
2321        );
2322    }
2323
2324    // ── Permission translation across all agents ────────────────
2325
2326    /// Test that all agents handle the default permission rules consistently.
2327    #[test]
2328    fn all_agents_handle_default_permissions() {
2329        let perms = PermissionRules::default();
2330        let sys = "/tmp/sys.md";
2331        let msg = "/tmp/msg.md";
2332
2333        // Claude: should have bypassPermissions and rm disallowed
2334        let claude = get_runner("claude");
2335        let cmd = claude.build_command(None, "", sys, msg, &perms);
2336        assert!(
2337            cmd.contains("--permission-mode bypassPermissions"),
2338            "claude default: expected bypassPermissions, got: {cmd}"
2339        );
2340        assert!(
2341            cmd.contains("Bash(rm *)"),
2342            "claude default: expected rm disallowed, got: {cmd}"
2343        );
2344
2345        // Codex: autonomous + workspace-write → --sandbox workspace-write -c 'approval_policy="never"'
2346        let codex = get_runner("codex");
2347        let cmd = codex.build_command(None, "", sys, msg, &perms);
2348        assert!(
2349            cmd.contains("--sandbox workspace-write"),
2350            "codex default: expected --sandbox workspace-write, got: {cmd}"
2351        );
2352        assert!(
2353            cmd.contains(r#"-c 'approval_policy="never"'"#),
2354            "codex default: expected -c approval_policy=never, got: {cmd}"
2355        );
2356        assert!(
2357            !cmd.contains("--ask-for-approval"),
2358            "codex default: --ask-for-approval was removed in 0.133.0 and must not appear, got: {cmd}"
2359        );
2360        assert!(
2361            !cmd.contains("--full-auto"),
2362            "codex default: --full-auto is deprecated and must not appear, got: {cmd}"
2363        );
2364
2365        // OpenCode: autonomous dispatch passes --dangerously-skip-permissions
2366        // and writes no config file (relies on opencode's built-in flag).
2367        let opencode = get_runner("opencode");
2368        let cmd = opencode.build_command(None, "", sys, msg, &perms);
2369        assert!(
2370            cmd.contains("--dangerously-skip-permissions"),
2371            "opencode default: should pass --dangerously-skip-permissions, got: {cmd}"
2372        );
2373        assert!(
2374            !cmd.contains("opencode.json"),
2375            "opencode default: should not write a config file, got: {cmd}"
2376        );
2377        assert!(
2378            !cmd.contains("XDG_CONFIG_HOME"),
2379            "opencode default: should not override XDG_CONFIG_HOME, got: {cmd}"
2380        );
2381        assert!(
2382            !cmd.contains(".orch-opencode"),
2383            "opencode default: should not reference .orch-opencode, got: {cmd}"
2384        );
2385    }
2386
2387    /// Test supervised mode translates correctly for each agent.
2388    #[test]
2389    fn all_agents_handle_supervised_mode() {
2390        let perms = PermissionRules {
2391            autonomous: false,
2392            sandbox: SandboxLevel::WorkspaceWrite,
2393            disallowed_tools: vec![],
2394            allowed_tools: vec![],
2395            allowed_edit_paths: vec![],
2396            deny_read_only: false,
2397            extra_writable_dirs: vec![],
2398        };
2399        let sys = "/tmp/sys.md";
2400        let msg = "/tmp/msg.md";
2401
2402        // Claude: supervised → acceptEdits
2403        let claude = get_runner("claude");
2404        let cmd = claude.build_command(None, "", sys, msg, &perms);
2405        assert!(
2406            cmd.contains("--permission-mode acceptEdits"),
2407            "claude supervised: expected acceptEdits, got: {cmd}"
2408        );
2409
2410        // Codex: supervised → on-request
2411        let codex = get_runner("codex");
2412        let cmd = codex.build_command(None, "", sys, msg, &perms);
2413        assert!(
2414            cmd.contains(r#"-c 'approval_policy="on-request"'"#),
2415            "codex supervised: expected -c approval_policy=on-request, got: {cmd}"
2416        );
2417        assert!(
2418            !cmd.contains("--ask-for-approval"),
2419            "codex supervised: --ask-for-approval was removed in 0.133.0 and must not appear, got: {cmd}"
2420        );
2421    }
2422
2423    /// Test full access sandbox translates correctly for each agent.
2424    #[test]
2425    fn all_agents_handle_full_access_sandbox() {
2426        let perms = PermissionRules {
2427            autonomous: true,
2428            sandbox: SandboxLevel::FullAccess,
2429            disallowed_tools: vec![],
2430            allowed_tools: vec![],
2431            allowed_edit_paths: vec![],
2432            deny_read_only: false,
2433            extra_writable_dirs: vec![],
2434        };
2435        let sys = "/tmp/sys.md";
2436        let msg = "/tmp/msg.md";
2437
2438        // Claude: ignores sandbox level (no --sandbox flag)
2439        let claude = get_runner("claude");
2440        let cmd = claude.build_command(None, "", sys, msg, &perms);
2441        assert!(
2442            !cmd.contains("--sandbox"),
2443            "claude full_access: should have no sandbox flag, got: {cmd}"
2444        );
2445
2446        // Codex: full access → --dangerously-bypass-approvals-and-sandbox
2447        let codex = get_runner("codex");
2448        let cmd = codex.build_command(None, "", sys, msg, &perms);
2449        assert!(
2450            cmd.contains("--dangerously-bypass-approvals-and-sandbox"),
2451            "codex full_access: expected dangerously-bypass, got: {cmd}"
2452        );
2453    }
2454
2455    /// SandboxLevel::None with autonomous uses --sandbox workspace-write (same as WorkspaceWrite).
2456    #[test]
2457    fn codex_sandbox_none_uses_workspace_write() {
2458        let perms = PermissionRules {
2459            autonomous: true,
2460            sandbox: SandboxLevel::None,
2461            disallowed_tools: vec![],
2462            allowed_tools: vec![],
2463            allowed_edit_paths: vec![],
2464            deny_read_only: false,
2465            extra_writable_dirs: vec![],
2466        };
2467        let codex = get_runner("codex");
2468        let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2469        assert!(
2470            cmd.contains("--sandbox workspace-write"),
2471            "codex sandbox::none + autonomous: should use --sandbox workspace-write, got: {cmd}"
2472        );
2473        assert!(
2474            cmd.contains(r#"-c 'approval_policy="never"'"#),
2475            "codex sandbox::none + autonomous: should use -c approval_policy=never, got: {cmd}"
2476        );
2477        assert!(
2478            !cmd.contains("--ask-for-approval"),
2479            "codex sandbox::none: --ask-for-approval was removed in 0.133.0, got: {cmd}"
2480        );
2481        assert!(
2482            !cmd.contains("--full-auto"),
2483            "codex sandbox::none: --full-auto is deprecated and must not appear, got: {cmd}"
2484        );
2485    }
2486
2487    /// Test that allowed_edit_paths scopes Edit/Write when used with allowed_tools.
2488    #[test]
2489    fn claude_allowed_edit_paths_scope_edit_write() {
2490        let perms = PermissionRules {
2491            autonomous: true,
2492            sandbox: SandboxLevel::WorkspaceWrite,
2493            disallowed_tools: vec![],
2494            allowed_tools: vec![
2495                "Edit".to_string(),
2496                "Write".to_string(),
2497                "Read".to_string(),
2498                "Bash".to_string(),
2499            ],
2500            allowed_edit_paths: vec![PathBuf::from("/home/user/worktree")],
2501            deny_read_only: false,
2502            extra_writable_dirs: vec![],
2503        };
2504        let claude = get_runner("claude");
2505        let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2506
2507        // Edit/Write should be scoped to worktree path
2508        assert!(
2509            cmd.contains("Edit(/home/user/worktree/*)"),
2510            "missing scoped Edit, got: {cmd}"
2511        );
2512        assert!(
2513            cmd.contains("Write(/home/user/worktree/*)"),
2514            "missing scoped Write, got: {cmd}"
2515        );
2516        // Read should be unrestricted
2517        assert!(cmd.contains("Read"), "missing Read");
2518    }
2519
2520    /// Test that blocked paths don't affect Codex (it uses sandbox isolation).
2521    #[test]
2522    fn codex_ignores_allowed_edit_paths() {
2523        let perms = PermissionRules {
2524            autonomous: true,
2525            sandbox: SandboxLevel::WorkspaceWrite,
2526            disallowed_tools: vec![],
2527            allowed_tools: vec![],
2528            allowed_edit_paths: vec![PathBuf::from("/home/user/project")],
2529            deny_read_only: false,
2530            extra_writable_dirs: vec![],
2531        };
2532        let codex = get_runner("codex");
2533        let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2534        assert!(
2535            !cmd.contains("/home/user/project"),
2536            "codex: should not reference blocked paths, got: {cmd}"
2537        );
2538    }
2539
2540    /// Test that blocked paths don't affect OpenCode.
2541    #[test]
2542    fn opencode_ignores_allowed_edit_paths() {
2543        let perms = PermissionRules {
2544            autonomous: true,
2545            sandbox: SandboxLevel::WorkspaceWrite,
2546            disallowed_tools: vec![],
2547            allowed_tools: vec![],
2548            allowed_edit_paths: vec![PathBuf::from("/home/user/project")],
2549            deny_read_only: false,
2550            extra_writable_dirs: vec![],
2551        };
2552        let opencode = get_runner("opencode");
2553        let cmd = opencode.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2554        assert!(
2555            !cmd.contains("/home/user/project"),
2556            "opencode: should not reference blocked paths, got: {cmd}"
2557        );
2558    }
2559
2560    /// Test that disallowed tools merge correctly for Claude (defaults + custom).
2561    #[test]
2562    fn claude_merges_disallowed_tools() {
2563        let perms = PermissionRules {
2564            autonomous: true,
2565            sandbox: SandboxLevel::WorkspaceWrite,
2566            disallowed_tools: vec![
2567                "Bash(rm *)".to_string(),
2568                "Bash(sudo *)".to_string(),
2569                "WebFetch".to_string(),
2570            ],
2571            allowed_tools: vec![],
2572            allowed_edit_paths: vec![],
2573            deny_read_only: false,
2574            extra_writable_dirs: vec![],
2575        };
2576        let claude = get_runner("claude");
2577        let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2578        assert!(cmd.contains("Bash(rm *)"), "missing rm disallow");
2579        assert!(cmd.contains("Bash(sudo *)"), "missing sudo disallow");
2580        assert!(cmd.contains("WebFetch"), "missing WebFetch disallow");
2581    }
2582
2583    /// Test that Codex ignores disallowed tools (has no such flag).
2584    #[test]
2585    fn codex_ignores_disallowed_tools() {
2586        let perms = PermissionRules {
2587            autonomous: true,
2588            sandbox: SandboxLevel::WorkspaceWrite,
2589            disallowed_tools: vec!["Bash(rm *)".to_string(), "WebFetch".to_string()],
2590            allowed_tools: vec![],
2591            allowed_edit_paths: vec![],
2592            deny_read_only: false,
2593            extra_writable_dirs: vec![],
2594        };
2595        let codex = get_runner("codex");
2596        let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2597        assert!(
2598            !cmd.contains("disallow"),
2599            "codex: should not have disallow flags, got: {cmd}"
2600        );
2601    }
2602
2603    /// Test Claude with empty disallowed tools produces no --disallowedTools flag.
2604    #[test]
2605    fn claude_no_disallowed_flag_when_empty() {
2606        let perms = PermissionRules {
2607            autonomous: true,
2608            sandbox: SandboxLevel::WorkspaceWrite,
2609            disallowed_tools: vec![],
2610            allowed_tools: vec![],
2611            allowed_edit_paths: vec![],
2612            deny_read_only: false,
2613            extra_writable_dirs: vec![],
2614        };
2615        let claude = get_runner("claude");
2616        let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2617        assert!(
2618            !cmd.contains("--disallowedTools"),
2619            "claude: should have no disallowed flag when empty, got: {cmd}"
2620        );
2621    }
2622
2623    /// Test Kimi/MiniMax aliases inherit Claude permission translation.
2624    #[test]
2625    fn kimi_minimax_use_claude_permissions() {
2626        let perms = PermissionRules {
2627            autonomous: false,
2628            sandbox: SandboxLevel::WorkspaceWrite,
2629            disallowed_tools: vec!["Bash(rm *)".to_string()],
2630            allowed_tools: vec![],
2631            allowed_edit_paths: vec![],
2632            deny_read_only: false,
2633            extra_writable_dirs: vec![],
2634        };
2635        let sys = "/tmp/sys.md";
2636        let msg = "/tmp/msg.md";
2637
2638        for agent in &["kimi", "minimax"] {
2639            let runner = get_runner(agent);
2640            let cmd = runner.build_command(None, "", sys, msg, &perms);
2641            assert!(
2642                cmd.contains("--permission-mode acceptEdits"),
2643                "{agent}: expected acceptEdits"
2644            );
2645            assert!(
2646                cmd.contains("Bash(rm *)"),
2647                "{agent}: expected rm disallowed"
2648            );
2649        }
2650    }
2651
2652    /// Test kimi/minimax get --allowedTools when allowed_tools is set.
2653    #[test]
2654    fn kimi_minimax_use_allowed_tools() {
2655        let perms = PermissionRules {
2656            autonomous: true,
2657            sandbox: SandboxLevel::WorkspaceWrite,
2658            disallowed_tools: vec![],
2659            allowed_tools: vec!["Edit".to_string(), "Bash".to_string(), "git".to_string()],
2660            allowed_edit_paths: vec![],
2661            deny_read_only: false,
2662            extra_writable_dirs: vec![],
2663        };
2664
2665        for agent in &["kimi", "minimax"] {
2666            let runner = get_runner(agent);
2667            let cmd = runner.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2668            assert!(
2669                cmd.contains("--allowedTools"),
2670                "{agent}: expected --allowedTools, got: {cmd}"
2671            );
2672            assert!(
2673                cmd.contains("Bash(git *)"),
2674                "{agent}: expected Bash(git *) pattern, got: {cmd}"
2675            );
2676        }
2677    }
2678
2679    // ── Allowed tools across agents ─────────────────────────────
2680
2681    /// Test that allowed_tools generates --allowedTools for Claude.
2682    #[test]
2683    fn claude_allowed_tools_generates_allowedtools_flag() {
2684        let perms = PermissionRules {
2685            autonomous: true,
2686            sandbox: SandboxLevel::WorkspaceWrite,
2687            disallowed_tools: vec!["Bash(rm *)".to_string()],
2688            allowed_tools: vec![
2689                "Edit".to_string(),
2690                "Write".to_string(),
2691                "Read".to_string(),
2692                "Bash".to_string(),
2693                "git".to_string(),
2694            ],
2695            allowed_edit_paths: vec![],
2696            deny_read_only: false,
2697            extra_writable_dirs: vec![],
2698        };
2699
2700        let claude = get_runner("claude");
2701        let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2702        assert!(
2703            cmd.contains("--allowedTools"),
2704            "expected --allowedTools, got: {cmd}"
2705        );
2706        assert!(
2707            !cmd.contains("--disallowedTools"),
2708            "should not have --disallowedTools when allowed_tools is set"
2709        );
2710    }
2711
2712    /// Test that codex/opencode ignore allowed_tools (no equivalent flag).
2713    #[test]
2714    fn codex_opencode_ignore_allowed_tools() {
2715        let perms = PermissionRules {
2716            autonomous: true,
2717            sandbox: SandboxLevel::WorkspaceWrite,
2718            disallowed_tools: vec![],
2719            allowed_tools: vec!["Edit".to_string(), "git".to_string()],
2720            allowed_edit_paths: vec![],
2721            deny_read_only: false,
2722            extra_writable_dirs: vec![],
2723        };
2724
2725        let codex = get_runner("codex");
2726        let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2727        assert!(
2728            !cmd.contains("--allowedTools"),
2729            "codex should not have --allowedTools, got: {cmd}"
2730        );
2731
2732        let opencode = get_runner("opencode");
2733        let cmd = opencode.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2734        assert!(
2735            !cmd.contains("--allowedTools"),
2736            "opencode should not have --allowedTools, got: {cmd}"
2737        );
2738    }
2739
2740    // ── Integration: from_config() → agent translation ──────────
2741
2742    /// Integration test: verify from_config() loads real config and agents
2743    /// translate it correctly. Requires ~/.orch/config.yml to exist.
2744    #[test]
2745    #[ignore = "reads the operator config"]
2746    fn integration_from_config_to_agent_commands() {
2747        let perms = PermissionRules::from_config();
2748
2749        // Verify defaults are reasonable
2750        assert!(
2751            perms.autonomous,
2752            "from_config: expected autonomous=true by default"
2753        );
2754
2755        // Verify each agent can build a command from the config-loaded rules
2756        for agent_name in &["claude", "codex", "opencode", "kimi", "minimax"] {
2757            let runner = get_runner(agent_name);
2758            let cmd =
2759                runner.build_command(None, "timeout 1800", "/tmp/sys.md", "/tmp/msg.md", &perms);
2760            assert!(
2761                !cmd.is_empty(),
2762                "{agent_name}: build_command returned empty string"
2763            );
2764            assert!(
2765                cmd.contains(agent_name) || *agent_name == "kimi" || *agent_name == "minimax",
2766                "{agent_name}: command should reference agent binary, got: {cmd}"
2767            );
2768        }
2769    }
2770
2771    /// Integration test: verify from_config() handles supervised mode.
2772    /// Requires config with workflow.permissions.mode = "supervised".
2773    #[test]
2774    #[ignore = "reads the operator config"]
2775    fn integration_supervised_config_translates_correctly() {
2776        // This test requires config to have:
2777        // workflow:
2778        //   permissions:
2779        //     mode: supervised
2780        let perms = PermissionRules::from_config();
2781
2782        let claude = get_runner("claude");
2783        let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2784
2785        if perms.autonomous {
2786            assert!(
2787                cmd.contains("bypassPermissions"),
2788                "autonomous config → bypassPermissions"
2789            );
2790        } else {
2791            assert!(
2792                cmd.contains("acceptEdits"),
2793                "supervised config → acceptEdits"
2794            );
2795        }
2796
2797        let codex = get_runner("codex");
2798        let cmd = codex.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2799
2800        if perms.autonomous {
2801            // autonomous codex uses --sandbox workspace-write -c 'approval_policy="never"'
2802            assert!(
2803                cmd.contains("--sandbox workspace-write"),
2804                "autonomous config → --sandbox workspace-write, got: {cmd}"
2805            );
2806            assert!(
2807                cmd.contains(r#"-c 'approval_policy="never"'"#),
2808                "autonomous config → -c approval_policy=never, got: {cmd}"
2809            );
2810        } else {
2811            assert!(
2812                cmd.contains(r#"-c 'approval_policy="on-request"'"#),
2813                "supervised config → -c approval_policy=on-request, got: {cmd}"
2814            );
2815        }
2816        assert!(
2817            !cmd.contains("--ask-for-approval"),
2818            "--ask-for-approval was removed in codex 0.133.0 and must not appear, got: {cmd}"
2819        );
2820    }
2821
2822    // ── deny_read_only preset ───────────────────────────────────
2823
2824    /// Test that deny_read_only() sets the right disallowed tools for control sessions.
2825    #[test]
2826    fn deny_read_only_blocks_reading_tools() {
2827        let perms = PermissionRules::deny_read_only();
2828
2829        let read_tools = [
2830            "Bash(ls *)",
2831            "Bash(ls)",
2832            "Bash(find *)",
2833            "Bash(cat *)",
2834            "Bash(head *)",
2835            "Bash(tail *)",
2836            "Bash(fzf *)",
2837            "Bash(less *)",
2838            "Bash(more *)",
2839            "Read",
2840            "Glob",
2841            "Grep",
2842        ];
2843
2844        for tool in read_tools {
2845            assert!(
2846                perms.disallowed_tools.contains(&tool.to_string()),
2847                "deny_read_only should block {tool}, got: {:?}",
2848                perms.disallowed_tools
2849            );
2850        }
2851    }
2852
2853    /// Test that deny_read_only() produces correct Claude command for control session.
2854    #[test]
2855    fn deny_read_only_claude_command() {
2856        let perms = PermissionRules::deny_read_only();
2857        let claude = get_runner("claude");
2858        let cmd = claude.build_command(None, "", "/tmp/sys.md", "/tmp/msg.md", &perms);
2859
2860        // Should contain Read, Glob, Grep disallow patterns
2861        assert!(
2862            cmd.contains("Read"),
2863            "should block Read for control session"
2864        );
2865        assert!(
2866            cmd.contains("Glob"),
2867            "should block Glob for control session"
2868        );
2869        assert!(
2870            cmd.contains("Grep"),
2871            "should block Grep for control session"
2872        );
2873        // Should block ls
2874        assert!(
2875            cmd.contains("Bash(ls") || cmd.contains("Bash(ls *)"),
2876            "should block ls"
2877        );
2878        // Should still have bypassPermissions (autonomous)
2879        assert!(
2880            cmd.contains("--permission-mode bypassPermissions"),
2881            "should be autonomous (bypassPermissions)"
2882        );
2883    }
2884
2885    // --- synthesize_response_from_text structured extraction ---
2886
2887    #[test]
2888    fn synthesize_extracts_file_paths() {
2889        let text = "Fixed the issue by modifying src/engine/runner/agents/mod.rs and tests/integration.rs.";
2890        let resp = synthesize_response_from_text(text).unwrap();
2891        assert!(
2892            resp.files
2893                .contains(&"src/engine/runner/agents/mod.rs".to_string()),
2894            "expected src/engine/runner/agents/mod.rs in files, got: {:?}",
2895            resp.files
2896        );
2897        assert!(
2898            resp.files.contains(&"tests/integration.rs".to_string()),
2899            "expected tests/integration.rs in files, got: {:?}",
2900            resp.files
2901        );
2902    }
2903
2904    #[test]
2905    fn synthesize_extracts_accomplished_bullets() {
2906        let text = "All tests pass.\n- Added logging to src/foo.rs\n- Updated migration file";
2907        let resp = synthesize_response_from_text(text).unwrap();
2908        assert_eq!(resp.status, "done");
2909        assert!(
2910            resp.accomplished
2911                .iter()
2912                .any(|a| a.contains("Added logging")),
2913            "expected accomplished bullet, got: {:?}",
2914            resp.accomplished
2915        );
2916        assert!(
2917            resp.accomplished
2918                .iter()
2919                .any(|a| a.contains("Updated migration")),
2920            "expected accomplished bullet, got: {:?}",
2921            resp.accomplished
2922        );
2923    }
2924
2925    #[test]
2926    fn synthesize_extracts_remaining_section() {
2927        let text = "Completed the main fix.\n- Patched src/lib.rs\n\nRemaining:\n- Write unit tests\n- Update docs";
2928        let resp = synthesize_response_from_text(text).unwrap();
2929        assert!(
2930            resp.remaining
2931                .iter()
2932                .any(|r| r.contains("Write unit tests")),
2933            "expected remaining item, got: {:?}",
2934            resp.remaining
2935        );
2936        assert!(
2937            resp.remaining.iter().any(|r| r.contains("Update docs")),
2938            "expected remaining item, got: {:?}",
2939            resp.remaining
2940        );
2941        assert!(
2942            resp.accomplished.iter().any(|a| a.contains("Patched")),
2943            "expected accomplished item, got: {:?}",
2944            resp.accomplished
2945        );
2946    }
2947
2948    #[test]
2949    fn synthesize_fixed_phrase_is_done() {
2950        let text = "Fixed. The bug no longer reproduces.";
2951        let resp = synthesize_response_from_text(text).unwrap();
2952        assert_eq!(resp.status, "done", "expected done for 'Fixed.' text");
2953    }
2954
2955    // ── detect_rate_limit false-positive guard ────────────────────────────
2956    // Regression: NDJSON telemetry blobs can contain "429" as a token count
2957    // (e.g. "outputTokens":429). `detect_rate_limit` should still flag those
2958    // because it cannot distinguish context without the terminal_reason guard.
2959    // The guard lives in review.rs, but here we verify the raw detector
2960    // behaviour so callers know they must apply the guard themselves.
2961    #[test]
2962    fn detect_rate_limit_fires_on_bare_429_in_token_count() {
2963        // This SHOULD return Some — the generic detector has no context.
2964        // The caller (review.rs) is responsible for suppressing it when
2965        // terminal_reason:completed is present.
2966        let payload = r#"{"type":"result","terminal_reason":"completed","outputTokens":429,"is_error":false}"#;
2967        assert!(
2968            patterns::detect_rate_limit(payload).is_some(),
2969            "detect_rate_limit must still fire on bare 429 so callers apply the guard"
2970        );
2971    }
2972
2973    #[test]
2974    fn detect_rate_limit_ignores_429_inside_longer_number() {
2975        let uuid = r#"{"type":"hook","uuid":"a1b2c3d4-4295-4e5f-8a9b-0c1d2e3f4a5b"}"#;
2976        assert!(
2977            patterns::detect_rate_limit(uuid).is_none(),
2978            "429 inside a UUID digit run must not match"
2979        );
2980    }
2981
2982    #[test]
2983    fn detect_rate_limit_ignores_429_in_uuid_hex_group() {
2984        let hook = r#"{"type":"system","subtype":"hook_response","hook_id":"18db61b6-7b72-429c-8279-fae3089bf565"}"#;
2985        assert!(patterns::detect_rate_limit(hook).is_none());
2986    }
2987
2988    #[test]
2989    fn detect_rate_limit_429_message_comes_from_matched_line() {
2990        let filler = "unrelated agent prose that is long enough to fill the window. ".repeat(20);
2991        let text = format!("HTTP 429 Too Many Requests\n{filler}");
2992        match patterns::detect_rate_limit(&text) {
2993            Some(AgentError::RateLimit { message }) => assert!(message.contains("429")),
2994            other => panic!("expected RateLimit, got {other:?}"),
2995        }
2996    }
2997
2998    // Verify the guard logic that review.rs uses: when raw NDJSON has
2999    // terminal_reason:completed without is_error:true, the result of
3000    // detect_rate_limit should be suppressed.
3001    #[test]
3002    fn terminal_reason_completed_guard_suppresses_false_rate_limit() {
3003        let raw_output = r#"{"type":"result","terminal_reason":"completed","outputTokens":429,"is_error":false}"#;
3004        let ndjson_completed = raw_output.contains("\"terminal_reason\":\"completed\"")
3005            && !raw_output.contains("\"is_error\":true");
3006        // Apply the same guard that review.rs now uses.
3007        let detected = (!ndjson_completed)
3008            .then(|| patterns::detect_rate_limit(raw_output))
3009            .flatten();
3010        assert!(
3011            detected.is_none(),
3012            "guard must suppress rate-limit false positive from token-count 429 when terminal_reason:completed"
3013        );
3014    }
3015
3016    // Verify the guard does NOT suppress a real rate-limit error.
3017    #[test]
3018    fn terminal_reason_completed_guard_passes_real_rate_limit() {
3019        // Real rate-limit output has no terminal_reason:completed.
3020        let raw_output = "Error: 429 Too Many Requests — you have exceeded your quota";
3021        let ndjson_completed = raw_output.contains("\"terminal_reason\":\"completed\"")
3022            && !raw_output.contains("\"is_error\":true");
3023        let detected = (!ndjson_completed)
3024            .then(|| patterns::detect_rate_limit(raw_output))
3025            .flatten();
3026        assert!(
3027            detected.is_some(),
3028            "guard must NOT suppress a real rate-limit error"
3029        );
3030    }
3031
3032    #[test]
3033    fn synthesize_no_false_positive_file_paths() {
3034        // URLs and version strings should not appear in files list.
3035        // The text is ambiguous (no error, no done signal, no explicit negation) so
3036        // synthesize_response_from_text returns None — no file extraction happens.
3037        let text = "See https://example.com/foo.rs for details. Version 1.2.3 is fine.";
3038        match synthesize_response_from_text(text) {
3039            None => {} // Ambiguous text correctly returns None — no files extracted.
3040            Some(resp) => {
3041                assert!(
3042                    resp.files.is_empty(),
3043                    "expected no file paths extracted from URL text, got: {:?}",
3044                    resp.files
3045                );
3046            }
3047        }
3048    }
3049
3050    // Regression: issue #3197 — CLI arg-parser diagnostics were being synthesized as
3051    // agent responses. When a process (e.g. codex) fails with an invalid CLI flag, it
3052    // exits non-zero with a clap/help diagnostic on stderr. This should be rejected
3053    // (return None) rather than synthesized as a "needs_review" response.
3054    #[test]
3055    fn synthesize_rejects_cli_parser_diagnostics_unexpected_argument() {
3056        // Real clap error from the bug report (codex exit 141)
3057        let text = "error: unexpected argument '--ask-for-approval' found\n  \
3058                    tip: to pass '--ask-for-approval' as a value, use '-- --ask-for-approval'\n\
3059                    Usage: codex exec [OPTIONS] [PROMPT]";
3060        assert!(
3061            synthesize_response_from_text(text).is_none(),
3062            "CLI parser diagnostic must not synthesize as agent response"
3063        );
3064    }
3065
3066    #[test]
3067    fn synthesize_rejects_cli_parser_diagnostics_usage_line() {
3068        let text = "Usage: mycommand [OPTIONS] <arg>";
3069        assert!(
3070            synthesize_response_from_text(text).is_none(),
3071            "Usage line must not synthesize as agent response"
3072        );
3073    }
3074
3075    #[test]
3076    fn synthesize_rejects_cli_parser_diagnostics_help_hint() {
3077        let text = "Error: unknown flag --foo\nFor more information, try '--help'";
3078        assert!(
3079            synthesize_response_from_text(text).is_none(),
3080            "Help hint must not synthesize as agent response"
3081        );
3082    }
3083
3084    #[test]
3085    fn synthesize_rejects_cli_parser_diagnostics_tip() {
3086        let text = "error: bad value\ntip: to pass '--flag' as a value, use '-- --flag'";
3087        assert!(
3088            synthesize_response_from_text(text).is_none(),
3089            "Clap tip must not synthesize as agent response"
3090        );
3091    }
3092
3093    #[test]
3094    fn synthesize_accepts_agent_error_messages_that_mention_error() {
3095        // Agent returning plain text that happens to contain "error:" but is an actual
3096        // agent message (e.g. summarizing what went wrong) should still synthesize.
3097        let text = "I tried to run the command but got an error: permission denied on that file.";
3098        let response =
3099            synthesize_response_from_text(text).expect("agent error message should synthesize");
3100        assert_eq!(response.status, "needs_review");
3101        assert!(response.error.is_some());
3102    }
3103
3104    // Regression: Issue #3197 — exact clap error from bug report.
3105    // When codex fails with an invalid CLI flag (e.g., --ask-for-approval with old codex versions),
3106    // it should return None, not synthesize as "needs_review". Without this fix, the run
3107    // would be marked as success and advance to in_review, wasting resources.
3108    #[test]
3109    fn synthesize_rejects_exact_codex_cli_error() {
3110        let stderr_from_codex = "error: unexpected argument '--ask-for-approval' found\n  \
3111                                 tip: to pass '--ask-for-approval' as a value, use '-- --ask-for-approval'\n\
3112                                 Usage: codex exec [OPTIONS] [PROMPT]";
3113        assert!(
3114            synthesize_response_from_text(stderr_from_codex).is_none(),
3115            "exact codex CLI error from #3197 must not synthesize as agent response"
3116        );
3117    }
3118}