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