Skip to main content

orch/
parser.rs

1//! Agent response parser — normalizes JSON output from different agents.
2//!
3//! Each agent (Claude, Codex, OpenCode) returns a different JSON shape.
4//! This module parses them all into a common `AgentResponse` struct.
5//! Replaces `scripts/parse_response.sh` + `jq` pipelines.
6
7use anyhow::Context;
8use regex::Regex;
9use serde::{Deserialize, Serialize};
10use std::io::Read;
11
12use crate::status_heuristics;
13
14use std::cmp::Reverse;
15use std::fs;
16use std::io;
17use std::sync::LazyLock;
18
19static TRAILING_COMMA_RE: LazyLock<Regex> =
20    LazyLock::new(|| Regex::new(r",(\s*[}\]])").expect("trailing comma regex is valid"));
21
22/// Normalized agent response.
23#[derive(Debug, Clone, Default, Serialize, Deserialize)]
24pub struct AgentResponse {
25    pub status: String,
26    #[serde(default)]
27    pub summary: String,
28    #[serde(default)]
29    pub accomplished: Vec<String>,
30    #[serde(default)]
31    pub remaining: Vec<String>,
32    #[serde(default, alias = "files_changed", alias = "files_modified")]
33    pub files: Vec<String>,
34    #[serde(default)]
35    pub error: Option<String>,
36    /// Input token count (if available from agent).
37    #[serde(default)]
38    pub input_tokens: Option<u64>,
39    /// Output token count (if available from agent).
40    #[serde(default)]
41    pub output_tokens: Option<u64>,
42    /// Key learnings from this attempt (for memory persistence across retries).
43    #[serde(default)]
44    pub learnings: Vec<String>,
45    /// Subtask delegations — agent requests child tasks to be created.
46    #[serde(default)]
47    pub delegations: Vec<Delegation>,
48    /// Screenshots of a change a user sees, as image paths in the worktree.
49    #[serde(default)]
50    pub screenshots: Vec<Screenshot>,
51    /// Why no screenshot could be taken, or which tool was missing.
52    #[serde(default)]
53    pub screenshot_note: Option<String>,
54}
55
56/// A screenshot the agent took, with a short caption.
57#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
58pub struct Screenshot {
59    pub path: String,
60    #[serde(default)]
61    pub caption: String,
62}
63
64/// A subtask delegation requested by an agent.
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct Delegation {
67    pub title: String,
68    pub body: String,
69    #[serde(default)]
70    pub labels: Vec<String>,
71}
72
73/// Parse an agent response from a file path (or stdin if "-").
74#[expect(
75    clippy::print_stdout,
76    reason = "prints the parsed response for the CLI"
77)]
78pub fn parse_and_print(path: &str) -> anyhow::Result<()> {
79    let content = if path == "-" {
80        let mut buf = String::new();
81        io::stdin()
82            .read_to_string(&mut buf)
83            .context("reading stdin")?;
84        buf
85    } else {
86        fs::read_to_string(path).with_context(|| format!("reading {path}"))?
87    };
88
89    let response = parse(&content)?;
90    println!("{}", serde_json::to_string_pretty(&response)?);
91    Ok(())
92}
93
94/// Known canonical statuses - used to prefer better candidates.
95/// NOTE: Does NOT include aliases like "ready_for_review" or "ok" - the only
96/// caller runs normalize_status() first, which maps every alias to one of these.
97fn status_is_known(status: &str) -> bool {
98    matches!(
99        status,
100        "new" | "routed" | "in_progress" | "done" | "blocked" | "in_review" | "needs_review"
101    )
102}
103
104/// Parse raw agent output into a normalized response.
105pub fn parse(raw: &str) -> anyhow::Result<AgentResponse> {
106    let mut last_err: Option<anyhow::Error> = None;
107    let mut saw_jsonish_candidate = false;
108    // Pair: (parsed response, raw candidate string) so we can check the raw object
109    // for substantive fields that map_generic_response handles but that direct
110    // deserialization into AgentResponse ignores (e.g. "output", "message").
111    let mut best_candidate: Option<(AgentResponse, String)> = None;
112
113    for candidate in json_candidates(raw) {
114        match parse_candidate(&candidate) {
115            Ok(mut resp) => {
116                resp = normalize_status(resp);
117                // If status is known, return immediately (good candidate found).
118                if status_is_known(&resp.status) {
119                    return Ok(resp);
120                }
121                // Non-canonical status - remember it but keep looking for better.
122                if best_candidate.is_none() {
123                    best_candidate = Some((resp, candidate));
124                }
125            }
126            Err(err) => {
127                if err.to_string() != "invalid agent response candidate" {
128                    saw_jsonish_candidate = true;
129                    last_err = Some(err);
130                }
131            }
132        }
133    }
134
135    // If we found a candidate with non-canonical status but no known-status
136    // candidate was found, use the best one we have — but only if it has at
137    // least one substantive orch control field. Domain JSON records (career
138    // pipeline entries, trading alerts, etc.) have a `status` field that can
139    // be deserialized into AgentResponse, but they carry no orch fields like
140    // `summary`, `accomplished`, `files`, etc. Returning them would silently
141    // promote a domain value (e.g. "inbound-not-submitted") as the task status.
142    if let Some((resp, raw_candidate)) = best_candidate
143        && has_substantive_fields(&raw_candidate)
144    {
145        return Ok(resp);
146    }
147
148    if saw_jsonish_candidate && let Some(err) = last_err {
149        return Err(err);
150    }
151
152    if let Some(err) = last_err {
153        return Err(err);
154    }
155
156    anyhow::bail!(
157        "agent output is not valid JSON or a supported JSON wrapper: {}",
158        raw.trim()
159    )
160}
161
162/// Map known non-canonical agent statuses to their canonical equivalents.
163///
164/// Agents sometimes return statuses like `"ok"`, `"success"`, or `"completed"`
165/// that are semantically equivalent to `"done"`. Normalizing them here ensures
166/// that `classify_run_outcome` correctly classifies the run as success and
167/// prevents opaque `"no error info available"` failures when an agent returns
168/// a valid but non-canonical status.
169///
170/// Unknown statuses that read as completions normalize to done via the shared
171/// heuristic in `status_heuristics`; the rest stay as-is for the audit trail.
172fn normalize_status(mut resp: AgentResponse) -> AgentResponse {
173    let normalized = resp.status.to_ascii_lowercase();
174    if normalized.starts_with("pushed to ") || normalized.starts_with("pushed ") {
175        resp.status = "done".to_string();
176        return resp;
177    }
178
179    resp.status = match normalized.as_str() {
180        // Canonical completion statuses.
181        // Some agents return `complete` or `no_changes_needed` to indicate
182        // a successful run with no further edits required — treat them as
183        // `done` so the run is classified as successful.
184        "done"
185        | "completed"
186        | "complete"
187        | "skipped"
188        | "skip"
189        | "ok"
190        | "success"
191        | "noop"
192        | "green"
193        | "no_changes_needed"
194        | "no_trades_no_positions"
195        | "no_setups"
196        | "changes_made"
197        | "change_made"
198        | "changes_pushed"
199        | "pushed"
200        | "acknowledged"
201        | "flat"
202        | "no_action"
203        | "no_action_needed"
204        | "missed"
205        | "changes_addressed"
206        | "changes_requested_addressed"
207        | "review_addressed"
208        | "already_finalized_in_attempt_1"
209        | "alert"
210        | "alerts"
211        | "alerts_sent"
212        | "not_configured"
213        | "healthy"
214        | "alerts_fired"
215        | "verified"
216        | "fixed" => "done".to_string(),
217        // Canonical progress statuses.
218        // `partial` is used by some models to indicate partial progress —
219        // treat it as in_progress so the task remains open for follow-up.
220        "in_progress" | "running" | "partial" | "waiting" => "in_progress".to_string(),
221        "in_review" | "reviewing" => "in_review".to_string(),
222        "needs_review" | "pending_review" | "ready_for_review" => "needs_review".to_string(),
223        // Canonical error statuses.
224        "blocked" | "error" | "failed" | "failure" => "blocked".to_string(),
225        // Passthrough: the canonical statuses the arms above do not already cover.
226        "new" | "routed" => normalized.clone(),
227        // Unknown status reading as completion, done if the response carries orch
228        // fields — domain records without them stay non-canonical and get rejected (#3336)
229        _ if !resp.summary.is_empty()
230            || !resp.accomplished.is_empty()
231            || !resp.files.is_empty()
232            || resp.error.is_some() =>
233        {
234            if status_heuristics::status_looks_like_descriptive_completion(&normalized) {
235                "done".to_string()
236            } else {
237                resp.status.clone()
238            }
239        }
240        _ => resp.status.clone(),
241    };
242    resp
243}
244
245/// Extract the first JSON code block from markdown.
246fn extract_json_block(text: &str) -> Option<String> {
247    let start = text.find("```json")?;
248    let fence_end = start + "```json".len();
249    let remainder = &text[fence_end..];
250
251    // Find key positions after the opening fence.
252    let newline_pos = remainder.find('\n');
253    let json_start_pos = remainder.find(['{', '[']);
254    let first_nl = newline_pos.unwrap_or(usize::MAX);
255
256    // Decide fenced vs inline:
257    // - If a JSON delimiter ('{' or '[') appears before the first newline, treat as inline.
258    // - If there is no newline at all, treat as inline.
259    // - Otherwise, treat as a standard fenced block.
260    let is_inline = json_start_pos.is_some_and(|js| js < first_nl) || newline_pos.is_none();
261
262    if is_inline {
263        // Inline: closing fence may appear anywhere on the same logical line.
264        // Using find("```") here is safe because the JSON start already appeared
265        // before any newline, so the closing fence is on the same line too.
266        let closing_fence_pos = remainder.find("```")?;
267        let content_start = remainder
268            .char_indices()
269            .find(|(_, ch)| !ch.is_whitespace())
270            .map_or(fence_end, |(idx, _)| fence_end + idx);
271        let end = fence_end + closing_fence_pos;
272        if content_start > end {
273            return None;
274        }
275        Some(text[content_start..end].to_string())
276    } else {
277        // Fenced block: content begins after the first newline.
278        // The closing fence must be anchored to a line boundary (\n```) to avoid
279        // false positives from triple-backticks inside JSON string values.
280        let nl = newline_pos?;
281        let content_start = fence_end + nl + 1;
282        let content = &text[content_start..];
283        let closing_pos = find_closing_fence_at_line_boundary(content)?;
284        Some(text[content_start..content_start + closing_pos].to_string())
285    }
286}
287
288/// Find the position (within `content`) where a ``` closing fence starts, anchored to a
289/// line boundary.  Returns the byte offset of the leading ``` so that `content[..pos]`
290/// is everything before the closing fence (including the preceding newline).
291fn find_closing_fence_at_line_boundary(content: &str) -> Option<usize> {
292    // Edge case: content itself begins with the closing fence (no preceding content).
293    if content.starts_with("```") {
294        return Some(0);
295    }
296    // Scan for \n``` pattern — the closing fence must start at the beginning of a line.
297    let mut search_from = 0;
298    while let Some(nl_idx) = content[search_from..].find('\n') {
299        let after_nl = search_from + nl_idx + 1;
300        if content[after_nl..].starts_with("```") {
301            // Return the position of the ``` (after the \n).
302            // The content slice up to this point includes the \n, matching Markdown semantics.
303            return Some(after_nl);
304        }
305        search_from = after_nl;
306    }
307    None
308}
309
310/// Returns true if the raw JSON candidate has at least one substantive orch control field.
311///
312/// Operates on the raw string (not the deserialized `AgentResponse`) so that fields like
313/// `output` and `message` — which `map_generic_response` maps to `summary` but which are
314/// not struct fields on `AgentResponse` and are silently ignored by direct deserialization —
315/// are correctly treated as substantive. This prevents domain JSON records (career pipeline
316/// entries, trading alerts, etc.) whose only orch-like field is `status` from being promoted
317/// as the task status.
318fn has_substantive_fields(raw: &str) -> bool {
319    if let Ok(serde_json::Value::Object(obj)) = serde_json::from_str::<serde_json::Value>(raw) {
320        return SUBSTANTIVE_RESPONSE_FIELDS
321            .iter()
322            .any(|key| obj.contains_key(*key))
323            || obj.contains_key("error");
324    }
325    false
326}
327
328/// Fields that indicate a JSON blob is an AgentResponse (higher score = better match).
329const AGENT_RESPONSE_FIELDS: &[&str] = &[
330    "\"status\"",
331    "\"summary\"",
332    "\"accomplished\"",
333    "\"remaining\"",
334    "\"files\"",
335    "\"learnings\"",
336    "\"delegations\"",
337    "\"screenshots\"",
338    "\"error\"",
339];
340
341fn agent_response_score(blob: &str) -> usize {
342    AGENT_RESPONSE_FIELDS
343        .iter()
344        .filter(|&&f| blob.contains(f))
345        .count()
346}
347
348fn json_candidates(raw: &str) -> Vec<String> {
349    let mut candidates = Vec::new();
350
351    if let Some(block) = extract_json_block(raw) {
352        candidates.push(block);
353    }
354
355    // Collect ALL balanced JSON blobs and sort by how much they look like an
356    // AgentResponse, so the real response is tried before telemetry blobs.
357    let mut all_json = extract_all_balanced_json(raw);
358    all_json.sort_by_key(|b| Reverse(agent_response_score(b)));
359
360    for candidate in all_json {
361        if !candidates.iter().any(|existing| existing == &candidate) {
362            candidates.push(candidate);
363        }
364    }
365
366    candidates.push(raw.to_string());
367    candidates
368}
369
370fn parse_candidate(candidate: &str) -> anyhow::Result<AgentResponse> {
371    if let Ok(resp) = serde_json::from_str::<AgentResponse>(candidate) {
372        return Ok(resp);
373    }
374
375    let repaired = repair_json_like(candidate);
376    if repaired != candidate
377        && let Ok(resp) = serde_json::from_str::<AgentResponse>(&repaired)
378    {
379        return Ok(resp);
380    }
381
382    if let Ok(val) = serde_json::from_str::<serde_json::Value>(candidate) {
383        return map_generic_response(&val);
384    }
385
386    if repaired != candidate
387        && let Ok(val) = serde_json::from_str::<serde_json::Value>(&repaired)
388    {
389        return map_generic_response(&val);
390    }
391
392    anyhow::bail!("invalid agent response candidate")
393}
394
395/// Scan `text` and return every top-level balanced JSON object or array found.
396fn extract_all_balanced_json(text: &str) -> Vec<String> {
397    let mut results = Vec::new();
398    let mut pos = 0;
399
400    while pos < text.len() {
401        // Find the next `{` or `[` starting from `pos`.
402        let Some(start_offset) = text[pos..]
403            .char_indices()
404            .find(|(_, ch)| matches!(ch, '{' | '['))
405            .map(|(idx, _)| idx)
406        else {
407            break;
408        };
409        let start = pos + start_offset;
410
411        let mut stack = Vec::new();
412        let mut in_string = false;
413        let mut escape = false;
414        let mut end: Option<usize> = None;
415
416        for (idx, ch) in text[start..].char_indices() {
417            let abs = start + idx;
418            if in_string {
419                if escape {
420                    escape = false;
421                    continue;
422                }
423                match ch {
424                    '\\' => escape = true,
425                    '"' => in_string = false,
426                    _ => {}
427                }
428                continue;
429            }
430
431            match ch {
432                '"' => in_string = true,
433                '{' | '[' => stack.push(ch),
434                '}' => {
435                    if stack.pop() != Some('{') {
436                        break; // malformed — skip past this `{`
437                    }
438                    if stack.is_empty() {
439                        end = Some(abs);
440                        break;
441                    }
442                }
443                ']' => {
444                    if stack.pop() != Some('[') {
445                        break; // malformed — skip past this `[`
446                    }
447                    if stack.is_empty() {
448                        end = Some(abs);
449                        break;
450                    }
451                }
452                _ => {}
453            }
454        }
455
456        if let Some(end_idx) = end {
457            results.push(text[start..=end_idx].to_string());
458            pos = end_idx + 1;
459        } else {
460            // No closing brace found — skip past the opening character.
461            pos = start + 1;
462        }
463    }
464
465    results
466}
467
468fn repair_json_like(text: &str) -> String {
469    let mut repaired = text.trim().replace(['“', '”'], "\"");
470    repaired = repaired.replace(['‘', '’'], "'");
471    repaired = TRAILING_COMMA_RE.replace_all(&repaired, "$1").into_owned();
472
473    let mut stack = Vec::new();
474    let mut in_string = false;
475    let mut escape = false;
476
477    for ch in repaired.chars() {
478        if in_string {
479            if escape {
480                escape = false;
481                continue;
482            }
483            match ch {
484                '\\' => escape = true,
485                '"' => in_string = false,
486                _ => {}
487            }
488            continue;
489        }
490
491        match ch {
492            '"' => in_string = true,
493            '{' => stack.push('}'),
494            '[' => stack.push(']'),
495            '}' | ']' => {
496                if let Some(expected) = stack.last().copied()
497                    && expected == ch
498                {
499                    stack.pop();
500                }
501            }
502            _ => {}
503        }
504    }
505
506    while let Some(ch) = stack.pop() {
507        repaired.push(ch);
508    }
509
510    repaired
511}
512
513/// Fields that indicate a substantive agent response (not just a status blob).
514/// NOTE: We don't include "output" or "message" here because those are
515/// handled via summary extraction in map_generic_response. This list is for
516/// validating that the payload has meaningful agent response structure beyond
517/// just a status field.
518const SUBSTANTIVE_RESPONSE_FIELDS: &[&str] = &[
519    "summary",
520    "message",
521    "accomplished",
522    "remaining",
523    "files",
524    "files_changed",
525    "files_modified",
526    "learnings",
527    "delegations",
528    "output",
529    "pr_url",
530    "report",
531];
532
533/// Infer a canonical completion status from known non-standard completion envelope shapes.
534///
535/// Claude agents sometimes return JSON without a `status`/`result` field, using
536/// alternative completion indicators instead. This function maps those shapes to
537/// a canonical status so they are not misclassified as `InvalidResponse`.
538///
539/// Recognized patterns (all map to `"done"`):
540/// - `{"success": true, ...}` — explicit success boolean
541/// - `{"type": "task_complete", ...}` — explicit task_complete type string
542/// - `{"tests_passed": true, ...}` — tests-passed completion signal
543fn infer_completion_status(obj: &serde_json::Map<String, serde_json::Value>) -> Option<String> {
544    // success: true
545    if obj.get("success").and_then(serde_json::Value::as_bool) == Some(true) {
546        return Some("done".to_string());
547    }
548    // type: "task_complete"
549    if obj.get("type").and_then(|v| v.as_str()) == Some("task_complete") {
550        return Some("done".to_string());
551    }
552    // ok: true
553    if obj.get("ok").and_then(serde_json::Value::as_bool) == Some(true) {
554        return Some("done".to_string());
555    }
556    // tests_passed: true
557    if obj.get("tests_passed").and_then(serde_json::Value::as_bool) == Some(true) {
558        return Some("done".to_string());
559    }
560    None
561}
562
563/// Map a generic JSON object to AgentResponse.
564///
565/// Requires stricter shape checking: the object must have:
566/// 1. A status/result field (or a recognized completion envelope shape)
567/// 2. AND at least one substantive field OR an error field
568///
569/// This prevents acceptance of non-response JSON blobs (telemetry, tool outputs)
570/// that happen to contain a status field.
571fn map_generic_response(val: &serde_json::Value) -> anyhow::Result<AgentResponse> {
572    let obj = val.as_object().context("expected JSON object")?;
573
574    // Check for status or result field first; fall back to known completion envelopes.
575    let status = obj
576        .get("status")
577        .or_else(|| obj.get("result"))
578        .and_then(|v| v.as_str())
579        .map(String::from)
580        .or_else(|| infer_completion_status(obj))
581        .context("agent response is missing required 'status' or 'result' field")?;
582
583    // Require at least one substantive field OR an error field.
584    // This prevents accepting telemetry/event JSON blobs that happen to have
585    // a status field but are not actual agent responses.
586    let has_substantive_field = SUBSTANTIVE_RESPONSE_FIELDS
587        .iter()
588        .any(|key| obj.contains_key(*key));
589    let has_error = obj.contains_key("error");
590
591    if !has_substantive_field && !has_error {
592        anyhow::bail!("JSON object lacks substantive response fields");
593    }
594
595    let summary = obj
596        .get("summary")
597        .or_else(|| obj.get("message"))
598        .or_else(|| obj.get("output"))
599        .and_then(|v| v.as_str())
600        .unwrap_or("")
601        .to_string();
602
603    let accomplished = extract_string_array(obj.get("accomplished"));
604    let remaining = extract_string_array(obj.get("remaining"));
605    let files = {
606        let f = extract_string_array(obj.get("files"));
607        if f.is_empty() {
608            let fc = extract_string_array(obj.get("files_changed"));
609            if fc.is_empty() {
610                extract_string_array(obj.get("files_modified"))
611            } else {
612                fc
613            }
614        } else {
615            f
616        }
617    };
618    let error = obj.get("error").and_then(|v| v.as_str()).map(String::from);
619    let learnings = extract_string_array(obj.get("learnings"));
620
621    // Extract token counts if available
622    let input_tokens = extract_u64(obj.get("input_tokens"))
623        .or_else(|| extract_u64(obj.get("tokens_input")))
624        .or_else(|| extract_usage_tokens(obj.get("usage"), true));
625    let output_tokens = extract_u64(obj.get("output_tokens"))
626        .or_else(|| extract_u64(obj.get("tokens_output")))
627        .or_else(|| extract_usage_tokens(obj.get("usage"), false));
628
629    // Extract delegations. If the `delegations` field is present but malformed,
630    // return an error instead of silently ignoring it so callers can surface
631    // and debug malformed agent output.
632    let delegations = if let Some(v) = obj.get("delegations") {
633        serde_json::from_value::<Vec<Delegation>>(v.clone())
634            .with_context(|| format!("invalid delegations field: {v}"))?
635    } else {
636        Vec::new()
637    };
638
639    let screenshots = extract_screenshots(obj.get("screenshots"));
640    let screenshot_note = obj
641        .get("screenshot_note")
642        .and_then(|v| v.as_str())
643        .map(str::trim)
644        .filter(|n| !n.is_empty())
645        .map(String::from);
646
647    Ok(AgentResponse {
648        status,
649        summary,
650        accomplished,
651        remaining,
652        files,
653        error,
654        input_tokens,
655        output_tokens,
656        learnings,
657        delegations,
658        screenshots,
659        screenshot_note,
660    })
661}
662
663/// Read the `screenshots` list. An entry is `{"path", "caption"}` or a bare path string.
664/// A malformed entry is skipped, since a bad screenshot must not lose the rest of the response.
665fn extract_screenshots(val: Option<&serde_json::Value>) -> Vec<Screenshot> {
666    let Some(serde_json::Value::Array(items)) = val else {
667        return Vec::new();
668    };
669    items
670        .iter()
671        .filter_map(|item| match item {
672            serde_json::Value::String(path) => Some(Screenshot {
673                path: path.clone(),
674                caption: String::new(),
675            }),
676            serde_json::Value::Object(_) => serde_json::from_value::<Screenshot>(item.clone()).ok(),
677            _ => None,
678        })
679        .filter(|s| !s.path.trim().is_empty())
680        .collect()
681}
682
683/// Extract a u64 from a JSON value.
684fn extract_u64(val: Option<&serde_json::Value>) -> Option<u64> {
685    val.and_then(serde_json::Value::as_u64)
686}
687
688/// Extract tokens from a usage object (common in OpenAI-compatible APIs).
689fn extract_usage_tokens(usage: Option<&serde_json::Value>, is_input: bool) -> Option<u64> {
690    let obj = usage?.as_object()?;
691    let key = if is_input {
692        "input_tokens"
693    } else {
694        "output_tokens"
695    };
696    obj.get(key).and_then(serde_json::Value::as_u64)
697}
698
699fn extract_string_array(val: Option<&serde_json::Value>) -> Vec<String> {
700    val.and_then(|v| v.as_array())
701        .map(|arr| {
702            arr.iter()
703                .filter_map(|v| v.as_str().map(String::from))
704                .collect()
705        })
706        .unwrap_or_default()
707}
708
709#[cfg(test)]
710mod tests {
711    use super::*;
712
713    #[test]
714    fn parse_direct_json() {
715        let input = r#"{"status":"done","summary":"Fixed bug","accomplished":["fixed it"],"remaining":[],"files":["src/main.rs"]}"#;
716        let resp = parse(input).unwrap();
717        assert_eq!(resp.status, "done");
718        assert_eq!(resp.summary, "Fixed bug");
719        assert_eq!(resp.accomplished, vec!["fixed it"]);
720        assert_eq!(resp.files, vec!["src/main.rs"]);
721        assert!(resp.error.is_none());
722    }
723
724    #[test]
725    fn parse_json_in_markdown_block() {
726        let input = r#"Here is the result:
727
728```json
729{"status":"in_progress","summary":"Working on it","accomplished":[],"remaining":["finish tests"],"files":[]}
730```
731
732Done.
733"#;
734        let resp = parse(input).unwrap();
735        assert_eq!(resp.status, "in_progress");
736        assert_eq!(resp.remaining, vec!["finish tests"]);
737    }
738
739    #[test]
740    fn parse_generic_json_with_different_field_names() {
741        let input = r#"{"result":"done","message":"All good","files":["a.rs","b.rs"]}"#;
742        let resp = parse(input).unwrap();
743        assert_eq!(resp.status, "done");
744        assert_eq!(resp.summary, "All good");
745        assert_eq!(resp.files, vec!["a.rs", "b.rs"]);
746    }
747
748    #[test]
749    fn parse_with_error_field() {
750        let input = r#"{"status":"blocked","summary":"Cannot proceed","accomplished":[],"remaining":[],"files":[],"error":"missing dependency"}"#;
751        let resp = parse(input).unwrap();
752        assert_eq!(resp.status, "blocked");
753        assert_eq!(resp.error, Some("missing dependency".to_string()));
754    }
755
756    #[test]
757    fn parse_fallback_raw_text() {
758        let input = "This is just plain text output from the agent.";
759        let err = parse(input).unwrap_err();
760        assert!(
761            err.to_string()
762                .contains("agent output is not valid JSON or a supported JSON wrapper")
763        );
764    }
765
766    #[test]
767    fn parse_malformed_json_block_returns_error() {
768        let input = r#"Here is the result:
769
770```json
771{"status":"done","summary":"missing brace"
772```
773"#;
774        let resp = parse(input).unwrap();
775        assert_eq!(resp.status, "done");
776        assert_eq!(resp.summary, "missing brace");
777    }
778
779    #[test]
780    fn parse_json_with_trailing_comma() {
781        let input =
782            r#"{"status":"done","summary":"Fixed","accomplished":[],"remaining":[],"files":[],}"#;
783        let resp = parse(input).unwrap();
784        assert_eq!(resp.status, "done");
785        assert_eq!(resp.summary, "Fixed");
786    }
787
788    #[test]
789    fn parse_json_embedded_in_commentary() {
790        let input = r#"Done:
791{"status":"in_progress","summary":"working","accomplished":[],"remaining":["tests"],"files":[]}
792Thanks"#;
793        let resp = parse(input).unwrap();
794        assert_eq!(resp.status, "in_progress");
795        assert_eq!(resp.remaining, vec!["tests"]);
796    }
797
798    #[test]
799    fn extract_json_block_from_markdown() {
800        let text = "prefix\n```json\n{\"key\":\"value\"}\n```\nsuffix";
801        let block = extract_json_block(text).unwrap();
802        assert_eq!(block, "{\"key\":\"value\"}\n");
803    }
804
805    #[test]
806    fn extract_json_block_inline_fence() {
807        let text = "prefix\n```json{\"key\":\"value\"}```\nsuffix";
808        let block = extract_json_block(text).unwrap();
809        assert_eq!(block, "{\"key\":\"value\"}");
810    }
811
812    #[test]
813    fn extract_json_block_with_info_string() {
814        let text = "prefix\n```json some-meta\n{\"key\":\"value\"}\n```\nsuffix";
815        let block = extract_json_block(text).unwrap();
816        assert_eq!(block, "{\"key\":\"value\"}\n");
817    }
818
819    #[test]
820    fn extract_json_block_with_info_string_and_whitespace() {
821        let text = "prefix\n```json   some-meta   \n{\"key\":\"value\"}\n```\nsuffix";
822        let block = extract_json_block(text).unwrap();
823        assert_eq!(block, "{\"key\":\"value\"}\n");
824    }
825
826    #[test]
827    fn extract_json_block_inline_with_internal_newline() {
828        // Inline JSON that contains a newline inside the JSON value
829        let text = "prefix\n```json{\"key\":\"value\\nwith newline\"}```\nsuffix";
830        let block = extract_json_block(text).unwrap();
831        assert_eq!(block, r#"{"key":"value\nwith newline"}"#);
832    }
833
834    #[test]
835    fn extract_json_block_inline_with_whitespace_newline() {
836        // Inline JSON that contains a newline as whitespace between key and value
837        let text = "prefix\n```json{\"key\":\n\"value\"}```\nsuffix";
838        let block = extract_json_block(text).unwrap();
839        assert_eq!(block, "{\"key\":\n\"value\"}");
840    }
841
842    #[test]
843    fn extract_json_block_missing_closing_fence() {
844        let text = "prefix\n```json{\"key\":\"value\"}\n";
845        assert!(extract_json_block(text).is_none());
846    }
847
848    #[test]
849    fn extract_json_block_array_inline() {
850        let text = "prefix\n```json[1,2,3]```\nsuffix";
851        let block = extract_json_block(text).unwrap();
852        assert_eq!(block, "[1,2,3]");
853    }
854
855    #[test]
856    fn extract_json_block_multiple_fences() {
857        let text = "prefix\n```json{\"first\":1}``` middle\n```json{\"second\":2}``` suffix";
858        let block = extract_json_block(text).unwrap();
859        assert_eq!(block, "{\"first\":1}");
860    }
861
862    #[test]
863    fn extract_json_block_missing_returns_none() {
864        assert!(extract_json_block("no code block here").is_none());
865    }
866
867    #[test]
868    fn extract_string_array_from_json() {
869        let val: serde_json::Value = serde_json::json!(["a", "b", "c"]);
870        let result = extract_string_array(Some(&val));
871        assert_eq!(result, vec!["a", "b", "c"]);
872    }
873
874    #[test]
875    fn extract_string_array_none() {
876        let result = extract_string_array(None);
877        assert!(result.is_empty(), "{result:?}");
878    }
879
880    #[test]
881    fn parse_empty_object() {
882        let input = "{}";
883        let err = parse(input).unwrap_err();
884        let msg = err.to_string();
885        assert!(
886            msg.contains("agent response is missing required")
887                || msg.contains("JSON object lacks substantive"),
888            "unexpected error: {msg}"
889        );
890    }
891
892    #[test]
893    fn parse_with_learnings() {
894        let input = r#"{"status":"needs_review","summary":"Need to fix imports","accomplished":[],"remaining":["fix imports"],"files":["src/main.rs"],"learnings":["Use std::sync::Arc for shared state","Check imports before committing"]}"#;
895        let resp = parse(input).unwrap();
896        assert_eq!(resp.status, "needs_review");
897        assert_eq!(resp.summary, "Need to fix imports");
898        assert_eq!(resp.learnings.len(), 2);
899        assert_eq!(resp.learnings[0], "Use std::sync::Arc for shared state");
900        assert_eq!(resp.learnings[1], "Check imports before committing");
901    }
902
903    #[test]
904    fn parse_screenshots_with_captions() {
905        let input = r#"{"status":"done","summary":"x","screenshots":[{"path":"shots/home.png","caption":"Home, desktop"},"shots/phone.png",{"caption":"no path"},7],"screenshot_note":" skill missing "}"#;
906        let resp = parse(input).unwrap();
907        assert_eq!(
908            resp.screenshots,
909            vec![
910                Screenshot {
911                    path: "shots/home.png".into(),
912                    caption: "Home, desktop".into()
913                },
914                Screenshot {
915                    path: "shots/phone.png".into(),
916                    caption: String::new()
917                },
918            ]
919        );
920        assert_eq!(resp.screenshot_note.as_deref(), Some("skill missing"));
921    }
922
923    #[test]
924    fn parse_without_screenshots_yields_none() {
925        let resp = parse(r#"{"status":"done","summary":"x","accomplished":["a"]}"#).unwrap();
926        assert!(resp.screenshots.is_empty());
927        assert!(resp.screenshot_note.is_none());
928    }
929
930    #[test]
931    fn parse_learnings_empty_by_default() {
932        let input = r#"{"status":"done","summary":"Completed","accomplished":["done"],"remaining":[],"files":[]}"#;
933        let resp = parse(input).unwrap();
934        assert!(resp.learnings.is_empty(), "{:?}", resp.learnings);
935    }
936
937    #[test]
938    fn parse_with_delegations() {
939        let input = r#"{
940            "status": "blocked",
941            "summary": "Task requires subtasks",
942            "accomplished": ["Analyzed requirements"],
943            "remaining": ["Waiting on subtasks"],
944            "files_changed": [],
945            "blockers": ["Waiting on delegated subtasks"],
946            "reason": "Decomposed into subtasks",
947            "delegations": [
948                {"title": "Implement login API", "body": "Create POST /api/login", "labels": ["backend"]},
949                {"title": "Add login form", "body": "Create React login component", "labels": ["frontend"]}
950            ]
951        }"#;
952        let resp = parse(input).unwrap();
953        assert_eq!(resp.status, "blocked");
954        assert_eq!(resp.delegations.len(), 2);
955        assert_eq!(resp.delegations[0].title, "Implement login API");
956        assert_eq!(resp.delegations[0].body, "Create POST /api/login");
957        assert_eq!(resp.delegations[0].labels, vec!["backend"]);
958        assert_eq!(resp.delegations[1].title, "Add login form");
959        assert_eq!(resp.delegations[1].labels, vec!["frontend"]);
960    }
961
962    #[test]
963    fn parse_delegations_empty_by_default() {
964        let input =
965            r#"{"status":"done","summary":"Done","accomplished":[],"remaining":[],"files":[]}"#;
966        let resp = parse(input).unwrap();
967        assert!(resp.delegations.is_empty());
968    }
969
970    #[test]
971    fn parse_delegations_without_labels() {
972        let input = r#"{
973            "status": "blocked",
974            "summary": "Delegating",
975            "delegations": [
976                {"title": "Subtask", "body": "Do the thing"}
977            ]
978        }"#;
979        let resp = parse(input).unwrap();
980        assert_eq!(resp.delegations.len(), 1);
981        assert_eq!(resp.delegations[0].title, "Subtask");
982        assert_eq!(resp.delegations[0].labels, Vec::<String>::new());
983    }
984
985    #[test]
986    fn parse_response_after_telemetry_json() {
987        // Telemetry JSON appears before the actual response JSON.
988        // The parser must skip the telemetry blob and find the real response.
989        let input = r#"Processing...
990{"type":"telemetry","message":"starting task","tokens":42}
991Some output here.
992{"status":"done","summary":"Fixed the bug","accomplished":["patched parser"],"remaining":[],"files":["src/parser.rs"]}
993"#;
994        let resp = parse(input).unwrap();
995        assert_eq!(resp.status, "done");
996        assert_eq!(resp.summary, "Fixed the bug");
997        assert_eq!(resp.files, vec!["src/parser.rs"]);
998    }
999
1000    // --- Edge-case tests for line-boundary fence extraction ---
1001
1002    #[test]
1003    fn extract_json_block_backticks_inside_json_string() {
1004        // Triple-backticks appear inside a JSON string value.
1005        // The old code would stop at the first ``` (inside the string).
1006        // The new code must find the real closing fence at a line boundary.
1007        let text = "```json\n{\"code\":\"example: ```snippet``` end\"}\n```\n";
1008        let block = extract_json_block(text).unwrap();
1009        assert_eq!(block, "{\"code\":\"example: ```snippet``` end\"}\n");
1010    }
1011
1012    #[test]
1013    fn extract_json_block_backticks_inside_json_string_parse_roundtrip() {
1014        // Full parse roundtrip: fenced block with backticks inside a JSON string value.
1015        let input = "```json\n{\"status\":\"done\",\"summary\":\"use ```code``` here\"}\n```\n";
1016        let resp = parse(input).unwrap();
1017        assert_eq!(resp.status, "done");
1018        assert_eq!(resp.summary, "use ```code``` here");
1019    }
1020
1021    #[test]
1022    fn extract_json_block_inline_with_embedded_backtick_pairs() {
1023        // Inline JSON: embedded backticks that are NOT triple should not confuse the parser.
1024        let text = "```json{\"key\":\"a`b``c\"}```\n";
1025        let block = extract_json_block(text).unwrap();
1026        assert_eq!(block, "{\"key\":\"a`b``c\"}");
1027    }
1028
1029    #[test]
1030    fn parse_mixed_telemetry_and_fenced_response() {
1031        // Telemetry JSON with backtick sequences followed by a fenced agent response.
1032        let input = r#"Processing...
1033{"type":"log","msg":"calling tool: ```bash```"}
1034```json
1035{"status":"done","summary":"fixed it","accomplished":["patched"],"remaining":[],"files":["src/x.rs"]}
1036```
1037"#;
1038        let resp = parse(input).unwrap();
1039        assert_eq!(resp.status, "done");
1040        assert_eq!(resp.summary, "fixed it");
1041        assert_eq!(resp.files, vec!["src/x.rs"]);
1042    }
1043
1044    #[test]
1045    fn parse_response_from_ndjson_multiple_objects() {
1046        // NDJSON stream: only the last object has `status` — must select it.
1047        let input = r#"{"type":"text","text":"Working on it..."}
1048{"type":"tool_call","name":"bash","input":{"command":"cargo test"}}
1049{"type":"tool_result","output":"test passed"}
1050{"status":"needs_review","summary":"All tests pass","accomplished":["fixed bug"],"remaining":[],"files":["src/lib.rs"]}
1051"#;
1052        let resp = parse(input).unwrap();
1053        assert_eq!(resp.status, "needs_review");
1054        assert_eq!(resp.summary, "All tests pass");
1055        assert_eq!(resp.files, vec!["src/lib.rs"]);
1056    }
1057
1058    // ── normalize_status tests ────────────────────────────────────────────────
1059
1060    #[test]
1061    fn parse_normalizes_ok_alias_to_done() {
1062        let input =
1063            r#"{"status":"ok","summary":"all good","accomplished":[],"remaining":[],"files":[]}"#;
1064        let resp = parse(input).unwrap();
1065        assert_eq!(resp.status, "done");
1066    }
1067
1068    #[test]
1069    fn parse_normalizes_success_alias_to_done() {
1070        let input = r#"{"status":"success","summary":"fixed it","accomplished":[],"remaining":[],"files":[]}"#;
1071        let resp = parse(input).unwrap();
1072        assert_eq!(resp.status, "done");
1073    }
1074
1075    #[test]
1076    fn parse_normalizes_completed_alias_to_done() {
1077        let input = r#"{"status":"completed","summary":"done","accomplished":[],"remaining":[],"files":[]}"#;
1078        let resp = parse(input).unwrap();
1079        assert_eq!(resp.status, "done");
1080    }
1081
1082    #[test]
1083    fn parse_normalizes_missed_alias_to_done_case_insensitive() {
1084        let input = r#"{"status":"MISSED","summary":"no setups found","accomplished":[],"remaining":[],"files":[]}"#;
1085        let resp = parse(input).unwrap();
1086        assert_eq!(resp.status, "done");
1087    }
1088
1089    #[test]
1090    fn parse_normalizes_changes_addressed_alias_to_done() {
1091        let input = r#"{"status":"changes_addressed","summary":"feedback addressed","accomplished":[],"remaining":[],"files":[]}"#;
1092        let resp = parse(input).unwrap();
1093        assert_eq!(resp.status, "done");
1094    }
1095
1096    #[test]
1097    fn parse_normalizes_changes_requested_addressed_alias_to_done() {
1098        let input = r#"{"status":"changes_requested_addressed","summary":"review feedback addressed","accomplished":[],"remaining":[],"files":[]}"#;
1099        let resp = parse(input).unwrap();
1100        assert_eq!(resp.status, "done");
1101    }
1102
1103    #[test]
1104    fn parse_normalizes_review_addressed_alias_to_done() {
1105        let input = r#"{"status":"review_addressed","summary":"review feedback addressed","accomplished":[],"remaining":[],"files":[]}"#;
1106        let resp = parse(input).unwrap();
1107        assert_eq!(resp.status, "done");
1108    }
1109
1110    #[test]
1111    fn parse_normalizes_already_finalized_in_attempt_1_alias_to_done() {
1112        let input = r#"{"status":"already_finalized_in_attempt_1","summary":"work already done in attempt 1","accomplished":[],"remaining":[],"files":[]}"#;
1113        let resp = parse(input).unwrap();
1114        assert_eq!(resp.status, "done");
1115    }
1116
1117    #[test]
1118    fn parse_normalizes_noop_alias_to_done() {
1119        // noop / green / alerts_sent → done, matching #3273 alias map.
1120        let input = r#"{"status":"noop","summary":"nothing to do","accomplished":[],"remaining":[],"files":[]}"#;
1121        let resp = parse(input).unwrap();
1122        assert_eq!(resp.status, "done");
1123    }
1124
1125    #[test]
1126    fn parse_normalizes_green_alias_to_done() {
1127        let input = r#"{"status":"green","summary":"all passing","accomplished":[],"remaining":[],"files":[]}"#;
1128        let resp = parse(input).unwrap();
1129        assert_eq!(resp.status, "done");
1130    }
1131
1132    #[test]
1133    fn parse_normalizes_alerts_sent_alias_to_done() {
1134        let input = r#"{"status":"alerts_sent","summary":"notifications dispatched","accomplished":[],"remaining":[],"files":[]}"#;
1135        let resp = parse(input).unwrap();
1136        assert_eq!(resp.status, "done");
1137    }
1138
1139    #[test]
1140    fn parse_normalizes_verified_alias_to_done() {
1141        let input = r#"{"status":"verified","summary":"result verified correct","accomplished":[],"remaining":[],"files":[]}"#;
1142        let resp = parse(input).unwrap();
1143        assert_eq!(resp.status, "done");
1144    }
1145
1146    #[test]
1147    fn parse_normalizes_fixed_alias_to_done() {
1148        let input = r#"{"status":"fixed","summary":"bug has been fixed","accomplished":["fixed bug"],"remaining":[],"files":["src/parser.rs"]}"#;
1149        let resp = parse(input).unwrap();
1150        assert_eq!(resp.status, "done");
1151    }
1152
1153    #[test]
1154    fn parse_normalizes_alerts_fired_alias_to_done() {
1155        let input = r#"{"status":"alerts_fired","summary":"alerts dispatched","accomplished":[],"remaining":[],"files":[]}"#;
1156        let resp = parse(input).unwrap();
1157        assert_eq!(resp.status, "done");
1158    }
1159
1160    #[test]
1161    fn parse_normalizes_waiting_alias_to_in_progress() {
1162        // waiting → in_progress (distinct from running/partial in the alias map).
1163        let input = r#"{"status":"waiting","summary":"blocked on upstream","accomplished":[],"remaining":[],"files":[]}"#;
1164        let resp = parse(input).unwrap();
1165        assert_eq!(resp.status, "in_progress");
1166    }
1167
1168    #[test]
1169    fn parse_normalizes_changes_pushed_alias_to_done() {
1170        let input = r#"{"status":"changes_pushed","summary":"changes pushed to branch","accomplished":[],"remaining":[],"files":[]}"#;
1171        let resp = parse(input).unwrap();
1172        assert_eq!(resp.status, "done");
1173    }
1174
1175    #[test]
1176    fn parse_normalizes_bare_pushed_alias_to_done() {
1177        let input = r#"{"status":"pushed","summary":"changes pushed to branch","accomplished":[],"remaining":[],"files":[]}"#;
1178        let resp = parse(input).unwrap();
1179        assert_eq!(resp.status, "done");
1180    }
1181
1182    #[test]
1183    fn parse_normalizes_dynamic_pushed_to_branch_status_to_done() {
1184        let input = r#"{"status":"pushed to internal-155195-weekly-review-patterns-progress-and-next","summary":"changes pushed to branch","accomplished":[],"remaining":[],"files":[]}"#;
1185        let resp = parse(input).unwrap();
1186        assert_eq!(resp.status, "done");
1187    }
1188
1189    #[test]
1190    fn parse_normalizes_running_alias_to_in_progress() {
1191        let input = r#"{"status":"running","summary":"working","accomplished":[],"remaining":[],"files":[]}"#;
1192        let resp = parse(input).unwrap();
1193        assert_eq!(resp.status, "in_progress");
1194    }
1195
1196    #[test]
1197    fn parse_normalizes_reviewing_alias_to_in_review() {
1198        let input = r#"{"status":"reviewing","summary":"reviewing","accomplished":[],"remaining":[],"files":[]}"#;
1199        let resp = parse(input).unwrap();
1200        assert_eq!(resp.status, "in_review");
1201    }
1202
1203    #[test]
1204    fn parse_normalizes_pending_review_alias_to_needs_review() {
1205        let input = r#"{"status":"pending_review","summary":"ready","accomplished":[],"remaining":[],"files":[]}"#;
1206        let resp = parse(input).unwrap();
1207        assert_eq!(resp.status, "needs_review");
1208    }
1209
1210    #[test]
1211    fn parse_normalizes_error_alias_to_blocked() {
1212        let input =
1213            r#"{"status":"error","summary":"failed","accomplished":[],"remaining":[],"files":[]}"#;
1214        let resp = parse(input).unwrap();
1215        assert_eq!(resp.status, "blocked");
1216    }
1217
1218    #[test]
1219    fn parse_normalizes_failed_alias_to_blocked() {
1220        let input = r#"{"status":"failed","summary":"could not complete","accomplished":[],"remaining":[],"files":[]}"#;
1221        let resp = parse(input).unwrap();
1222        assert_eq!(resp.status, "blocked");
1223    }
1224
1225    #[test]
1226    fn parse_normalizes_failure_alias_to_blocked() {
1227        let input = r#"{"status":"failure","summary":"could not complete","accomplished":[],"remaining":[],"files":[]}"#;
1228        let resp = parse(input).unwrap();
1229        assert_eq!(resp.status, "blocked");
1230    }
1231
1232    #[test]
1233    fn parse_keeps_canonical_statuses_unchanged() {
1234        for status in &[
1235            "new",
1236            "routed",
1237            "in_progress",
1238            "done",
1239            "blocked",
1240            "in_review",
1241            "needs_review",
1242        ] {
1243            let input = format!(
1244                r#"{{"status":"{status}","summary":"test","accomplished":[],"remaining":[],"files":[]}}"#
1245            );
1246            let resp = parse(&input).unwrap();
1247            assert_eq!(
1248                resp.status, *status,
1249                "canonical status '{status}' should be unchanged"
1250            );
1251        }
1252    }
1253
1254    #[test]
1255    fn parse_keeps_non_canonical_status_as_is_for_audit_trail() {
1256        // Non-canonical statuses that are not in the alias map are kept as-is
1257        // so operators can identify which statuses need to be added to normalize_status.
1258        let input = r#"{"status":"fix_deployed","summary":"deployed","accomplished":[],"remaining":[],"files":[]}"#;
1259        let resp = parse(input).unwrap();
1260        // Kept as-is (not normalized away) so build_run_audit can report it explicitly.
1261        assert_eq!(resp.status, "fix_deployed");
1262    }
1263
1264    #[test]
1265    fn parse_normalizes_heuristic_completion_alias_to_done() {
1266        // #3627: bare "addressed" and compound "duplicate_skipped" are not in the
1267        // literal alias map but clearly read as completion via the shared heuristic.
1268        for status in &["addressed", "duplicate_skipped"] {
1269            let input = format!(
1270                r#"{{"status":"{status}","summary":"done","accomplished":[],"remaining":[],"files":[]}}"#
1271            );
1272            let resp = parse(&input).unwrap();
1273            assert_eq!(
1274                resp.status, "done",
1275                "status '{status}' should normalize to done"
1276            );
1277        }
1278    }
1279
1280    #[test]
1281    fn parse_fails_when_summary_present_but_status_missing() {
1282        // Payload contains a supported field but omits status/result — should NOT
1283        // be treated as done. Regression test for gh-issue-2835.
1284        let input = r#"{"summary":"still working","accomplished":[],"remaining":[],"files":[]}"#;
1285        let result = parse(input);
1286        assert!(
1287            result.is_err(),
1288            "missing status should error, not default to done"
1289        );
1290    }
1291
1292    #[test]
1293    fn parse_fails_when_files_present_but_status_missing() {
1294        // Payload contains files/summary but no status — should not default to done.
1295        let input = r#"{"summary":"partial output","files":["src/foo.rs"]}"#;
1296        let result = parse(input);
1297        assert!(
1298            result.is_err(),
1299            "missing status should error, not default to done"
1300        );
1301    }
1302
1303    #[test]
1304    fn parse_fails_when_only_message_present_without_status() {
1305        // Payload contains only a message field, no status — should not default to done.
1306        let input = r#"{"message":"working on it"}"#;
1307        let result = parse(input);
1308        assert!(
1309            result.is_err(),
1310            "missing status should error, not default to done"
1311        );
1312    }
1313
1314    // ── Regression tests for gh-issue-2880 ───────────────────────────────
1315
1316    #[test]
1317    fn parse_regression_2880_ready_for_review_normalized() {
1318        // ready_for_review should be normalized to needs_review.
1319        let input = r#"{"status":"ready_for_review","summary":"Ready for review","accomplished":["done"],"remaining":[],"files":["src/main.rs"]}"#;
1320        let resp = parse(input).unwrap();
1321        assert_eq!(resp.status, "needs_review");
1322    }
1323
1324    #[test]
1325    fn parse_regression_2880_status_with_output_accepted() {
1326        // status + output SHOULD be accepted (output is a substantive field).
1327        // This was already supported via summary extraction in map_generic_response.
1328        let input = r#"{"status":"done","output":"All tests passed"}"#;
1329        let resp = parse(input).unwrap();
1330        assert_eq!(resp.status, "done");
1331    }
1332
1333    #[test]
1334    fn parse_regression_2880_mixed_ndjson_chooses_best_candidate() {
1335        // In a mixed NDJSON stream:
1336        // - First blob: file path as status (like the bug)
1337        // - Later blob: proper response with done status
1338        // The parser should prefer the one with known status.
1339        let input = r#"{"status":"src/channels/discord_ws.rs","summary":"","accomplished":[],"remaining":[],"files":[]}
1340{"status":"done","summary":"Fixed websocket timeout","accomplished":["fixed"],"remaining":[],"files":["src/channels/discord_ws.rs"]}"#;
1341        let resp = parse(input).unwrap();
1342        // The parser now prefers known statuses, so it should pick the "done" one.
1343        assert_eq!(resp.status, "done");
1344        assert_eq!(resp.summary, "Fixed websocket timeout");
1345    }
1346
1347    #[test]
1348    fn parse_regression_2880_normalize_aliases() {
1349        // Verify all status aliases are normalized correctly.
1350        for (input, expected) in [
1351            ("ok", "done"),
1352            ("success", "done"),
1353            ("completed", "done"),
1354            ("complete", "done"),
1355            ("skipped", "done"),
1356            ("skip", "done"),
1357            ("no_changes_needed", "done"),
1358            ("no_trades_no_positions", "done"),
1359            ("changes_made", "done"),
1360            ("changes_pushed", "done"),
1361            ("changes_addressed", "done"),
1362            ("changes_requested_addressed", "done"),
1363            ("fixed", "done"),
1364            ("running", "in_progress"),
1365            ("partial", "in_progress"),
1366            ("reviewing", "in_review"),
1367            ("pending_review", "needs_review"),
1368            ("ready_for_review", "needs_review"),
1369            ("error", "blocked"),
1370            ("failed", "blocked"),
1371        ] {
1372            let input = format!(
1373                r#"{{"status":"{input}","summary":"test","accomplished":[],"remaining":[],"files":[]}}"#
1374            );
1375            let resp = parse(&input).unwrap();
1376            assert_eq!(
1377                resp.status, expected,
1378                "status '{input}' should normalize to '{expected}'"
1379            );
1380        }
1381    }
1382
1383    #[test]
1384    fn parse_regression_2880_telemetry_skipped() {
1385        // Telemetry objects without proper response structure should be ignored.
1386        let input = r#"{"type":"telemetry","event":"tool_call"}
1387{"status":"done","summary":"Work complete","accomplished":["done"],"remaining":[],"files":["src/main.rs"]}"#;
1388        let resp = parse(input).unwrap();
1389        assert_eq!(resp.status, "done");
1390        assert_eq!(resp.summary, "Work complete");
1391    }
1392
1393    // ── Regression tests for gh-issue-2979 ───────────────────────────────
1394
1395    #[test]
1396    fn parse_regression_2979_success_true_envelope() {
1397        // Claude returns prose + fenced JSON with `success: true` instead of `status`.
1398        // Reproduces internal:148284 attempt 3.
1399        let input = r#"The fix removes all actionable entry/SL/TP/R:R parameters from the bearish-mode trade section. The three candidates are now a plain watchlist table.
1400
1401```json
1402{"success": true, "summary": "Fixed bearish/longs contradiction: replaced actionable long setups with a non-executable watchlist table."}
1403```"#;
1404        let resp = parse(input).unwrap();
1405        assert_eq!(resp.status, "done");
1406        assert_eq!(
1407            resp.summary,
1408            "Fixed bearish/longs contradiction: replaced actionable long setups with a non-executable watchlist table."
1409        );
1410    }
1411
1412    #[test]
1413    fn parse_regression_2979_type_task_complete_envelope() {
1414        // Claude returns prose + fenced JSON with `type: "task_complete"` instead of `status`.
1415        // Reproduces internal:147845 attempt 7.
1416        let input = r#"The daily trending doc is complete at md/research/2026-04-22-daily-trending.md.
1417
1418```json
1419{
1420  "type": "task_complete",
1421  "summary": "Fetched global trending topics and saved to md/research/2026-04-22-daily-trending.md.",
1422  "files_changed": ["md/research/2026-04-22-daily-trending.md"]
1423}
1424```"#;
1425        let resp = parse(input).unwrap();
1426        assert_eq!(resp.status, "done");
1427        assert!(resp.summary.contains("Fetched global trending topics"));
1428        assert_eq!(resp.files, vec!["md/research/2026-04-22-daily-trending.md"]);
1429    }
1430
1431    #[test]
1432    fn parse_regression_2979_tests_passed_envelope() {
1433        // Claude returns prose + fenced JSON with `tests_passed: true` and `files_modified`.
1434        // Reproduces task 2955 attempt 9.
1435        let input = r#"PR created: gabrielkoerich/orch#2969
1436
1437The fix from attempt #8 was already committed. All quality gates pass.
1438
1439```json
1440{
1441  "summary": "Retry watermark persistence on store failure.",
1442  "files_modified": ["src/engine/review_poll.rs"],
1443  "pr_url": "https://github.com/gabrielkoerich/orch/pull/2969",
1444  "tests_passed": true,
1445  "quality_gates": ["cargo fmt", "cargo clippy", "cargo nextest run"]
1446}
1447```"#;
1448        let resp = parse(input).unwrap();
1449        assert_eq!(resp.status, "done");
1450        assert!(resp.summary.contains("Retry watermark persistence"));
1451        assert_eq!(resp.files, vec!["src/engine/review_poll.rs"]);
1452    }
1453
1454    #[test]
1455    fn parse_regression_2979_success_false_does_not_infer_done() {
1456        // success: false should NOT infer done — only success: true triggers inference.
1457        let input = r#"```json
1458{"success": false, "summary": "Could not complete the task."}
1459```"#;
1460        let result = parse(input);
1461        // success: false has no `status` and `success` is not a valid status value,
1462        // and infer_completion_status only fires for success=true, so this must error.
1463        assert!(
1464            result.is_err(),
1465            "success: false should not be treated as done"
1466        );
1467    }
1468
1469    #[test]
1470    fn parse_regression_2979_type_other_does_not_infer_done() {
1471        // type: "something_else" should NOT infer done.
1472        let input = r#"{"type": "tool_call", "summary": "calling bash"}"#;
1473        let result = parse(input);
1474        assert!(
1475            result.is_err(),
1476            "type other than task_complete should not be treated as done"
1477        );
1478    }
1479
1480    #[test]
1481    fn parse_regression_2979_files_modified_alias() {
1482        // files_modified should be picked up as the files list.
1483        let input = r#"{"status": "done", "summary": "done", "files_modified": ["src/foo.rs", "src/bar.rs"]}"#;
1484        let resp = parse(input).unwrap();
1485        assert_eq!(resp.files, vec!["src/foo.rs", "src/bar.rs"]);
1486    }
1487
1488    // ── Regression tests for gh-issue-3336 ───────────────────────────────
1489
1490    #[test]
1491    fn parse_regression_3336_jsonl_domain_status_field_rejected() {
1492        // Career pipeline JSONL output. Neither record has an orch canonical status
1493        // and neither has any substantive orch fields — must be rejected, not returned
1494        // with domain status "inbound-not-submitted" as the task status.
1495        let input = r#"{"date":"2026-06-15","role":"Senior Solana Engineer","company":"M0","status":"inbound-not-submitted","source":"referral"}
1496{"date":"2026-06-15","role":"Rust Engineer (Solana)","company":"Exo Tech","status":"applied-follow-up-overdue","source":"linkedin"}"#;
1497        let err = parse(input).unwrap_err();
1498        let msg = err.to_string();
1499        assert!(
1500            msg.contains("agent output is not valid JSON or a supported JSON wrapper")
1501                || msg.contains("JSON object lacks substantive"),
1502            "unexpected error: {msg}"
1503        );
1504    }
1505
1506    #[test]
1507    fn parse_regression_3336_single_domain_record_rejected() {
1508        // A single domain JSON record with a non-canonical status and no orch fields.
1509        let input = r#"{"status":"inbound-not-submitted","date":"2026-06-15","role":"Engineer","company":"Acme"}"#;
1510        let err = parse(input).unwrap_err();
1511        let msg = err.to_string();
1512        assert!(
1513            msg.contains("agent output is not valid JSON or a supported JSON wrapper")
1514                || msg.contains("JSON object lacks substantive"),
1515            "unexpected error: {msg}"
1516        );
1517    }
1518
1519    #[test]
1520    fn parse_regression_3336_noncanonical_status_with_summary_still_accepted() {
1521        // A non-canonical orch status WITH a summary is a real agent response and must
1522        // still be accepted (not broken by the substantive-field guard).
1523        let input = r#"{"status":"fix_deployed","summary":"deployed to staging","accomplished":[],"remaining":[],"files":[]}"#;
1524        let resp = parse(input).unwrap();
1525        assert_eq!(resp.status, "fix_deployed");
1526        assert_eq!(resp.summary, "deployed to staging");
1527    }
1528
1529    #[test]
1530    fn parse_regression_3336_jsonl_domain_plus_orch_response_prefers_orch() {
1531        // JSONL output where domain records precede an actual orch response with a
1532        // canonical status. The parser must pick the orch response.
1533        let input = r#"{"date":"2026-06-15","role":"Senior Solana Engineer","company":"M0","status":"inbound-not-submitted","source":"referral"}
1534{"date":"2026-06-15","role":"Rust Engineer (Solana)","company":"Exo Tech","status":"applied-follow-up-overdue","source":"linkedin"}
1535{"status":"done","summary":"Career radar written to md/career/2026-06-15-radar.md","accomplished":["Wrote career radar"],"remaining":[],"files":["md/career/2026-06-15-radar.md"]}"#;
1536        let resp = parse(input).unwrap();
1537        assert_eq!(resp.status, "done");
1538        assert_eq!(
1539            resp.summary,
1540            "Career radar written to md/career/2026-06-15-radar.md"
1541        );
1542        assert_eq!(resp.files, vec!["md/career/2026-06-15-radar.md"]);
1543    }
1544
1545    #[test]
1546    fn parse_regression_3336_noncanonical_with_output_accepted() {
1547        // A non-canonical status with `output` (handled by map_generic_response but not a
1548        // struct field on AgentResponse) must still be accepted — not rejected with a parse
1549        // error. Previously `has_substantive_fields` checked the deserialized struct and
1550        // missed `output`, causing this to fail with "JSON object lacks substantive".
1551        let input = r#"{"status":"mystery_status","output":"All tests passed"}"#;
1552        let resp = parse(input).unwrap();
1553        assert_eq!(resp.status, "mystery_status");
1554    }
1555
1556    #[test]
1557    fn parse_regression_3336_noncanonical_with_message_accepted() {
1558        // Same as above for `message` — also substantive but absent from the AgentResponse
1559        // struct, so direct deserialization leaves summary empty.
1560        let input = r#"{"status":"mystery_status","message":"All tests passed"}"#;
1561        let resp = parse(input).unwrap();
1562        assert_eq!(resp.status, "mystery_status");
1563    }
1564}