Skip to main content

orch/engine/runner/agents/
claude.rs

1//! Claude-compatible agent runner.
2//!
3//! Handles Claude, Kimi, and MiniMax agents. All three use the same
4//! `claude` binary (or a shell wrapper that sets `ANTHROPIC_BASE_URL`).
5//!
6//! ## CLI invocation
7//!
8//! ```bash
9//! claude -p --model {model} \
10//!   --permission-mode bypassPermissions \
11//!   --output-format stream-json \
12//!   --disallowedTools '...' \
13//!   --append-system-prompt "{sys_file}" \
14//!   < "{msg_file}"
15//! ```
16//!
17//! ## Output format (`--output-format stream-json`)
18//!
19//! NDJSON event stream; the final event is always `"type": "result"`:
20//! ```jsonl
21//! {"type":"system","subtype":"init",...}
22//! {"type":"assistant","message":{...}}
23//! {"type":"tool_use","tool":{...}}
24//! {"type":"tool_result","result":{...}}
25//! {"type":"result","subtype":"success","is_error":false,"duration_ms":2006,"result":"...","usage":{"input_tokens":10,"output_tokens":78},"modelUsage":{...}}
26//! ```
27//!
28//! Backward compatible with `--output-format json` (single JSON blob) — the
29//! parser finds the last `"type":"result"` line whether it is NDJSON or a
30//! pretty-printed single object.
31//!
32//! ## Kimi/MiniMax wrappers
33//!
34//! Both are shell scripts that `exec` the claude binary with custom env:
35//! ```bash
36//! exec env ANTHROPIC_BASE_URL=... ANTHROPIC_API_KEY=... claude "$@"
37//! ```
38//!
39//! ## Known error patterns
40//!
41//! - `is_error: true` with various message strings
42//! - "credit balance too low" — billing/auth
43//! - "overloaded" — capacity / rate limit (HTTP 529)
44//! - "rate limit" / "429" — standard rate limiting
45//! - "context_length_exceeded" — context overflow
46
47use std::path::PathBuf;
48
49use tokio::process::Command;
50
51use super::SandboxLevel;
52use super::{
53    AgentError, AgentRunner, ParsedResponse, PermissionRules, StreamEvent, json_error_message,
54    json_str,
55};
56use crate::engine::cooldown::RateLimitWindow;
57use crate::engine::runner::agents::opencode;
58use crate::parser;
59
60/// Runner for Claude-compatible agents (Claude, Kimi, MiniMax).
61#[derive(Debug)]
62pub struct ClaudeRunner {
63    /// The agent binary name (claude, kimi, minimax, or custom).
64    binary: String,
65}
66
67impl ClaudeRunner {
68    pub fn new(agent_name: &str) -> Self {
69        Self {
70            binary: agent_name.to_string(),
71        }
72    }
73
74    /// Parse the Claude `--output-format json` envelope.
75    ///
76    /// Extracts `result`, `usage`, and `is_error`.
77    fn parse_envelope(raw: &str) -> Result<ParsedResponse, AgentError> {
78        let parsed_json: serde_json::Value = serde_json::from_str(raw).map_err(|_| {
79            // Not valid JSON at all — try as raw text
80            AgentError::InvalidResponse {
81                raw: raw.to_string(),
82            }
83        })?;
84
85        let envelope = parsed_json
86            .as_object()
87            .ok_or_else(|| AgentError::InvalidResponse {
88                raw: raw.to_string(),
89            })?;
90
91        // Check if this is a Claude envelope (has "type" field)
92        let is_envelope = envelope.get("type").and_then(|v| v.as_str()) == Some("result");
93
94        if !is_envelope {
95            // Not a Claude envelope — try direct parsing via generic parser
96            return Self::parse_direct(raw);
97        }
98
99        // Check is_error flag
100        let is_error = envelope
101            .get("is_error")
102            .and_then(serde_json::Value::as_bool)
103            .unwrap_or(false);
104
105        // Extract the result text
106        let error_text = if is_error {
107            envelope_error_text(envelope)
108        } else {
109            String::new()
110        };
111        let result_text = if is_error {
112            error_text.as_str()
113        } else {
114            envelope
115                .get("result")
116                .and_then(|v| v.as_str())
117                .unwrap_or("")
118        };
119
120        if is_error {
121            // Classify the error from the result text.
122            // Check stale session first — it requires a targeted recovery action
123            // (reset UUID + retry) that is distinct from generic agent failures.
124            if let Some(e) = super::patterns::detect_stale_session(result_text) {
125                return Err(e);
126            }
127            // Check thinking block conflict before auth — it's a specific 400
128            // that must not be counted as a model failure.
129            if let Some(e) = super::patterns::detect_thinking_block_conflict(result_text) {
130                return Err(e);
131            }
132            // Check auth before rate_limit — billing errors (credit balance)
133            // are auth issues, not transient rate limits.
134            // Use result_text only (not combined with raw JSON) so the error
135            // message stays clean — the raw NDJSON stats blob must not leak
136            // into the logged reason string.
137            if let Some(e) = super::patterns::detect_auth_error(result_text) {
138                return Err(e);
139            }
140            if let Some(e) = super::patterns::detect_rate_limit(result_text) {
141                return Err(e);
142            }
143            if let Some(e) = super::patterns::detect_context_overflow(result_text) {
144                return Err(e);
145            }
146            return Err(AgentError::AgentFailed {
147                message: result_text.to_string(),
148            });
149        }
150
151        // Extract token usage from top-level `usage` object
152        let (input_tokens, output_tokens) = extract_usage(envelope);
153
154        // Extract duration
155        let duration_ms = envelope
156            .get("duration_ms")
157            .and_then(serde_json::Value::as_u64);
158
159        // Parse the inner result text into AgentResponse.
160        // Do NOT check for rate limits here — result_text is agent work product
161        // (summary, code descriptions) when is_error=false. Rate-limit keywords
162        // in work product cause false positives (see issue #1292).
163        let response = match parser::parse(result_text) {
164            Ok(r) => r,
165            Err(_) => {
166                // Structured parse failed — try plain-text synthesis.
167                // Preserve already-extracted tokens rather than discarding them (issue #1387).
168                super::synthesize_response_from_text(result_text).ok_or_else(|| {
169                    AgentError::InvalidResponse {
170                        raw: result_text.to_string(),
171                    }
172                })?
173            }
174        };
175
176        Ok(ParsedResponse {
177            response,
178            input_tokens,
179            output_tokens,
180            cost_usd: envelope_cost(envelope),
181            duration_ms,
182        })
183    }
184
185    /// Parse raw text directly (non-envelope response).
186    fn parse_direct(raw: &str) -> Result<ParsedResponse, AgentError> {
187        let response = parser::parse(raw).map_err(|_| AgentError::InvalidResponse {
188            raw: raw.to_string(),
189        })?;
190
191        Ok(ParsedResponse {
192            response,
193            input_tokens: None,
194            output_tokens: None,
195            cost_usd: None,
196            duration_ms: None,
197        })
198    }
199}
200
201/// Error text of an `is_error` envelope: `result`, else the joined `errors[]`, else `subtype`.
202/// Some agents (e.g. billing failures) put the message only in `errors[]`
203fn envelope_error_text(obj: &serde_json::Map<String, serde_json::Value>) -> String {
204    let result = obj.get("result").and_then(|v| v.as_str()).unwrap_or("");
205    if !result.is_empty() {
206        return result.to_string();
207    }
208    let errors = obj
209        .get("errors")
210        .and_then(|v| v.as_array())
211        .map(|a| {
212            a.iter()
213                .filter_map(|e| e.as_str())
214                .collect::<Vec<_>>()
215                .join("\n")
216        })
217        .unwrap_or_default();
218    if !errors.is_empty() {
219        return errors;
220    }
221    obj.get("subtype")
222        .and_then(|v| v.as_str())
223        .unwrap_or("")
224        .to_string()
225}
226
227/// Helper: extract error from a JSON object if it is a `type:result` envelope
228/// with `is_error=true`. Uses pattern detection for proper error classification
229/// (auth, rate limit, context overflow) rather than always returning AgentFailed.
230fn extract_error_from_envelope(
231    obj: &serde_json::Map<String, serde_json::Value>,
232    _raw: &str,
233) -> Option<AgentError> {
234    if obj.get("type").and_then(|v| v.as_str()) == Some("result")
235        && obj
236            .get("is_error")
237            .and_then(serde_json::Value::as_bool)
238            .unwrap_or(false)
239    {
240        let result_text = envelope_error_text(obj);
241        let result_text = result_text.as_str();
242        // Use result_text only (not combined with raw JSON) so the error
243        // message stays clean — the raw NDJSON stats blob must not leak
244        // into the logged reason string.
245        if let Some(e) = super::patterns::detect_thinking_block_conflict(result_text) {
246            return Some(e);
247        }
248        if let Some(e) = super::patterns::detect_auth_error(result_text) {
249            return Some(e);
250        }
251        if let Some(e) = super::patterns::detect_rate_limit(result_text) {
252            return Some(e);
253        }
254        if let Some(e) = super::patterns::detect_context_overflow(result_text) {
255            return Some(e);
256        }
257        return Some(AgentError::AgentFailed {
258            message: result_text.to_string(),
259        });
260    }
261    None
262}
263
264/// Helper: scan NDJSON lines in `text` for a `type:result` envelope with
265/// `is_error=true` and extract the error message. Returns `None` if no error
266/// envelope is found.
267fn detect_error_envelope(text: &str) -> Option<AgentError> {
268    for line in text.lines().filter(|l| !l.trim().is_empty()) {
269        if let Ok(val) = serde_json::from_str::<serde_json::Value>(line)
270            && let Some(obj) = val.as_object()
271            && let Some(err) = extract_error_from_envelope(obj, line)
272        {
273            return Some(err);
274        }
275    }
276    None
277}
278
279pub(crate) fn extract_stream_json_result_text(raw: &str) -> Result<String, AgentError> {
280    let trimmed = raw.trim();
281    if trimmed.is_empty() {
282        return Err(AgentError::InvalidResponse { raw: String::new() });
283    }
284
285    // Prefer the final result envelope whose result field is valid JSON.
286    // This skips outer-session plain-text summaries (issue #1387).
287    let envelope_line_opt = find_ndjson_result_line(trimmed).map(|(line, _)| line);
288
289    if let Some(line) = envelope_line_opt {
290        // Parse the found result line.
291        if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(line)
292            && let Some(obj) = parsed.as_object()
293        {
294            // Check is_error FIRST.
295            if let Some(err) = extract_error_from_envelope(obj, line) {
296                return Err(err);
297            }
298            // Extract result text from the JSON object.
299            if let Some(result) = obj.get("result") {
300                if let Some(text) = result.as_str() {
301                    return Ok(text.to_string());
302                }
303                if result.is_object() || result.is_array() {
304                    return Ok(result.to_string());
305                }
306            }
307        }
308        // Not an error, but result field is not extractable: fall through to fallback.
309    }
310
311    // No JSON result line found (or it wasn't an error). Try opencode-style
312    // text extraction which scans NDJSON for text/result events.
313    if let Some(fallback) = opencode::extract_router_text(trimmed) {
314        return Ok(fallback);
315    }
316
317    // No opencode-style text found. Try parsing the whole trimmed string as a
318    // single JSON object (handles `--output-format json` plain output).
319    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(trimmed)
320        && let Some(obj) = parsed.as_object()
321    {
322        // Check for error envelope in the single-line JSON.
323        if let Some(err) = extract_error_from_envelope(obj, trimmed) {
324            return Err(err);
325        }
326        // Extract result text from the JSON object.
327        if let Some(result) = obj.get("result") {
328            if let Some(text) = result.as_str() {
329                return Ok(text.to_string());
330            }
331            if result.is_object() || result.is_array() {
332                return Ok(result.to_string());
333            }
334        }
335        return Ok(trimmed.to_string());
336    }
337
338    // Not valid JSON at all. Before returning raw text, scan for error envelopes
339    // (handles the case where find_ndjson_result_line skipped error-only output).
340    if let Some(err) = detect_error_envelope(trimmed) {
341        return Err(err);
342    }
343
344    Ok(trimmed.to_string())
345}
346
347impl AgentRunner for ClaudeRunner {
348    #[cfg(test)]
349    fn name(&self) -> &str {
350        &self.binary
351    }
352
353    fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent> {
354        stream_events(event)
355    }
356
357    fn router_transcript(&self) -> super::RouterTranscript {
358        super::RouterTranscript::Messages
359    }
360
361    fn extract_text(&self, raw: &str) -> Result<String, super::AgentError> {
362        // Empty input: return empty string (not an error), matching historical behavior.
363        if raw.trim().is_empty() {
364            return Ok(String::new());
365        }
366        extract_stream_json_result_text(raw)
367    }
368
369    fn build_command(
370        &self,
371        model: Option<&str>,
372        timeout_cmd: &str,
373        sys_file: &str,
374        msg_file: &str,
375        permissions: &PermissionRules,
376    ) -> String {
377        let model_flag = model
378            .map(str::trim)
379            .filter(|m| !m.is_empty())
380            .map(|m| format!("--model {}", super::shell_single_quote(m)))
381            .unwrap_or_default();
382
383        // Claude permission mode: autonomous → bypassPermissions, supervised → acceptEdits
384        // dontAsk refuses every tool not on --allowedTools instead of asking, so a read-only
385        // chat runs its allowlist and nothing else
386        let permission_mode = if permissions.sandbox == SandboxLevel::ReadOnly {
387            "dontAsk"
388        } else if permissions.autonomous {
389            "bypassPermissions"
390        } else {
391            "acceptEdits"
392        };
393
394        // Build tool restriction flags.
395        // If allowed_tools is set (whitelist), use --allowedTools and ignore disallowed_tools.
396        // Otherwise fall back to --disallowedTools (deny list).
397        let tool_flag = if !permissions.allowed_tools.is_empty() {
398            let tools = translate_allowed_tools(
399                &permissions.allowed_tools,
400                &permissions.allowed_edit_paths,
401            );
402            format!("--allowedTools '{}'", tools.join(","))
403        } else if !permissions.disallowed_tools.is_empty() {
404            format!(
405                "--disallowedTools '{}'",
406                permissions.disallowed_tools.join(",")
407            )
408        } else {
409            String::new()
410        };
411
412        // A read-only chat ignores the operator's own settings files, whose allow rules would widen
413        // its allowlist, loads no MCP server, and has only the tool kinds its allowlist names
414        let (restrict_flag, prompt_flag) = if permissions.sandbox == SandboxLevel::ReadOnly {
415            let mut kinds: Vec<&str> = permissions
416                .allowed_tools
417                .iter()
418                .filter(|t| CLAUDE_NATIVE_TOOLS.contains(&t.as_str()))
419                .map(String::as_str)
420                .collect();
421            if permissions
422                .allowed_tools
423                .iter()
424                .any(|t| t.starts_with("Bash("))
425            {
426                kinds.push("Bash");
427            }
428            (
429                format!(
430                    "--restricted --strict-mcp-config --tools '{}' \\\n  ",
431                    kinds.join(",")
432                ),
433                "--append-system-prompt-file",
434            )
435        } else {
436            (String::new(), "--append-system-prompt")
437        };
438
439        format!(
440            r#"{timeout_cmd} {binary} -p --verbose {model_flag} \
441  --permission-mode {permission_mode} \
442  --output-format stream-json \
443  {restrict_flag}{tool_flag} \
444  {prompt_flag} "{sys_file}" \
445  < "{msg_file}""#,
446            timeout_cmd = timeout_cmd,
447            binary = self.binary,
448            model_flag = model_flag,
449            permission_mode = permission_mode,
450            tool_flag = tool_flag,
451            sys_file = sys_file,
452            msg_file = msg_file,
453        )
454    }
455
456    fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError> {
457        let trimmed = raw.trim();
458        if trimmed.is_empty() {
459            return Err(AgentError::InvalidResponse { raw: String::new() });
460        }
461
462        // For NDJSON (--output-format stream-json): find the best result line and its
463        // token count. For single-line JSON (--output-format json), returns None.
464        if let Some((result_line, tokens)) = find_ndjson_result_line(trimmed) {
465            let result = Self::parse_envelope(result_line)?;
466            // If the envelope parse preserved meaningful tokens, use those.
467            // Otherwise, fall back to the tokens from find_ndjson_result_line
468            // (which selected the best result line by token count — issue #1387).
469            let input_tokens = result.input_tokens.or(tokens.map(|(i, _)| i));
470            let output_tokens = result.output_tokens.or(tokens.map(|(_, o)| o));
471            if input_tokens != result.input_tokens || output_tokens != result.output_tokens {
472                return Ok(ParsedResponse {
473                    input_tokens,
474                    output_tokens,
475                    ..result
476                });
477            }
478            return Ok(result);
479        }
480
481        // Fallback: treat the whole string as the envelope (e.g. pretty-printed JSON)
482        Self::parse_envelope(trimmed)
483    }
484
485    fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError {
486        // For claude-protocol agents the real error string lives in the `result`
487        // field of the NDJSON result line (when is_error=true). Prepend it to the
488        // combined text so the classifier sees it before the raw metadata tail.
489        let error_result: Option<String> = (|| {
490            let trimmed = stdout.trim();
491            let (line, _) = find_ndjson_result_line(trimmed)?;
492            let val: serde_json::Value = serde_json::from_str(line).ok()?;
493            let obj = val.as_object()?;
494            if obj.get("is_error").and_then(serde_json::Value::as_bool) != Some(true) {
495                return None;
496            }
497            Some(envelope_error_text(obj)).filter(|t| !t.is_empty())
498        })();
499
500        // Also check for system-level error events (e.g., session limit mid-stream).
501        // These appear as `type:system` NDJSON events with an error object, not as
502        // `type:result` lines with `is_error:true`. This catches errors like session
503        // limits, credential issues, and API errors that interrupt the agent mid-run.
504        //
505        // Example:
506        //   {"type":"system","subtype":"error","error":{"type":"session_limit","message":"..."}}
507        let system_error: Option<String> = (|| {
508            let trimmed = stdout.trim();
509            for line in trimmed.lines() {
510                let line = line.trim();
511                if line.is_empty() {
512                    continue;
513                }
514                if let Ok(val) = serde_json::from_str::<serde_json::Value>(line)
515                    && let Some(obj) = val.as_object()
516                    && obj.get("type").and_then(|t| t.as_str()) == Some("system")
517                    && let Some(error) = obj.get("error")
518                    && let Some(msg) = error.get("message").and_then(|m| m.as_str())
519                {
520                    return Some(msg.to_string());
521                }
522            }
523            None
524        })();
525
526        // A kill signal (SIGTERM or SIGKILL) with no result envelope and no error event
527        // is an interrupted run, not a provider failure, so skip the text scan
528        let has_result_line = find_ndjson_result_line(stdout.trim()).is_some();
529        if matches!(exit_code, 143 | 137)
530            && !has_result_line
531            && error_result.is_none()
532            && system_error.is_none()
533        {
534            return AgentError::Interrupted {
535                message: format!("agent killed by signal (exit {exit_code})"),
536            };
537        }
538
539        let combined = match (&error_result, &system_error) {
540            (Some(r), Some(s)) => format!("{s}\n{r}\n{stdout}\n{stderr}"),
541            (Some(r), None) => format!("{r}\n{stdout}\n{stderr}"),
542            (None, Some(s)) => format!("{s}\n{stdout}\n{stderr}"),
543            (None, None) => format!("{stdout}\n{stderr}"),
544        };
545        // Envelope billing text is prepended into the same 3000-byte head as hook
546        // UUIDs, so classify the envelope before the combined scan
547        if let Some(message) = &error_result
548            && let Some(e) = super::patterns::detect_auth_error(message)
549        {
550            return e;
551        }
552        let classified = super::patterns::classify_from_text(exit_code, &combined);
553
554        // `classify_from_text`'s generic catch-all truncates to the last 300
555        // bytes of the combined text, which can cut a perfectly well-formed
556        // `error_result` line off mid-field-name (e.g. `is_error` becomes
557        // `i_error`) once enough NDJSON precedes it (issue #3577). When we
558        // already extracted a clean, complete error message from the result
559        // envelope but none of the specific pattern detectors matched it,
560        // prefer that clean message over the byte-truncated fallback.
561        if let (AgentError::Unknown { .. }, Some(message)) = (&classified, &error_result)
562            && !message.is_empty()
563        {
564            return AgentError::AgentFailed {
565                message: message.clone(),
566            };
567        }
568        classified
569    }
570
571    fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command> {
572        let mut cmd = Command::new(&self.binary);
573        cmd.env_remove("CLAUDECODE"); // allow nested invocation
574        cmd.arg("--output-format")
575            .arg("stream-json")
576            .arg("--verbose")
577            .arg("--print");
578        if let Some(m) = model.map(str::trim).filter(|m| !m.is_empty()) {
579            cmd.arg("--model").arg(m);
580        }
581        cmd.arg(prompt);
582        Ok(cmd)
583    }
584}
585
586/// Known Claude Code native tool names.
587/// These are passed as-is to `--allowedTools`.
588const CLAUDE_NATIVE_TOOLS: &[&str] = &[
589    "Edit",
590    "Write",
591    "Read",
592    "Bash",
593    "Grep",
594    "Glob",
595    "WebFetch",
596    "WebSearch",
597    "Task",
598    "Skill",
599    "NotebookEdit",
600    "EnterPlanMode",
601    "ExitPlanMode",
602    "EnterWorktree",
603    "AskUserQuestion",
604    "TodoWrite",
605    "TodoRead",
606];
607
608/// Translate a unified allowed_tools list into Claude `--allowedTools` patterns.
609///
610/// - Items matching known Claude tool names pass through as-is
611/// - Edit/Write are scoped to `allowed_edit_paths` when set
612/// - Other items are treated as CLI commands and become `Bash(<cmd> *)` patterns
613fn translate_allowed_tools(allowed: &[String], allowed_edit_paths: &[PathBuf]) -> Vec<String> {
614    let mut tools = Vec::new();
615    for item in allowed {
616        if (item == "Edit" || item == "Write") && !allowed_edit_paths.is_empty() {
617            // Scope Edit/Write to allowed paths only
618            for path in allowed_edit_paths {
619                tools.push(format!("{}({}/*)", item, path.display()));
620            }
621        } else if CLAUDE_NATIVE_TOOLS.contains(&item.as_str()) || item.starts_with("Bash(") {
622            tools.push(item.clone());
623        } else {
624            // CLI command → Bash(<cmd> *) pattern
625            tools.push(format!("Bash({item} *)"));
626        }
627    }
628    tools
629}
630
631/// Find the best NDJSON result line and its token usage.
632///
633/// Returns `(line, tokens)` where `tokens` is `Some((input, output))` or `None`
634/// if no usage data was found.
635///
636/// Selection priority:
637/// 1. JSON result fields (object/array or string that parses as JSON) — always preferred
638/// 2. Among plain-text results: the one with the most total tokens (preferring actual
639///    work over outer-session confirmation summaries)
640/// 3. Error results (is_error=true) — included even with no tokens, so the caller can
641///    classify them properly
642///
643/// This skips outer-session plain-text summaries in favor of inner task results
644/// with meaningful token counts (issue #1387).
645pub(crate) fn find_ndjson_result_line(text: &str) -> Option<(&str, Option<(u64, u64)>)> {
646    let lines: Vec<_> = text.lines().filter(|l| !l.trim().is_empty()).collect();
647
648    // Pass 1: find a result line with a JSON result field.
649    // JSON results are always preferred (inner task delegate output).
650    for line in lines.iter().rev() {
651        if let Ok(val) = serde_json::from_str::<serde_json::Value>(line)
652            && let Some(obj) = val.as_object()
653            && obj.get("type").and_then(|t| t.as_str()) == Some("result")
654            && let Some(result) = obj.get("result")
655        {
656            let is_json_result = match result {
657                serde_json::Value::Object(_) | serde_json::Value::Array(_) => true,
658                serde_json::Value::String(s) => {
659                    serde_json::from_str::<serde_json::Value>(s).is_ok()
660                }
661                _ => false,
662            };
663            if is_json_result {
664                let tokens = extract_result_tokens(obj);
665                return Some((line, tokens));
666            }
667        }
668    }
669
670    // Pass 2: no JSON result found — choose the plain-text result with the most tokens.
671    // This handles outer-session confirmation summaries (e.g. "Already retrieved the result")
672    // vs. actual work summaries: prefer the one with more tokens.
673    // Error results (is_error=true) are included even with zero tokens, so the caller
674    // can classify them properly.
675    let mut best_line: Option<&str> = None;
676    let mut best_total = 0u64;
677
678    for line in &lines {
679        if let Ok(val) = serde_json::from_str::<serde_json::Value>(line)
680            && let Some(obj) = val.as_object()
681            && obj.get("type").and_then(|t| t.as_str()) == Some("result")
682        {
683            let tokens = extract_result_tokens(obj);
684            let total = tokens.map_or(0, |(i, o)| i.saturating_add(o));
685            if total >= best_total {
686                best_total = total;
687                best_line = Some(*line);
688            }
689        }
690    }
691
692    best_line.map(|line| (line, extract_result_tokens_from_line(line)))
693}
694
695/// Extract input/output token counts from a parsed result envelope object.
696fn extract_result_tokens(obj: &serde_json::Map<String, serde_json::Value>) -> Option<(u64, u64)> {
697    // Try top-level `usage` first.
698    if let Some(usage) = obj.get("usage").and_then(|v| v.as_object()) {
699        let input = usage
700            .get("input_tokens")
701            .and_then(serde_json::Value::as_u64);
702        let output = usage
703            .get("output_tokens")
704            .and_then(serde_json::Value::as_u64);
705        if let (Some(i), Some(o)) = (input, output) {
706            return Some((i, o));
707        }
708    }
709    // Try modelUsage (aggregated across models).
710    if let Some(model_usage) = obj.get("modelUsage").and_then(|v| v.as_object()) {
711        let mut total_input = 0u64;
712        let mut total_output = 0u64;
713        let mut found = false;
714        for (_model_name, model_stats) in model_usage {
715            if let Some(stats) = model_stats.as_object() {
716                if let Some(i) = stats
717                    .get("inputTokens")
718                    .or_else(|| stats.get("input_tokens"))
719                    .and_then(serde_json::Value::as_u64)
720                {
721                    total_input += i;
722                    found = true;
723                }
724                if let Some(o) = stats
725                    .get("outputTokens")
726                    .or_else(|| stats.get("output_tokens"))
727                    .and_then(serde_json::Value::as_u64)
728                {
729                    total_output += o;
730                    found = true;
731                }
732            }
733        }
734        if found {
735            return Some((total_input, total_output));
736        }
737    }
738    None
739}
740
741/// Extract token counts from a raw NDJSON result line string.
742fn extract_result_tokens_from_line(line: &str) -> Option<(u64, u64)> {
743    let val = serde_json::from_str::<serde_json::Value>(line).ok()?;
744    let obj = val.as_object()?;
745    extract_result_tokens(obj)
746}
747
748/// The run cost the envelope reports. Claude Code names it `total_cost_usd`, older builds used
749/// `costUSD` or `cost_usd`.
750fn envelope_cost(envelope: &serde_json::Map<String, serde_json::Value>) -> Option<f64> {
751    envelope
752        .get("total_cost_usd")
753        .or_else(|| envelope.get("costUSD"))
754        .or_else(|| envelope.get("cost_usd"))
755        .and_then(serde_json::Value::as_f64)
756}
757
758/// Extract input/output tokens from the Claude envelope's usage objects.
759fn extract_usage(
760    envelope: &serde_json::Map<String, serde_json::Value>,
761) -> (Option<u64>, Option<u64>) {
762    // Try top-level `usage` first
763    if let Some(usage) = envelope.get("usage").and_then(|v| v.as_object()) {
764        let input = usage
765            .get("input_tokens")
766            .and_then(serde_json::Value::as_u64);
767        let output = usage
768            .get("output_tokens")
769            .and_then(serde_json::Value::as_u64);
770        if input.is_some() || output.is_some() {
771            return (input, output);
772        }
773    }
774
775    // Try modelUsage (aggregated across models)
776    if let Some(model_usage) = envelope.get("modelUsage").and_then(|v| v.as_object()) {
777        let mut total_input = 0u64;
778        let mut total_output = 0u64;
779        let mut found = false;
780
781        for (_model_name, model_stats) in model_usage {
782            if let Some(stats) = model_stats.as_object() {
783                if let Some(i) = stats
784                    .get("inputTokens")
785                    .or_else(|| stats.get("input_tokens"))
786                    .and_then(serde_json::Value::as_u64)
787                {
788                    total_input += i;
789                    found = true;
790                }
791                if let Some(o) = stats
792                    .get("outputTokens")
793                    .or_else(|| stats.get("output_tokens"))
794                    .and_then(serde_json::Value::as_u64)
795                {
796                    total_output += o;
797                    found = true;
798                }
799            }
800        }
801
802        if found {
803            return (Some(total_input), Some(total_output));
804        }
805    }
806
807    (None, None)
808}
809
810const SHOW_CURSOR: &str = "\x1b[?25h";
811const HIDE_CURSOR: &str = "\x1b[?25l";
812
813/// Drop `script` tty junk: show-cursor (`ESC[?25h`) and `^D`/backspace redraw lines
814pub fn strip_tty_control_lines(raw: &str) -> String {
815    raw.lines()
816        .filter(|line| !is_tty_control_line(line))
817        .map(strip_trailing_cursor)
818        .collect::<Vec<_>>()
819        .join("\n")
820}
821
822fn strip_trailing_cursor(line: &str) -> &str {
823    let mut s = line.trim_end();
824    loop {
825        if let Some(next) = s
826            .strip_suffix(SHOW_CURSOR)
827            .or_else(|| s.strip_suffix(HIDE_CURSOR))
828        {
829            s = next.trim_end();
830            continue;
831        }
832        return s;
833    }
834}
835
836fn is_tty_control_line(line: &str) -> bool {
837    let trimmed = strip_trailing_cursor(line).trim();
838    if trimmed.is_empty() {
839        return !line.trim().is_empty();
840    }
841    trimmed.chars().all(|c| matches!(c, '^' | 'D' | '\u{0008}'))
842}
843
844/// Type of the last content block on the last assistant NDJSON message
845fn last_assistant_content_type(ndjson: &str) -> Option<String> {
846    let mut last = None;
847    for line in ndjson.lines() {
848        let line = line.trim();
849        if line.is_empty() {
850            continue;
851        }
852        let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
853            continue;
854        };
855        if val.get("type").and_then(|v| v.as_str()) != Some("assistant") {
856            continue;
857        }
858        let Some(content) = val
859            .get("message")
860            .and_then(|m| m.get("content"))
861            .and_then(|c| c.as_array())
862        else {
863            continue;
864        };
865        if let Some(item) = content.last()
866            && let Some(t) = item.get("type").and_then(|v| v.as_str())
867        {
868            last = Some(t.to_string());
869        }
870    }
871    last
872}
873
874/// True when the stream has no result envelope and ended on a thinking block
875/// or a tool call, so the model never produced a finished review decision
876pub fn review_session_exited_mid_thought(ndjson: &str) -> bool {
877    if find_ndjson_result_line(ndjson).is_some() {
878        return false;
879    }
880    matches!(
881        last_assistant_content_type(ndjson).as_deref(),
882        Some("thinking" | "redacted_thinking" | "tool_use")
883    )
884}
885
886/// Extract a structured `AgentResult` from Claude/Kimi/MiniMax NDJSON output.
887///
888/// Finds the last `"type":"result"` line whose `result` field contains valid JSON.
889/// This skips outer-session plain-text summaries (issue #1387) and finds the
890/// actual task-delegate result with structured JSON.
891///
892/// Extracts:
893/// - `result` text (the inner content)
894/// - `is_error` flag
895/// - token usage from `usage` or `modelUsage`
896/// - `duration_ms`
897///
898/// If no JSON result line exists (common with MiniMax), falls back to
899/// extracting the last assistant text message from the stream.
900///
901/// Returns `None` only if the input contains no recognizable NDJSON events.
902pub fn find_claude_result(ndjson: &str) -> Option<super::AgentResult> {
903    let stripped = strip_tty_control_lines(ndjson);
904    let trimmed = stripped.trim();
905    if trimmed.is_empty() {
906        return None;
907    }
908
909    // Try to find the result envelope first
910    if let Some((result_line, _tokens)) = find_ndjson_result_line(trimmed)
911        && let Ok(parsed) = serde_json::from_str::<serde_json::Value>(result_line)
912        && let Some(envelope) = parsed.as_object()
913    {
914        let is_error = envelope
915            .get("is_error")
916            .and_then(serde_json::Value::as_bool)
917            .unwrap_or(false);
918
919        let result_text = if is_error {
920            // Error envelopes put the real message in errors[] (billing,
921            // rate limits) with `result` empty — don't lose it (issue #3713)
922            envelope_error_text(envelope)
923        } else {
924            envelope
925                .get("result")
926                .and_then(|v| v.as_str())
927                .unwrap_or("")
928                .to_string()
929        };
930
931        let (input_tokens, output_tokens) = extract_usage(envelope);
932        let duration_ms = envelope
933            .get("duration_ms")
934            .and_then(serde_json::Value::as_u64);
935
936        let cost_usd = envelope_cost(envelope);
937
938        return Some(super::AgentResult {
939            is_error,
940            result_text,
941            input_tokens,
942            output_tokens,
943            cost_usd,
944            duration_ms,
945            truncated_by_length: false,
946        });
947    }
948
949    // Fallback for MiniMax/Kimi: extract last assistant text message
950    let mut last_text = None;
951    let mut input_tokens = None;
952    let mut output_tokens = None;
953
954    for line in trimmed.lines() {
955        let line = line.trim();
956        if line.is_empty() {
957            continue;
958        }
959        let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
960            continue;
961        };
962        if val.get("type").and_then(|v| v.as_str()) != Some("assistant") {
963            continue;
964        }
965        // Extract text from content array
966        if let Some(content) = val
967            .get("message")
968            .and_then(|m| m.get("content"))
969            .and_then(|c| c.as_array())
970        {
971            for item in content {
972                if item.get("type").and_then(|v| v.as_str()) == Some("text")
973                    && let Some(text) = item.get("text").and_then(|v| v.as_str())
974                {
975                    let t = text.trim();
976                    if !t.is_empty() {
977                        last_text = Some(t.to_string());
978                    }
979                }
980            }
981        }
982        // Extract usage (take max, as Claude reports cumulative)
983        if let Some(usage) = val.get("message").and_then(|m| m.get("usage")) {
984            if let Some(inp) = usage
985                .get("input_tokens")
986                .and_then(serde_json::Value::as_u64)
987            {
988                input_tokens = Some(input_tokens.unwrap_or(0u64).max(inp));
989            }
990            if let Some(out) = usage
991                .get("output_tokens")
992                .and_then(serde_json::Value::as_u64)
993            {
994                output_tokens = Some(output_tokens.unwrap_or(0u64).max(out));
995            }
996        }
997    }
998
999    last_text.map(|text| super::AgentResult {
1000        is_error: false,
1001        result_text: text,
1002        input_tokens,
1003        output_tokens,
1004        cost_usd: None,
1005        duration_ms: None,
1006        truncated_by_length: false,
1007    })
1008}
1009
1010/// Keep a vendor label printable: letters, digits, `_` and `-`, at most 32 characters
1011fn sanitize_window_label(raw: &str) -> String {
1012    raw.chars()
1013        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'))
1014        .take(32)
1015        .collect()
1016}
1017
1018/// Every window of every `rate_limit_event`, oldest first. The event status belongs to the headline
1019/// window, the other `unifiedWindows` entries use their own status or `unknown`
1020pub fn rate_limit_windows(ndjson: &str) -> Vec<RateLimitWindow> {
1021    let mut windows = Vec::new();
1022    for line in ndjson
1023        .lines()
1024        .filter(|line| line.contains("rate_limit_event"))
1025    {
1026        let Ok(val) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1027            continue;
1028        };
1029        if val.get("type").and_then(|v| v.as_str()) != Some("rate_limit_event") {
1030            continue;
1031        }
1032        let Some(info) = val.get("rate_limit_info") else {
1033            continue;
1034        };
1035        let Some(status) = info.get("status").and_then(|v| v.as_str()) else {
1036            continue;
1037        };
1038        let unified = info.get("unifiedWindows").and_then(|v| v.as_object());
1039        let headline_raw = info
1040            .get("rateLimitType")
1041            .and_then(|v| v.as_str())
1042            .unwrap_or("unknown");
1043        let headline = unified.and_then(|map| map.get(headline_raw));
1044        windows.push(RateLimitWindow {
1045            status: sanitize_window_label(status),
1046            window_type: sanitize_window_label(headline_raw),
1047            utilization: headline
1048                .and_then(|w| w.get("utilization"))
1049                .or_else(|| info.get("utilization"))
1050                .and_then(serde_json::Value::as_f64),
1051            resets_at: info
1052                .get("resetsAt")
1053                .or_else(|| headline.and_then(|w| w.get("resetsAt")))
1054                .and_then(serde_json::Value::as_i64),
1055        });
1056        for (name, w) in unified.into_iter().flatten() {
1057            if name == headline_raw {
1058                continue;
1059            }
1060            windows.push(RateLimitWindow {
1061                status: sanitize_window_label(
1062                    w.get("status")
1063                        .and_then(|v| v.as_str())
1064                        .unwrap_or("unknown"),
1065                ),
1066                window_type: sanitize_window_label(name),
1067                utilization: w.get("utilization").and_then(serde_json::Value::as_f64),
1068                resets_at: w.get("resetsAt").and_then(serde_json::Value::as_i64),
1069            });
1070        }
1071    }
1072    windows
1073}
1074
1075/// Concatenate text content from all `type:assistant` NDJSON messages in
1076/// the stream.  Used as a fallback when the `type:result` envelope text
1077/// does not contain valid AgentResponse JSON but an earlier assistant turn
1078/// might have emitted it.
1079pub fn collect_assistant_messages_text(ndjson: &str) -> String {
1080    let mut parts: Vec<String> = Vec::new();
1081    for line in ndjson.trim().lines() {
1082        let line = line.trim();
1083        if line.is_empty() {
1084            continue;
1085        }
1086        let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
1087            continue;
1088        };
1089        if val.get("type").and_then(|v| v.as_str()) != Some("assistant") {
1090            continue;
1091        }
1092        if let Some(content) = val
1093            .get("message")
1094            .and_then(|m| m.get("content"))
1095            .and_then(|c| c.as_array())
1096        {
1097            for item in content {
1098                if item.get("type").and_then(|v| v.as_str()) == Some("text")
1099                    && let Some(text) = item.get("text").and_then(|v| v.as_str())
1100                {
1101                    let t = text.trim();
1102                    if !t.is_empty() {
1103                        parts.push(t.to_string());
1104                    }
1105                }
1106            }
1107        }
1108    }
1109    parts.join("\n")
1110}
1111
1112#[cfg(test)]
1113mod tests {
1114    use super::*;
1115    use crate::engine::cooldown;
1116    use crate::engine::runner::agents::fixture;
1117
1118    fn runner() -> ClaudeRunner {
1119        ClaudeRunner::new("claude")
1120    }
1121
1122    #[test]
1123    fn error_envelope_uses_errors_array_when_result_missing() {
1124        let raw = r#"{"type":"result","subtype":"error_during_execution","is_error":true,"errors":["API error (status 402 Payment Required): usage balance exhausted"]}"#;
1125        match runner().parse_response(raw) {
1126            Err(AgentError::AgentFailed { message } | AgentError::Auth { message }) => {
1127                assert!(cooldown::detect_credit_exhaustion(&message).is_some());
1128            }
1129            other => panic!("unexpected: {other:?}"),
1130        }
1131    }
1132
1133    #[test]
1134    fn error_envelope_falls_back_to_subtype() {
1135        let raw = r#"{"type":"result","subtype":"error_during_execution","is_error":true}"#;
1136        match runner().parse_response(raw) {
1137            Err(AgentError::AgentFailed { message }) => {
1138                assert_eq!(message, "error_during_execution");
1139            }
1140            other => panic!("unexpected: {other:?}"),
1141        }
1142    }
1143
1144    #[test]
1145    fn parse_claude_envelope_success() {
1146        let raw = r#"{
1147            "type": "result",
1148            "subtype": "success",
1149            "is_error": false,
1150            "duration_ms": 2006,
1151            "result": "{\"status\":\"done\",\"summary\":\"hello\",\"accomplished\":[],\"remaining\":[],\"files\":[]}",
1152            "usage": {"input_tokens": 10, "output_tokens": 78},
1153            "permission_denials": []
1154        }"#;
1155
1156        let parsed = runner().parse_response(raw).unwrap();
1157        assert_eq!(parsed.response.status, "done");
1158        assert_eq!(parsed.response.summary, "hello");
1159        assert_eq!(parsed.input_tokens, Some(10));
1160        assert_eq!(parsed.output_tokens, Some(78));
1161        assert_eq!(parsed.duration_ms, Some(2006));
1162    }
1163
1164    #[test]
1165    fn parse_claude_envelope_with_markdown_result() {
1166        let raw = r#"{
1167            "type": "result",
1168            "subtype": "success",
1169            "is_error": false,
1170            "duration_ms": 5000,
1171            "result": "```json\n{\"status\": \"done\", \"summary\": \"fixed bug\"}\n```",
1172            "usage": {"input_tokens": 100, "output_tokens": 50},
1173            "permission_denials": ["Bash(rm *)"]
1174        }"#;
1175
1176        let parsed = runner().parse_response(raw).unwrap();
1177        assert_eq!(parsed.response.status, "done");
1178        assert_eq!(parsed.response.summary, "fixed bug");
1179    }
1180
1181    #[test]
1182    fn parse_claude_envelope_error() {
1183        let raw = r#"{
1184            "type": "result",
1185            "subtype": "error",
1186            "is_error": true,
1187            "result": "credit balance too low",
1188            "usage": {},
1189            "permission_denials": []
1190        }"#;
1191
1192        let err = runner().parse_response(raw).unwrap_err();
1193        assert!(matches!(err, AgentError::Auth { .. }));
1194    }
1195
1196    #[test]
1197    fn parse_claude_envelope_rate_limit_error() {
1198        let raw = r#"{
1199            "type": "result",
1200            "subtype": "error",
1201            "is_error": true,
1202            "result": "rate limit exceeded, please try again later",
1203            "usage": {},
1204            "permission_denials": []
1205        }"#;
1206
1207        let err = runner().parse_response(raw).unwrap_err();
1208        assert!(matches!(err, AgentError::RateLimit { .. }));
1209    }
1210
1211    #[test]
1212    fn parse_envelope_no_false_positive_from_work_product_result() {
1213        // Regression test for issue #1292: when is_error=false but the result
1214        // text contains rate-limit keywords (agent describing work it did),
1215        // parse_response must NOT return a RateLimit error.
1216        //
1217        // Fix for issue #1377: when parser::parse fails on plain-text output,
1218        // synthesize_response_from_text is tried and tokens are preserved.
1219        let raw = r#"{"type":"result","subtype":"success","is_error":false,"duration_ms":1000,"result":"Added detect_rate_limit and quota exceeded patterns","usage":{"input_tokens":10,"output_tokens":5}}"#.to_string();
1220        // Plain-text result with rate-limit keywords: parser::parse fails, but
1221        // synthesis succeeds — result must be Ok (tokens preserved) not RateLimit.
1222        let parsed = runner()
1223            .parse_response(&raw)
1224            .expect("plain-text work product must synthesize successfully");
1225        // Tokens must be preserved from the envelope (issue #1377)
1226        assert_eq!(
1227            parsed.input_tokens,
1228            Some(10),
1229            "input_tokens must be preserved"
1230        );
1231        assert_eq!(
1232            parsed.output_tokens,
1233            Some(5),
1234            "output_tokens must be preserved"
1235        );
1236    }
1237
1238    #[test]
1239    fn parse_direct_json_no_envelope() {
1240        let raw =
1241            r#"{"status":"done","summary":"hello","accomplished":[],"remaining":[],"files":[]}"#;
1242
1243        let parsed = runner().parse_response(raw).unwrap();
1244        assert_eq!(parsed.response.status, "done");
1245        assert!(parsed.input_tokens.is_none());
1246    }
1247
1248    #[test]
1249    fn parse_empty_response() {
1250        let err = runner().parse_response("").unwrap_err();
1251        assert!(matches!(err, AgentError::InvalidResponse { .. }));
1252    }
1253
1254    #[test]
1255    fn classify_error_rate_limit() {
1256        let err = runner().classify_error(1, "", "429 Too Many Requests");
1257        assert!(matches!(err, AgentError::RateLimit { .. }));
1258    }
1259
1260    #[test]
1261    fn classify_error_detects_session_limit_from_mid_stream_system_event() {
1262        // Regression test for issue #3272: Claude session limit errors appear as
1263        // `type:system` NDJSON events mid-stream, not as `type:result` lines with
1264        // `is_error:true`. When significant work product exists before and after
1265        // the system event, it is outside both head and tail scan windows in
1266        // `classify_from_text`. The `classify_error` function must extract the
1267        // error message from the system event and prepend it to the combined text.
1268        let header_events = "{\"type\":\"conversation\",\"subtype\":\"init\"}\n\
1269             {\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"I'll work on this task.\"}]}}\n"
1270            .repeat(80);
1271        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)"}}"#;
1272        let work_product = "{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"Here is the implementation...\"}]}}\n"
1273            .repeat(80);
1274        let stdout = format!("{header_events}{system_event}\n{work_product}");
1275        // Verify the system event is deep enough to miss head and tail scans.
1276        assert!(
1277            stdout.len() > 6000,
1278            "test stdout must exceed combined head+tail windows, got {} bytes",
1279            stdout.len()
1280        );
1281        let err = runner().classify_error(1, &stdout, "");
1282        assert!(
1283            matches!(err, AgentError::RateLimit { .. }),
1284            "session limit system event mid-stream must be detected, got: {err:?}"
1285        );
1286        let msg = err.to_string();
1287        assert!(
1288            msg.contains("session limit"),
1289            "error message should contain the rate limit reason, got: {msg}"
1290        );
1291    }
1292
1293    #[test]
1294    fn classify_error_killed_run_with_429_in_uuid_hex_group_is_not_rate_limit() {
1295        // Regression for issue #3956: `-429c-` in a hook id labelled a SIGTERM run RateLimit
1296        let hook = r#"{"type":"system","subtype":"hook_response","hook_id":"18db61b6-7b72-429c-8279-fae3089bf565"}"#;
1297        let prose = "the first lazy solution that works is the right one.\n".repeat(80);
1298        let stdout = format!("{hook}\n{prose}");
1299        assert!(stdout.len() > 3000);
1300        for code in [143, 137, 1] {
1301            let err = runner().classify_error(code, &stdout, "");
1302            assert!(
1303                !matches!(err, AgentError::RateLimit { .. }),
1304                "exit {code} must not classify as RateLimit, got: {err:?}"
1305            );
1306        }
1307        let err = runner().classify_error(143, &stdout, "");
1308        assert!(
1309            matches!(err, AgentError::Interrupted { .. }),
1310            "got: {err:?}"
1311        );
1312    }
1313
1314    #[test]
1315    fn classify_error_402_envelope_not_masked_by_429_in_hook_uuid() {
1316        // Regression for issue #3760: a 4295 hook UUID in the first 3000 bytes
1317        // classified a 402 envelope as a rate limit whose message was hook prose
1318        let hook = r#"{"type":"system","subtype":"init","hook":"SessionStart","uuid":"a1b2c3d4-4295-4e5f-8a9b-0c1d2e3f4a5b","outputTokens":429}"#;
1319        let hook_prose = "on. The first lazy solution that works is the\nright one once you actually know what the change has to touch.\n\n**Build the smallest thing that can fail.**\n";
1320        let padding = hook_prose.repeat(40);
1321        let result_line = r#"{"type":"result","is_error":true,"terminal_reason":"api_error","api_error_status":402,"subtype":"success","result":"API Error: 402 insufficient balance (1008)"}"#;
1322        let stdout = format!("{hook}\n{padding}\n{result_line}\n");
1323        assert!(
1324            stdout.len() > 3000,
1325            "fixture must put the 4295 UUID inside the 3000-byte head, got {} bytes",
1326            stdout.len()
1327        );
1328        let err = runner().classify_error(1, &stdout, "");
1329        assert!(
1330            matches!(err, AgentError::Auth { .. }),
1331            "402 envelope must classify as Auth, got: {err:?}"
1332        );
1333        let msg = err.to_string();
1334        assert!(
1335            msg.contains("insufficient balance"),
1336            "stored error must keep the 402 text, got: {msg}"
1337        );
1338    }
1339
1340    #[test]
1341    fn classify_error_prefers_clean_result_text_over_byte_truncated_tail() {
1342        // Regression test for issue #3577: a well-formed `type:result`
1343        // envelope with `is_error:true` was correctly extracted into
1344        // `error_result`, but `classify_from_text`'s generic Unknown
1345        // fallback then re-truncates the combined stdout+stderr to its last
1346        // 300 bytes — which, once enough preceding NDJSON pushes the result
1347        // line's start past that window, cuts it off mid-field-name (e.g.
1348        // `"is_error"` becomes `"i_error"`). The stored error ends up a
1349        // garbled JSON fragment instead of the clean message, and (in the
1350        // fallback.rs non-zero-exit path) skips the model cooldown that the
1351        // AgentFailed branch applies.
1352        let padding = "{\"type\":\"system\",\"subtype\":\"init\"}\n".repeat(50);
1353        let result_line = r#"{"is_error":true,"duration_api_ms":0,"num_turns":1,"stop_reason":"stop_sequence","session_id":"32a7c67c","total_cost_usd":0,"usage":{},"modelUsage":{},"permission_denials":[],"terminal_reason":"api_error","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subtype":"success","api_error_status":null,"result":"Failed to authenticate: OAuth session expired and could not be refreshed","type":"result","duration_ms":141,"uuid":"fe0ccff2-54d3-47cd-b5ba-a82f99a72b45"}"#;
1354        let stdout = format!("{padding}{result_line}\n");
1355        // Sanity check: the message text itself is not caught by any of the
1356        // specific keyword detectors (auth/rate_limit/context_overflow), so
1357        // without the fix this must fall to the generic Unknown branch.
1358        assert!(
1359            stdout.len() > 300,
1360            "test stdout must exceed the tail-truncation window"
1361        );
1362
1363        let err = runner().classify_error(1, &stdout, "");
1364        assert!(
1365            matches!(err, AgentError::AgentFailed { .. }),
1366            "expected AgentFailed with the clean message, got: {err:?}"
1367        );
1368        let msg = err.to_string();
1369        assert_eq!(
1370            msg,
1371            "agent failed: Failed to authenticate: OAuth session expired and could not be refreshed",
1372            "stored error must be the clean result text, not a byte-truncated JSON fragment"
1373        );
1374        assert!(
1375            !msg.contains("i_error"),
1376            "stored error must not contain the byte-truncated JSON fragment, got: {msg}"
1377        );
1378    }
1379
1380    #[test]
1381    fn classify_error_timeout() {
1382        let err = runner().classify_error(124, "", "");
1383        assert!(matches!(err, AgentError::Timeout { .. }));
1384    }
1385
1386    #[test]
1387    fn extract_usage_from_model_usage() {
1388        let response_json: serde_json::Value = serde_json::json!({
1389            "modelUsage": {
1390                "claude-haiku-4-5-20251001": {
1391                    "inputTokens": 1000,
1392                    "outputTokens": 500
1393                }
1394            }
1395        });
1396        let envelope = response_json.as_object().unwrap();
1397        let (input, output) = extract_usage(envelope);
1398        assert_eq!(input, Some(1000));
1399        assert_eq!(output, Some(500));
1400    }
1401
1402    #[test]
1403    fn build_command_skips_an_empty_model() {
1404        let r = runner();
1405        let perms = PermissionRules {
1406            autonomous: true,
1407            sandbox: SandboxLevel::WorkspaceWrite,
1408            disallowed_tools: vec![],
1409            allowed_tools: vec![],
1410            allowed_edit_paths: vec![],
1411            deny_read_only: false,
1412            extra_writable_dirs: vec![],
1413        };
1414        for m in ["", "  "] {
1415            let cmd = r.build_command(Some(m), "", "/tmp/sys.txt", "/tmp/msg.txt", &perms);
1416            assert!(!cmd.contains("--model"), "{cmd}");
1417        }
1418    }
1419
1420    #[test]
1421    fn build_command_with_model() {
1422        let r = runner();
1423        let perms = PermissionRules {
1424            autonomous: true,
1425            sandbox: SandboxLevel::WorkspaceWrite,
1426            disallowed_tools: vec!["Bash(rm *)".to_string()],
1427            allowed_tools: vec![],
1428            allowed_edit_paths: vec![],
1429            deny_read_only: false,
1430            extra_writable_dirs: vec![],
1431        };
1432        let cmd = r.build_command(
1433            Some("opus"),
1434            "timeout 1800",
1435            "/tmp/sys.txt",
1436            "/tmp/msg.txt",
1437            &perms,
1438        );
1439        assert!(cmd.contains("--model 'opus'"));
1440        assert!(cmd.contains("claude -p"));
1441        assert!(cmd.contains("--output-format stream-json"));
1442        assert!(cmd.contains("--permission-mode bypassPermissions"));
1443        assert!(cmd.contains("--disallowedTools 'Bash(rm *)'"));
1444    }
1445
1446    #[test]
1447    fn build_command_supervised_mode() {
1448        let r = runner();
1449        let perms = PermissionRules {
1450            autonomous: false,
1451            sandbox: SandboxLevel::WorkspaceWrite,
1452            disallowed_tools: vec![],
1453            allowed_tools: vec![],
1454            allowed_edit_paths: vec![],
1455            deny_read_only: false,
1456            extra_writable_dirs: vec![],
1457        };
1458        let cmd = r.build_command(None, "", "/tmp/sys.txt", "/tmp/msg.txt", &perms);
1459        assert!(cmd.contains("--permission-mode acceptEdits"));
1460    }
1461
1462    #[test]
1463    fn a_read_only_chat_runs_its_allowlist_and_nothing_else() {
1464        let r = runner();
1465        let perms = PermissionRules::read_only(vec![
1466            "Read".to_string(),
1467            "Bash(orch task list:*)".to_string(),
1468        ]);
1469        let cmd = r.build_command(None, "", "/tmp/sys.txt", "/tmp/msg.txt", &perms);
1470        assert!(cmd.contains("--permission-mode dontAsk"), "{cmd}");
1471        assert!(
1472            cmd.contains("--restricted"),
1473            "the operator's settings stay out: {cmd}"
1474        );
1475        assert!(cmd.contains("--strict-mcp-config"), "no MCP server: {cmd}");
1476        assert!(
1477            cmd.contains("--tools 'Read,Bash'"),
1478            "only the listed kinds: {cmd}"
1479        );
1480        assert!(
1481            cmd.contains("--allowedTools 'Read,Bash(orch task list:*)'"),
1482            "the exact allowlist: {cmd}"
1483        );
1484        assert!(
1485            cmd.contains("--append-system-prompt-file \"/tmp/sys.txt\""),
1486            "the prompt's content, not its path: {cmd}"
1487        );
1488        assert!(!cmd.contains("bypassPermissions"), "{cmd}");
1489    }
1490
1491    #[test]
1492    fn build_command_allowed_edit_paths_scopes_edit_write() {
1493        let r = runner();
1494        let perms = PermissionRules {
1495            autonomous: true,
1496            sandbox: SandboxLevel::WorkspaceWrite,
1497            disallowed_tools: vec![],
1498            allowed_tools: vec![
1499                "Edit".to_string(),
1500                "Write".to_string(),
1501                "Read".to_string(),
1502                "Bash".to_string(),
1503            ],
1504            allowed_edit_paths: vec![PathBuf::from("/home/user/worktree")],
1505            deny_read_only: false,
1506            extra_writable_dirs: vec![],
1507        };
1508        let cmd = r.build_command(None, "", "/tmp/sys.txt", "/tmp/msg.txt", &perms);
1509
1510        // Edit/Write should be scoped to the worktree path
1511        assert!(
1512            cmd.contains("Edit(/home/user/worktree/*)"),
1513            "expected scoped Edit, got: {cmd}"
1514        );
1515        assert!(
1516            cmd.contains("Write(/home/user/worktree/*)"),
1517            "expected scoped Write, got: {cmd}"
1518        );
1519
1520        // Read and Bash should not be scoped
1521        assert!(
1522            cmd.contains(",Read,") || cmd.contains("'Read,") || cmd.contains(",Read'"),
1523            "expected unrestricted Read, got: {cmd}"
1524        );
1525        assert!(
1526            cmd.contains(",Bash,") || cmd.contains("'Bash,") || cmd.contains(",Bash'"),
1527            "expected unrestricted Bash, got: {cmd}"
1528        );
1529    }
1530
1531    #[test]
1532    fn kimi_runner_name() {
1533        let r = ClaudeRunner::new("kimi");
1534        assert_eq!(r.name(), "kimi");
1535    }
1536
1537    // ── Fixture-based tests ─────────────────────────────────────
1538
1539    #[test]
1540    fn fixture_claude_success() {
1541        let raw = fixture::load(include_str!(
1542            "../../../../tests/fixtures/claude_success.json"
1543        ));
1544        let parsed = runner().parse_response(&raw.stdout).unwrap();
1545        assert_eq!(parsed.response.status, "done");
1546        assert!(parsed.response.summary.contains("Implemented"));
1547        assert_eq!(parsed.response.accomplished.len(), 2);
1548        assert_eq!(parsed.input_tokens, Some(15000));
1549        assert_eq!(parsed.output_tokens, Some(3500));
1550        assert_eq!(parsed.duration_ms, Some(45000));
1551    }
1552
1553    #[test]
1554    fn fixture_claude_rate_limit() {
1555        let raw = fixture::load(include_str!(
1556            "../../../../tests/fixtures/claude_error_rate_limit.json"
1557        ));
1558        let err = runner().parse_response(&raw.stdout).unwrap_err();
1559        assert!(matches!(err, AgentError::RateLimit { .. }), "got: {err:?}");
1560    }
1561
1562    // ── NDJSON / stream-json fixtures ────────────────────────────
1563
1564    #[test]
1565    fn fixture_claude_stream_error() {
1566        let raw = fixture::load(include_str!(
1567            "../../../../tests/fixtures/claude_stream_error.jsonl"
1568        ));
1569        let err = runner().parse_response(&raw.stdout).unwrap_err();
1570        assert!(matches!(err, AgentError::Auth { .. }), "got: {err:?}");
1571    }
1572
1573    #[test]
1574    fn fixture_claude_stream_thinking_block_conflict() {
1575        let raw = fixture::load(include_str!(
1576            "../../../../tests/fixtures/claude_stream_thinking_block_conflict.jsonl"
1577        ));
1578        let err = runner().parse_response(&raw.stdout).unwrap_err();
1579        assert!(
1580            matches!(err, AgentError::ThinkingBlockConflict { .. }),
1581            "expected ThinkingBlockConflict, got: {err:?}"
1582        );
1583    }
1584
1585    #[test]
1586    fn classify_error_thinking_block_conflict_from_stderr() {
1587        // The error can also surface through classify_error() when the claude
1588        // process exits non-zero with the message in stdout/stderr.
1589        let stderr = "claude failed: API Error: 400 messages.1.content.3: `thinking` or `redacted_thinking` blocks in the latest assistant message cannot be modified. These blocks must remain as they were in the original response.";
1590        let err = runner().classify_error(1, "", stderr);
1591        assert!(
1592            matches!(err, AgentError::ThinkingBlockConflict { .. }),
1593            "expected ThinkingBlockConflict, got: {err:?}"
1594        );
1595    }
1596
1597    #[test]
1598    fn thinking_block_conflict_does_not_match_unrelated_text() {
1599        // Ensure the pattern is specific enough to not false-positive on
1600        // work product that mentions "thinking" or "blocks".
1601        let unrelated = "I was thinking about how to handle blocks of code in the response.";
1602        let err = runner().classify_error(1, "", unrelated);
1603        assert!(
1604            !matches!(err, AgentError::ThinkingBlockConflict { .. }),
1605            "should not classify unrelated text as ThinkingBlockConflict, got: {err:?}"
1606        );
1607    }
1608
1609    #[test]
1610    fn parse_ndjson_with_intermediate_events() {
1611        // Parser must ignore intermediate events and only look at the result line
1612        let raw = concat!(
1613            r#"{"type":"system","subtype":"init"}"#,
1614            "\n",
1615            r#"{"type":"assistant","message":{"role":"assistant","content":[]}}"#,
1616            "\n",
1617            r#"{"type":"tool_use","tool":{"name":"Read","input":{}}}"#,
1618            "\n",
1619            r#"{"type":"result","subtype":"success","is_error":false,"duration_ms":1000,"result":"{\"status\":\"done\",\"summary\":\"streamed\",\"accomplished\":[],\"remaining\":[],\"files\":[]}","usage":{"input_tokens":5,"output_tokens":10}}"#,
1620            "\n"
1621        );
1622        let parsed = runner().parse_response(raw).unwrap();
1623        assert_eq!(parsed.response.status, "done");
1624        assert_eq!(parsed.response.summary, "streamed");
1625        assert_eq!(parsed.input_tokens, Some(5));
1626        assert_eq!(parsed.output_tokens, Some(10));
1627    }
1628
1629    #[test]
1630    fn parse_ndjson_skips_malformed_lines() {
1631        // Malformed intermediate lines should be ignored; result line still parsed
1632        let raw = concat!(
1633            "not valid json\n",
1634            r#"{"type":"partial_update","data":"something"}"#,
1635            "\n",
1636            r#"{"type":"result","subtype":"success","is_error":false,"duration_ms":500,"result":"{\"status\":\"done\",\"summary\":\"ok\",\"accomplished\":[],\"remaining\":[],\"files\":[]}","usage":{"input_tokens":1,"output_tokens":2}}"#,
1637            "\n"
1638        );
1639        let parsed = runner().parse_response(raw).unwrap();
1640        assert_eq!(parsed.response.status, "done");
1641        assert_eq!(parsed.response.summary, "ok");
1642    }
1643
1644    #[test]
1645    fn parse_single_line_json_backward_compat() {
1646        // Single-line JSON (--output-format json) still works
1647        let raw = r#"{"type":"result","subtype":"success","is_error":false,"duration_ms":2000,"result":"{\"status\":\"done\",\"summary\":\"backward compat\",\"accomplished\":[],\"remaining\":[],\"files\":[]}","usage":{"input_tokens":50,"output_tokens":25}}"#;
1648        let parsed = runner().parse_response(raw).unwrap();
1649        assert_eq!(parsed.response.status, "done");
1650        assert_eq!(parsed.response.summary, "backward compat");
1651        assert_eq!(parsed.input_tokens, Some(50));
1652        assert_eq!(parsed.output_tokens, Some(25));
1653    }
1654
1655    // ── Kimi / MiniMax (Claude-compatible wrappers) ───────────────
1656
1657    #[test]
1658    fn kimi_parses_claude_envelope() {
1659        let r = ClaudeRunner::new("kimi");
1660        let raw = r#"{
1661            "type": "result",
1662            "subtype": "success",
1663            "is_error": false,
1664            "duration_ms": 3000,
1665            "result": "{\"status\":\"done\",\"summary\":\"kimi did it\",\"accomplished\":[\"task\"],\"remaining\":[],\"files\":[\"a.rs\"]}",
1666            "usage": {"input_tokens": 200, "output_tokens": 100}
1667        }"#;
1668
1669        let parsed = r.parse_response(raw).unwrap();
1670        assert_eq!(parsed.response.status, "done");
1671        assert_eq!(parsed.response.summary, "kimi did it");
1672    }
1673
1674    #[test]
1675    fn minimax_parses_claude_envelope() {
1676        let r = ClaudeRunner::new("minimax");
1677        assert_eq!(r.name(), "minimax");
1678        let raw = r#"{
1679            "type": "result",
1680            "subtype": "success",
1681            "is_error": false,
1682            "result": "{\"status\":\"done\",\"summary\":\"minimax did it\",\"accomplished\":[],\"remaining\":[],\"files\":[]}",
1683            "usage": {}
1684        }"#;
1685
1686        let parsed = r.parse_response(raw).unwrap();
1687        assert_eq!(parsed.response.status, "done");
1688    }
1689
1690    #[test]
1691    fn kimi_build_command_uses_kimi_binary() {
1692        let r = ClaudeRunner::new("kimi");
1693        let perms = PermissionRules {
1694            autonomous: true,
1695            sandbox: SandboxLevel::WorkspaceWrite,
1696            disallowed_tools: vec![],
1697            allowed_tools: vec![],
1698            allowed_edit_paths: vec![],
1699            deny_read_only: false,
1700            extra_writable_dirs: vec![],
1701        };
1702        let cmd = r.build_command(
1703            Some("sonnet"),
1704            "timeout 1800",
1705            "/tmp/sys.txt",
1706            "/tmp/msg.txt",
1707            &perms,
1708        );
1709        assert!(cmd.contains("kimi -p"), "expected kimi binary, got: {cmd}");
1710        assert!(cmd.contains("--model 'sonnet'"));
1711    }
1712
1713    #[test]
1714    fn build_command_with_allowed_tools() {
1715        let r = runner();
1716        let perms = PermissionRules {
1717            autonomous: true,
1718            sandbox: SandboxLevel::WorkspaceWrite,
1719            disallowed_tools: vec!["Bash(rm *)".to_string()], // should be ignored
1720            allowed_tools: vec![
1721                "Edit".to_string(),
1722                "Write".to_string(),
1723                "Read".to_string(),
1724                "Bash".to_string(),
1725                "Grep".to_string(),
1726                "git".to_string(),
1727                "npm".to_string(),
1728            ],
1729            allowed_edit_paths: vec![],
1730            deny_read_only: false,
1731            extra_writable_dirs: vec![],
1732        };
1733        let cmd = r.build_command(None, "", "/tmp/sys.txt", "/tmp/msg.txt", &perms);
1734
1735        // Should use --allowedTools instead of --disallowedTools
1736        assert!(
1737            cmd.contains("--allowedTools"),
1738            "expected --allowedTools flag, got: {cmd}"
1739        );
1740        assert!(
1741            !cmd.contains("--disallowedTools"),
1742            "should not have --disallowedTools when allowed_tools is set, got: {cmd}"
1743        );
1744
1745        // Native tools pass through as-is
1746        assert!(cmd.contains("Edit"), "missing Edit tool");
1747        assert!(cmd.contains("Write"), "missing Write tool");
1748        assert!(cmd.contains("Bash"), "missing Bash tool");
1749
1750        // CLI commands become Bash(<cmd> *) patterns
1751        assert!(
1752            cmd.contains("Bash(git *)"),
1753            "missing Bash(git *) pattern, got: {cmd}"
1754        );
1755        assert!(
1756            cmd.contains("Bash(npm *)"),
1757            "missing Bash(npm *) pattern, got: {cmd}"
1758        );
1759    }
1760
1761    #[test]
1762    fn build_command_allowed_tools_empty_falls_back_to_disallowed() {
1763        let r = runner();
1764        let perms = PermissionRules {
1765            autonomous: true,
1766            sandbox: SandboxLevel::WorkspaceWrite,
1767            disallowed_tools: vec!["Bash(rm *)".to_string()],
1768            allowed_tools: vec![], // empty = use disallowed_tools
1769            allowed_edit_paths: vec![],
1770            deny_read_only: false,
1771            extra_writable_dirs: vec![],
1772        };
1773        let cmd = r.build_command(None, "", "/tmp/sys.txt", "/tmp/msg.txt", &perms);
1774
1775        assert!(
1776            cmd.contains("--disallowedTools"),
1777            "should fall back to --disallowedTools when allowed_tools is empty, got: {cmd}"
1778        );
1779        assert!(
1780            !cmd.contains("--allowedTools"),
1781            "should not have --allowedTools when empty, got: {cmd}"
1782        );
1783    }
1784
1785    #[test]
1786    fn translate_allowed_tools_categorizes_correctly() {
1787        let allowed = vec![
1788            "Edit".to_string(),
1789            "Bash".to_string(),
1790            "Grep".to_string(),
1791            "git".to_string(),
1792            "cargo".to_string(),
1793            "WebFetch".to_string(),
1794        ];
1795        // No allowed_edit_paths → Edit passes through as-is
1796        let result = translate_allowed_tools(&allowed, &[]);
1797        assert_eq!(
1798            result,
1799            vec![
1800                "Edit",
1801                "Bash",
1802                "Grep",
1803                "Bash(git *)",
1804                "Bash(cargo *)",
1805                "WebFetch"
1806            ]
1807        );
1808    }
1809
1810    #[test]
1811    fn translate_allowed_tools_scopes_edit_write() {
1812        let allowed = vec!["Edit".to_string(), "Write".to_string(), "Read".to_string()];
1813        let paths = vec![PathBuf::from("/tmp/worktree")];
1814        let result = translate_allowed_tools(&allowed, &paths);
1815        assert_eq!(
1816            result,
1817            vec!["Edit(/tmp/worktree/*)", "Write(/tmp/worktree/*)", "Read"]
1818        );
1819    }
1820
1821    #[test]
1822    fn classify_error_overloaded_529() {
1823        // Claude 529 overloaded error
1824        let err = runner().classify_error(1, "", "overloaded_error: 529");
1825        assert!(matches!(err, AgentError::RateLimit { .. }), "got: {err:?}");
1826    }
1827
1828    #[test]
1829    fn classify_error_context_length() {
1830        let err = runner().classify_error(1, "", "context_length_exceeded: max 200000 tokens");
1831        assert!(
1832            matches!(err, AgentError::ContextOverflow { .. }),
1833            "got: {err:?}"
1834        );
1835    }
1836
1837    // ── extract_text ─────────────────────────────────────────────
1838
1839    /// Claude stream-json: extract_text returns the inner result text for review parsing.
1840    #[test]
1841    fn extract_text_stream_json_returns_result_field() {
1842        let raw = concat!(
1843            r#"{"type":"system","subtype":"init","session_id":"s1"}"#,
1844            "\n",
1845            r#"{"type":"assistant","message":{"content":[{"type":"text","text":"Reviewing..."}]}}"#,
1846            "\n",
1847            r#"{"type":"result","subtype":"success","is_error":false,"result":"{\"decision\":\"approve\",\"notes\":\"LGTM\",\"test_results\":\"pass\",\"issues\":[]}","usage":{"input_tokens":100,"output_tokens":20}}"#,
1848        );
1849        let text = runner().extract_text(raw).unwrap();
1850        assert_eq!(
1851            text,
1852            r#"{"decision":"approve","notes":"LGTM","test_results":"pass","issues":[]}"#
1853        );
1854    }
1855
1856    /// Claude stream-json with markdown-wrapped ReviewResponse in result field.
1857    #[test]
1858    fn extract_text_stream_json_markdown_result() {
1859        let review_json =
1860            r#"```json\n{"decision":"request_changes","notes":"Fix it","issues":[]}\n```"#;
1861        let result_line = format!(
1862            r#"{{"type":"result","subtype":"success","is_error":false,"result":"{review_json}","usage":{{"input_tokens":10,"output_tokens":5}}}}"#
1863        );
1864        let raw = format!(
1865            "{}\n{}",
1866            r#"{"type":"system","subtype":"init","session_id":"s1"}"#, result_line
1867        );
1868        let text = runner().extract_text(&raw).unwrap();
1869        assert!(
1870            text.contains("request_changes"),
1871            "expected review JSON in result, got: {text}"
1872        );
1873    }
1874
1875    /// Claude stream-json error (is_error=true, rate limit): extract_text propagates RateLimit.
1876    #[test]
1877    fn extract_text_stream_json_rate_limit_propagates() {
1878        let raw = concat!(
1879            r#"{"type":"system","subtype":"init","session_id":"s1"}"#,
1880            "\n",
1881            r#"{"type":"result","subtype":"error","is_error":true,"result":"rate limit exceeded: 429 Too Many Requests","usage":{"input_tokens":0,"output_tokens":0}}"#,
1882        );
1883        let err = runner().extract_text(raw).unwrap_err();
1884        assert!(
1885            matches!(err, AgentError::RateLimit { .. }),
1886            "expected RateLimit, got: {err:?}"
1887        );
1888    }
1889
1890    #[test]
1891    fn extract_stream_json_fallbacks_to_opencode_extractor_on_leading_init() {
1892        // Some Claude wrappers emit a leading system/init envelope and then
1893        // place the real JSON payload inside an assistant message content array
1894        // (no final "type":"result" line). Ensure our extractor falls back
1895        // to the opencode-style NDJSON scanner and returns the inner JSON.
1896        let raw = concat!(
1897            r#"{"type":"system","subtype":"init","session_id":"s1"}"#,
1898            "\n",
1899            // The inner JSON must be escaped inside the outer JSON string
1900            r#"{"type":"assistant","message":{"content":[{"type":"text","text":"{\"status\":\"done\",\"summary\":\"fallback\",\"accomplished\":[],\"remaining\":[],\"files\":[]}"}]}}"#,
1901        );
1902
1903        let text = extract_stream_json_result_text(raw).expect("should fallback and extract JSON");
1904        let parsed: serde_json::Value =
1905            serde_json::from_str(&text).expect("extracted text must be JSON");
1906        assert_eq!(parsed["status"], "done");
1907        assert_eq!(parsed["summary"], "fallback");
1908    }
1909
1910    /// Claude stream-json error (is_error=true, auth): extract_text propagates Auth.
1911    #[test]
1912    fn extract_text_stream_json_auth_error_propagates() {
1913        let raw = concat!(
1914            r#"{"type":"system","subtype":"init","session_id":"s1"}"#,
1915            "\n",
1916            r#"{"type":"result","subtype":"error","is_error":true,"result":"401 Unauthorized: invalid api key","usage":{"input_tokens":0,"output_tokens":0}}"#,
1917        );
1918        let err = runner().extract_text(raw).unwrap_err();
1919        assert!(
1920            matches!(err, AgentError::Auth { .. }),
1921            "expected Auth, got: {err:?}"
1922        );
1923    }
1924
1925    /// extract_text on empty input returns empty string (not an error).
1926    #[test]
1927    fn extract_text_empty_input_returns_empty_ok() {
1928        let text = runner().extract_text("").unwrap();
1929        assert_eq!(text, "");
1930    }
1931
1932    // ── find_claude_result ──────────────────────────────────────
1933
1934    #[test]
1935    fn find_claude_result_success_with_tokens() {
1936        let ndjson = concat!(
1937            r#"{"type":"system","subtype":"init","session_id":"s1"}"#,
1938            "\n",
1939            r#"{"type":"assistant","message":{"content":[{"type":"text","text":"working..."}]}}"#,
1940            "\n",
1941            r#"{"type":"result","subtype":"success","is_error":false,"result":"{\"decision\":\"approve\",\"notes\":\"LGTM\"}","usage":{"input_tokens":1500,"output_tokens":200},"duration_ms":5000}"#,
1942        );
1943        let result = find_claude_result(ndjson).expect("should find result");
1944        assert!(!result.is_error);
1945        assert!(result.result_text.contains("approve"));
1946        assert_eq!(result.input_tokens, Some(1500));
1947        assert_eq!(result.output_tokens, Some(200));
1948        assert_eq!(result.duration_ms, Some(5000));
1949    }
1950
1951    #[test]
1952    fn find_claude_result_reads_total_cost_usd() {
1953        let ndjson = r#"{"type":"result","subtype":"success","is_error":false,"result":"{\"status\":\"done\",\"summary\":\"ok\"}","usage":{"input_tokens":10,"output_tokens":5},"total_cost_usd":0.1234}"#;
1954        let result = find_claude_result(ndjson).expect("should find result");
1955        assert_eq!(result.cost_usd, Some(0.1234));
1956        let parsed = runner().parse_response(ndjson).expect("should parse");
1957        assert_eq!(parsed.cost_usd, Some(0.1234));
1958    }
1959
1960    #[test]
1961    fn find_claude_result_without_a_cost_reports_none() {
1962        let ndjson = r#"{"type":"result","subtype":"success","is_error":false,"result":"ok","usage":{"input_tokens":10,"output_tokens":5}}"#;
1963        let result = find_claude_result(ndjson).expect("should find result");
1964        assert_eq!(result.cost_usd, None);
1965    }
1966
1967    #[test]
1968    fn find_claude_result_error_flag() {
1969        let ndjson = r#"{"type":"result","subtype":"error","is_error":true,"result":"rate limit exceeded","usage":{}}"#;
1970        let result = find_claude_result(ndjson).expect("should find result");
1971        assert!(result.is_error);
1972        assert!(result.result_text.contains("rate limit"));
1973    }
1974
1975    #[test]
1976    fn find_claude_result_error_envelope_with_empty_result_uses_errors() {
1977        // Grok 402: no `result` field, message only in errors[] — must not
1978        // become an empty AgentFailed (issue #3713)
1979        let ndjson = r#"{"type":"result","subtype":"error_during_execution","is_error":true,"num_turns":0,"errors":["Internal error: {\"message\":\"API error (status 402 Payment Required): Grok Build usage balance exhausted\",\"http_status\":402}"]}"#;
1980        let result = find_claude_result(ndjson).expect("should find result");
1981        assert!(result.is_error);
1982        assert!(result.result_text.contains("usage balance exhausted"));
1983        assert!(cooldown::detect_credit_exhaustion(&result.result_text).is_some());
1984    }
1985
1986    #[test]
1987    fn find_claude_result_empty_returns_none() {
1988        assert!(find_claude_result("").is_none());
1989        assert!(find_claude_result("   ").is_none());
1990    }
1991
1992    #[test]
1993    fn find_claude_result_no_result_line_falls_back_to_assistant() {
1994        // MiniMax/Kimi pattern: no type:result, just assistant messages
1995        let ndjson = concat!(
1996            r#"{"type":"system","subtype":"init","model":"MiniMax-M2.7"}"#,
1997            "\n",
1998            r#"{"type":"assistant","message":{"content":[{"type":"text","text":"analysis complete"}],"usage":{"input_tokens":800,"output_tokens":150}}}"#,
1999        );
2000        let result = find_claude_result(ndjson).expect("should fall back to assistant text");
2001        assert!(!result.is_error);
2002        assert_eq!(result.result_text, "analysis complete");
2003        assert_eq!(result.input_tokens, Some(800));
2004        assert_eq!(result.output_tokens, Some(150));
2005    }
2006
2007    #[test]
2008    fn find_claude_result_plain_text_returns_none() {
2009        // Plain text (not NDJSON) should return None
2010        assert!(find_claude_result("just some plain text output").is_none());
2011    }
2012
2013    #[test]
2014    fn strip_tty_control_lines_drops_show_cursor_and_ctrl_d_redraw() {
2015        let redraw = "^D\u{0008}".repeat(20);
2016        let raw = format!(
2017            "{}\n{}\n{}\n{}\n{}",
2018            r#"{"type":"system","subtype":"init"}"#,
2019            r#"{"type":"assistant","message":{"content":[{"type":"text","text":"hello"}]}}"#,
2020            SHOW_CURSOR,
2021            redraw,
2022            r#"{"type":"result","subtype":"success","is_error":false,"result":"{\"decision\":\"approve\",\"notes\":\"LGTM\",\"issues\":[]}"}"#,
2023        );
2024        let cleaned = strip_tty_control_lines(&raw);
2025        assert!(
2026            !cleaned.contains(SHOW_CURSOR),
2027            "show-cursor sequence must be stripped"
2028        );
2029        assert!(
2030            !cleaned.contains('\u{0008}'),
2031            "backspace redraw line must be stripped"
2032        );
2033        assert!(cleaned.contains("\"type\":\"result\""));
2034        assert!(cleaned.contains("hello"));
2035    }
2036
2037    #[test]
2038    fn strip_tty_control_lines_strips_trailing_cursor_on_json_line() {
2039        let line = format!(
2040            r#"{{"type":"result","subtype":"success","is_error":false,"result":"ok"}}{SHOW_CURSOR}"#
2041        );
2042        let cleaned = strip_tty_control_lines(&line);
2043        assert_eq!(
2044            cleaned,
2045            r#"{"type":"result","subtype":"success","is_error":false,"result":"ok"}"#
2046        );
2047    }
2048
2049    #[test]
2050    fn find_claude_result_ignores_trailing_tty_junk() {
2051        let ndjson = format!(
2052            "{}\n{}\n{}",
2053            r#"{"type":"assistant","message":{"content":[{"type":"text","text":"working"}]}}"#,
2054            r#"{"type":"result","subtype":"success","is_error":false,"result":"{\"decision\":\"approve\",\"notes\":\"LGTM\",\"issues\":[]}","usage":{"input_tokens":10,"output_tokens":4}}"#,
2055            SHOW_CURSOR,
2056        );
2057        let result = find_claude_result(&ndjson).expect("result envelope should still parse");
2058        assert!(result.result_text.contains("approve"));
2059        assert_eq!(result.input_tokens, Some(10));
2060    }
2061
2062    #[test]
2063    fn review_session_exited_mid_thought_detects_thinking_without_envelope() {
2064        let ndjson = concat!(
2065            r#"{"type":"system","subtype":"thinking_tokens","tokens":12}"#,
2066            "\n",
2067            r#"{"type":"assistant","message":{"content":[{"type":"text","text":"CI passes. Now verifying callers:"}],"stop_reason":null,"usage":{"output_tokens":0}}}"#,
2068            "\n",
2069            r#"{"type":"assistant","message":{"content":[{"type":"thinking","thinking":"checking lease edge cases"}],"stop_reason":null,"usage":{"output_tokens":0}}}"#,
2070        );
2071        assert!(review_session_exited_mid_thought(ndjson));
2072        assert!(find_ndjson_result_line(ndjson).is_none());
2073    }
2074
2075    #[test]
2076    fn review_session_exited_mid_thought_detects_tool_use_without_envelope() {
2077        let ndjson = r#"{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Read","input":{"file_path":"src/lib.rs"}}]}}"#;
2078        assert!(review_session_exited_mid_thought(ndjson));
2079    }
2080
2081    #[test]
2082    fn review_session_exited_mid_thought_false_when_envelope_present() {
2083        let ndjson = concat!(
2084            r#"{"type":"assistant","message":{"content":[{"type":"thinking","thinking":"done"}]}}"#,
2085            "\n",
2086            r#"{"type":"result","subtype":"success","is_error":false,"result":"{\"decision\":\"approve\",\"notes\":\"LGTM\",\"issues\":[]}"}"#,
2087        );
2088        assert!(!review_session_exited_mid_thought(ndjson));
2089    }
2090
2091    #[test]
2092    fn review_session_exited_mid_thought_false_for_finished_text() {
2093        let ndjson = r#"{"type":"assistant","message":{"content":[{"type":"text","text":"I have finished looking at the code."}]}}"#;
2094        assert!(!review_session_exited_mid_thought(ndjson));
2095    }
2096
2097    #[test]
2098    fn find_claude_result_model_usage() {
2099        let ndjson = r#"{"type":"result","subtype":"success","is_error":false,"result":"done","modelUsage":{"claude-sonnet-4-20250514":{"inputTokens":5000,"outputTokens":1000}},"duration_ms":3000}"#;
2100        let result = find_claude_result(ndjson).expect("should extract modelUsage");
2101        assert_eq!(result.input_tokens, Some(5000));
2102        assert_eq!(result.output_tokens, Some(1000));
2103    }
2104
2105    // ── Regression tests for issue #1387 ──────────────────────────────────────
2106
2107    /// Regression test: when an NDJSON stream has multiple type:result lines —
2108    /// one with JSON in the result field (inner task delegate) and one with
2109    /// plain text (outer session summary) — find_ndjson_result_line must
2110    /// skip the plain-text one and return the JSON one.
2111    #[test]
2112    fn find_ndjson_result_line_skips_plain_text_result() {
2113        // Build test NDJSON using serde_json to avoid string-escaping confusion.
2114        let inner_result = serde_json::json!({"status": "done", "summary": "fix applied"});
2115        let json_result_line = serde_json::json!({
2116            "type": "result",
2117            "subtype": "success",
2118            "is_error": false,
2119            "duration_ms": 273_044,
2120            "result": inner_result.to_string(),
2121            "usage": {"input_tokens": 12, "output_tokens": 1577}
2122        })
2123        .to_string();
2124        let plain_result_line = serde_json::json!({
2125            "type": "result",
2126            "subtype": "success",
2127            "is_error": false,
2128            "duration_ms": 2352,
2129            "result": "All 2352 tests passed.",
2130            "usage": {"input_tokens": 3, "output_tokens": 16}
2131        })
2132        .to_string();
2133        // Concatenate without using concat! to avoid string-escaping headaches.
2134        let mut ndjson = json_result_line;
2135        ndjson.push('\n');
2136        ndjson.push_str(r#"{"type":"system","subtype":"task_notification"}"#);
2137        ndjson.push('\n');
2138        ndjson.push_str(r#"{"type":"system","subtype":"init"}"#);
2139        ndjson.push('\n');
2140        ndjson.push_str(
2141            r#"{"type":"assistant","message":{"content":[{"type":"text","text":"summary here"}]}}"#,
2142        );
2143        ndjson.push('\n');
2144        ndjson.push_str(&plain_result_line);
2145
2146        let line = find_ndjson_result_line(&ndjson)
2147            .expect("should find a result line")
2148            .0;
2149        // Must be the JSON result (inner), not the plain-text one (outer).
2150        let parsed: serde_json::Value =
2151            serde_json::from_str(line).expect("returned line must be valid JSON");
2152        let result_val = parsed.get("result").expect("result field must exist");
2153        assert!(
2154            result_val.is_string(),
2155            "result field must be a JSON string (not plain text), got: {result_val}"
2156        );
2157        let result_str = result_val.as_str().unwrap();
2158        assert!(
2159            result_str.starts_with('{'),
2160            "result must be JSON (object), got: {result_str}"
2161        );
2162        assert!(
2163            !result_str.contains("All 2352 tests passed"),
2164            "must NOT return outer plain-text result: {result_str}"
2165        );
2166    }
2167
2168    /// Regression test: when BOTH result lines have plain-text results (no JSON),
2169    /// find_ndjson_result_line must return the one with more tokens — not the last.
2170    /// This is the actual task 1384 scenario: inner result has 12+1577 tokens,
2171    /// outer confirmation has 3+16 tokens. Must pick the inner one (issue #1387).
2172    #[test]
2173    fn find_ndjson_result_line_prefers_more_tokens_on_plain_text() {
2174        // Build NDJSON where both results are plain text.
2175        let inner_result_line = serde_json::json!({
2176            "type": "result",
2177            "subtype": "success",
2178            "is_error": false,
2179            "duration_ms": 273_044,
2180            "result": "All 2352 tests pass. The fix is clean and correct.",
2181            "usage": {"input_tokens": 12, "output_tokens": 1577}
2182        })
2183        .to_string();
2184        let outer_result_line = serde_json::json!({
2185            "type": "result",
2186            "subtype": "success",
2187            "is_error": false,
2188            "duration_ms": 2352,
2189            "result": "Already retrieved the result — all 2352 tests passed.",
2190            "usage": {"input_tokens": 3, "output_tokens": 16}
2191        })
2192        .to_string();
2193
2194        // Inner result FIRST, outer result LAST (the actual task 1384 ordering).
2195        let ndjson = format!(
2196            "{0}\n{1}\n{2}",
2197            inner_result_line, r#"{"type":"system","subtype":"init"}"#, outer_result_line
2198        );
2199
2200        let (line, tokens) = find_ndjson_result_line(&ndjson).expect("should find a result line");
2201
2202        // Must return the inner result (more tokens), not the outer one.
2203        assert!(
2204            line.contains("The fix is clean"),
2205            "expected inner result (more tokens), got: {line}"
2206        );
2207        // Tokens must match the inner result.
2208        assert_eq!(
2209            tokens,
2210            Some((12, 1577)),
2211            "tokens must be from the inner result"
2212        );
2213    }
2214
2215    /// Regression test: when parse_response encounters plain-text results
2216    /// and falls back to synthesis, tokens from the envelope must be preserved.
2217    #[test]
2218    fn parse_response_preserves_tokens_on_synthesis_fallback() {
2219        // Both results are plain text (no JSON in result field).
2220        // parse_response should synthesize but preserve the envelope tokens.
2221        let ndjson = concat!(
2222            r#"{"type":"result","subtype":"success","is_error":false,"duration_ms":273044,"result":"All 2352 tests pass. The fix is clean and correct.","usage":{"input_tokens":12,"output_tokens":1577}}"#,
2223            "\n",
2224            r#"{"type":"system","subtype":"init"}"#,
2225            "\n",
2226            r#"{"type":"result","subtype":"success","is_error":false,"duration_ms":2352,"result":"Already retrieved the result — all 2352 tests passed.","usage":{"input_tokens":3,"output_tokens":16}}"#,
2227        );
2228
2229        let parsed = runner()
2230            .parse_response(ndjson)
2231            .expect("should parse successfully");
2232
2233        // Must preserve tokens from the inner (higher-token) result.
2234        assert_eq!(
2235            parsed.input_tokens,
2236            Some(12),
2237            "input_tokens must be preserved (not lost on synthesis fallback)"
2238        );
2239        assert_eq!(
2240            parsed.output_tokens,
2241            Some(1577),
2242            "output_tokens must be preserved (not lost on synthesis fallback)"
2243        );
2244    }
2245
2246    #[test]
2247    fn parse_response_uses_inner_json_result_preserving_tokens() {
2248        // Simulates task 1384: outer session says "tests passed" (plain text),
2249        // but inner task delegate result is JSON with tokens.
2250        let ndjson = concat!(
2251            r#"{"type":"result","subtype":"success","is_error":false,"duration_ms":273044,"result":"{\"status\":\"done\",\"summary\":\"fix applied\",\"accomplished\":[\"fix\"],\"remaining\":[],\"files\":[]}","usage":{"input_tokens":12,"output_tokens":1577}}"#,
2252            "\n",
2253            r#"{"type":"system","subtype":"init","session_id":"s1"}"#,
2254            "\n",
2255            r#"{"type":"assistant","message":{"content":[{"type":"text","text":"tests passed"}]}}"#,
2256            "\n",
2257            r#"{"type":"result","subtype":"success","is_error":false,"duration_ms":2352,"result":"All 2352 tests passed.","usage":{"input_tokens":3,"output_tokens":16}}"#,
2258        );
2259
2260        let parsed = runner()
2261            .parse_response(ndjson)
2262            .expect("should parse successfully");
2263
2264        // Must use the inner JSON result (fix applied), not outer plain text.
2265        assert_eq!(
2266            parsed.response.status, "done",
2267            "expected inner JSON result status, got: {:?}",
2268            parsed.response.status
2269        );
2270        assert_eq!(
2271            parsed.response.summary.as_str(),
2272            "fix applied",
2273            "expected inner JSON result summary, got: {:?}",
2274            parsed.response.summary
2275        );
2276        // Tokens must be from the inner result with tokens, not the outer plain-text one.
2277        assert_eq!(
2278            parsed.input_tokens,
2279            Some(12),
2280            "input_tokens must be from inner result (not outer plain-text result)"
2281        );
2282        assert_eq!(
2283            parsed.output_tokens,
2284            Some(1577),
2285            "output_tokens must be from inner result (not outer plain-text result)"
2286        );
2287    }
2288
2289    /// Regression test: when find_ndjson_result_line returns None (no JSON
2290    /// result found), extract_stream_json_result_text must fall back to
2291    /// opencode-style text extraction, not return raw NDJSON.
2292    #[test]
2293    fn extract_text_falls_back_to_opencode_style_when_no_json_result() {
2294        // An NDJSON stream with no type:result at all — just a text event.
2295        let ndjson = concat!(
2296            r#"{"type":"system","subtype":"init","session_id":"s1"}"#,
2297            "\n",
2298            r#"{"type":"assistant","message":{"content":[{"type":"text","text":"All tasks complete"}]}}"#,
2299        );
2300
2301        let text = runner().extract_text(ndjson).expect("should extract text");
2302        // Must extract the assistant message text, not raw NDJSON.
2303        assert!(
2304            text.contains("All tasks complete"),
2305            "expected extracted assistant text, got: {text}"
2306        );
2307        assert!(!text.contains("type"), "must not return raw NDJSON: {text}");
2308    }
2309}
2310
2311/// Claude `stream-json`: calls and text are blocks in `assistant` messages, results in `user` ones
2312pub(crate) fn stream_events(v: &serde_json::Value) -> Vec<StreamEvent> {
2313    let blocks = || v["message"]["content"].as_array().into_iter().flatten();
2314    match json_str(v, "/type") {
2315        "system" if json_str(v, "/subtype") == "init" => vec![StreamEvent::Started {
2316            model: json_str(v, "/model").to_string(),
2317        }],
2318        "assistant" => blocks()
2319            .filter_map(|b| match json_str(b, "/type") {
2320                "text" => Some(StreamEvent::Text(json_str(b, "/text").to_string())),
2321                "thinking" => Some(StreamEvent::Thinking(json_str(b, "/thinking").to_string())),
2322                "tool_use" => Some(StreamEvent::ToolCall {
2323                    id: json_str(b, "/id").to_string(),
2324                    name: json_str(b, "/name").to_string(),
2325                    input: b["input"].clone(),
2326                }),
2327                _ => None,
2328            })
2329            .collect(),
2330        "user" => blocks()
2331            .filter(|b| json_str(b, "/type") == "tool_result")
2332            .map(|b| StreamEvent::ToolResult {
2333                id: json_str(b, "/tool_use_id").to_string(),
2334                name: String::new(),
2335                output: match &b["content"] {
2336                    serde_json::Value::String(s) => s.clone(),
2337                    serde_json::Value::Array(parts) => parts
2338                        .iter()
2339                        .filter_map(|p| p["text"].as_str())
2340                        .collect::<Vec<_>>()
2341                        .join("\n"),
2342                    _ => String::new(),
2343                },
2344                is_error: b["is_error"].as_bool() == Some(true),
2345            })
2346            .collect(),
2347        "error" => vec![StreamEvent::Error(json_error_message(v))],
2348        "result" => {
2349            let failed = v["is_error"].as_bool() == Some(true)
2350                || json_str(v, "/subtype").starts_with("error");
2351            if failed {
2352                return vec![StreamEvent::Error(json_str(v, "/result").to_string())];
2353            }
2354
2355            let turns = v["num_turns"].as_u64().unwrap_or(0);
2356            let secs = v["duration_ms"].as_u64().unwrap_or(0) / 1000;
2357            let time = if secs >= 60 {
2358                format!("{}m {}s", secs / 60, secs % 60)
2359            } else {
2360                format!("{secs}s")
2361            };
2362            vec![StreamEvent::Done(format!("{turns} turns · {time}"))]
2363        }
2364        _ => vec![],
2365    }
2366}
2367
2368#[cfg(test)]
2369mod stream_tests {
2370    use super::*;
2371    use serde_json::json;
2372
2373    fn events(line: &str) -> Vec<StreamEvent> {
2374        ClaudeRunner::new("claude").stream_events(&serde_json::from_str(line).unwrap())
2375    }
2376
2377    #[test]
2378    fn init_reports_model() {
2379        let line = r#"{"type":"system","subtype":"init","model":"claude-sonnet-5","cwd":"/w"}"#;
2380        assert_eq!(
2381            events(line),
2382            vec![StreamEvent::Started {
2383                model: "claude-sonnet-5".into()
2384            }]
2385        );
2386    }
2387
2388    #[test]
2389    fn assistant_blocks_in_order() {
2390        let line = r#"{"type":"assistant","message":{"content":[{"type":"thinking","thinking":"plan"},{"type":"text","text":"Reading."},{"type":"tool_use","id":"t1","name":"Read","input":{"file_path":"a.rs"}}]}}"#;
2391        assert_eq!(
2392            events(line),
2393            vec![
2394                StreamEvent::Thinking("plan".into()),
2395                StreamEvent::Text("Reading.".into()),
2396                StreamEvent::ToolCall {
2397                    id: "t1".into(),
2398                    name: "Read".into(),
2399                    input: json!({"file_path": "a.rs"}),
2400                },
2401            ]
2402        );
2403    }
2404
2405    #[test]
2406    fn tool_result_string_and_block_content() {
2407        let line = r#"{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"t1","content":"ok"},{"type":"tool_result","tool_use_id":"t2","content":[{"type":"text","text":"a"},{"type":"text","text":"b"}],"is_error":true}]}}"#;
2408        assert_eq!(
2409            events(line),
2410            vec![
2411                StreamEvent::ToolResult {
2412                    id: "t1".into(),
2413                    name: String::new(),
2414                    output: "ok".into(),
2415                    is_error: false,
2416                },
2417                StreamEvent::ToolResult {
2418                    id: "t2".into(),
2419                    name: String::new(),
2420                    output: "a\nb".into(),
2421                    is_error: true,
2422                },
2423            ]
2424        );
2425    }
2426
2427    #[test]
2428    fn result_success_and_error() {
2429        let ok = r#"{"type":"result","subtype":"success","is_error":false,"num_turns":66,"duration_ms":580214}"#;
2430        assert_eq!(
2431            events(ok),
2432            vec![StreamEvent::Done("66 turns · 9m 40s".into())]
2433        );
2434        let err = r#"{"type":"result","subtype":"error_max_turns","is_error":true,"result":"too many turns"}"#;
2435        assert_eq!(
2436            events(err),
2437            vec![StreamEvent::Error("too many turns".into())]
2438        );
2439    }
2440
2441    #[test]
2442    fn rate_limit_windows_parses_rejected_and_unknown_types() {
2443        let ndjson = concat!(
2444            r#"{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","rateLimitType":"five_hour","utilization":0.4,"resetsAt":1900000000}}"#,
2445            "\n",
2446            r#"{"type":"rate_limit_event","rate_limit_info":{"status":"rejected","rateLimitType":"weekly_opus","resetsAt":1900003600}}"#,
2447            "\n",
2448            r#"{"type":"rate_limit_event","rate_limit_info":{}}"#,
2449        );
2450        let windows = rate_limit_windows(ndjson);
2451        assert_eq!(windows.len(), 2);
2452        assert_eq!(windows[0].status, "allowed");
2453        assert_eq!(windows[0].utilization, Some(0.4));
2454        assert_eq!(windows[1].status, "rejected");
2455        assert_eq!(windows[1].window_type, "weekly_opus");
2456        assert_eq!(windows[1].resets_at, Some(1_900_003_600));
2457    }
2458
2459    #[test]
2460    fn rate_limit_windows_reads_every_unified_window() {
2461        let ndjson = r#"{"type":"rate_limit_event","rate_limit_info":{"status":"rejected","resetsAt":1791259200,"rateLimitType":"seven_day","overageStatus":"rejected","isUsingOverage":false,"unifiedWindows":{"five_hour":{"utilization":0.13,"resetsAt":1791250200},"seven_day":{"utilization":1,"resetsAt":1791259200}}}}"#;
2462        let windows = rate_limit_windows(ndjson);
2463        assert_eq!(windows.len(), 2);
2464        assert_eq!(windows[0].status, "rejected");
2465        assert_eq!(windows[0].window_type, "seven_day");
2466        assert_eq!(windows[0].utilization, Some(1.0));
2467        assert_eq!(windows[0].resets_at, Some(1_791_259_200));
2468        assert_eq!(windows[1].status, "unknown");
2469        assert_eq!(windows[1].window_type, "five_hour");
2470        assert_eq!(windows[1].utilization, Some(0.13));
2471        assert_eq!(windows[1].resets_at, Some(1_791_250_200));
2472    }
2473
2474    #[test]
2475    fn noise_events_are_dropped() {
2476        for line in [
2477            r#"{"type":"system","subtype":"thinking_tokens","tokens":12}"#,
2478            r#"{"type":"system","subtype":"task_started"}"#,
2479            r#"{"type":"rate_limit_event","rate_limit_info":{}}"#,
2480            r#"{"type":"tool_progress"}"#,
2481        ] {
2482            assert!(events(line).is_empty(), "{line}");
2483        }
2484    }
2485}