Skip to main content

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