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