Skip to main content

orch/engine/runner/
response.rs

1//! Response collection + error classification.
2//!
3//! After the agent finishes (tmux session ends), this module:
4//! 1. Reads the output file
5//! 2. Parses the response JSON
6//! 3. Classifies errors (timeout, usage limit, auth, tooling)
7//! 4. Determines next action (success, reroute, needs_review)
8
9use crate::store;
10use crate::store::TaskStore;
11use std::path::{Path, PathBuf};
12use std::sync::Arc;
13
14const JITTER_FACTOR: f64 = 0.3;
15
16/// Maximum output file size to read (10 MB).
17/// Prevents runaway outputs from consuming excessive memory.
18const MAX_OUTPUT_SIZE_BYTES: u64 = 10 * 1024 * 1024;
19
20/// Read a file with a size limit, returning truncated content if the file is too large.
21///
22/// This prevents runaway agent outputs from causing memory issues. If the file
23/// exceeds the limit, reads from the end of the file to capture the most recent
24/// output (which is typically where the result or error message is).
25fn read_file_with_limit<P: AsRef<Path>>(path: P, max_bytes: u64) -> anyhow::Result<String> {
26    use std::fs::File;
27    use std::io::{Read, Seek, SeekFrom};
28
29    let path = path.as_ref();
30    let metadata = std::fs::metadata(path)?;
31
32    if !metadata.is_file() {
33        anyhow::bail!("not a file: {}", path.display());
34    }
35
36    let file_size = metadata.len();
37
38    // If file is within limits, read the whole thing
39    if file_size <= max_bytes {
40        return std::fs::read_to_string(path).map_err(|e| e.into());
41    }
42
43    // File is too large - read from the end to get the most recent output
44    let mut file = File::open(path)?;
45    let start_pos = file_size.saturating_sub(max_bytes);
46    file.seek(SeekFrom::Start(start_pos))?;
47
48    let mut buffer = Vec::with_capacity(max_bytes as usize);
49    file.read_to_end(&mut buffer)?;
50
51    // Try to convert to UTF-8, replacing invalid sequences
52    let content = String::from_utf8_lossy(&buffer);
53
54    // Log a warning about truncation
55    tracing::warn!(
56        path = %path.display(),
57        file_size = file_size,
58        max_bytes = max_bytes,
59        "output file truncated: exceeded size limit"
60    );
61
62    Ok(content.into_owned())
63}
64
65/// Calculate exponential backoff with jitter for fallback retries.
66/// Uses retry count from the reroute chain to determine the delay.
67///
68/// Delay = min(base * 2^retry_count, max) * (1 + jitter)
69pub(crate) fn calculate_backoff_delay(retry_count: usize) -> u64 {
70    let base_delay = crate::engine::router::config::retry_base_delay_ms();
71    let max_delay = crate::engine::router::config::retry_max_delay_ms();
72
73    // Exponential: base * 2^retry_count
74    let exponential = base_delay * (2_u64.saturating_pow(retry_count as u32));
75    let capped = exponential.min(max_delay);
76
77    // Add jitter: ±30% using a hash-based pseudo-random value.
78    // Mix system time (nanoseconds) with thread ID so concurrent retries on
79    // different threads get different delays even when called in the same
80    // microsecond, avoiding the thundering-herd problem.
81    let jitter_range = (capped as f64 * JITTER_FACTOR) as u64;
82    let jitter = {
83        use std::collections::hash_map::DefaultHasher;
84        use std::hash::{Hash, Hasher};
85        let mut h = DefaultHasher::new();
86        std::time::SystemTime::now().hash(&mut h);
87        std::thread::current().id().hash(&mut h);
88        h.finish() % (jitter_range * 2 + 1)
89    };
90
91    capped.saturating_sub(jitter_range) + jitter
92}
93
94fn fallback_retry_count(task: Option<&crate::store::Task>) -> usize {
95    task.map(|t| {
96        let chain_retry_count = t
97            .limit_reroute_chain
98            .split(',')
99            .filter(|entry| !entry.is_empty())
100            .count();
101        let network_retry_count = t.network_retries.max(0) as usize;
102        chain_retry_count.max(network_retry_count)
103    })
104    .unwrap_or(0)
105}
106
107/// Wait with exponential backoff before retrying with a fallback agent.
108/// Returns the delay applied in milliseconds.
109pub async fn wait_for_fallback_backoff(
110    task_id: &str,
111    store: &Option<Arc<TaskStore>>,
112    repo: &str,
113) -> u64 {
114    let task = store::opt_store_get_task(store, repo, task_id).await;
115
116    // Normal failover uses reroute chain length. NetworkError retries bypass
117    // failover, so track their own streak and use whichever retry source is larger.
118    let retry_count = fallback_retry_count(task.as_ref());
119
120    let delay = calculate_backoff_delay(retry_count);
121
122    if delay > 0 {
123        tracing::debug!(
124            task_id,
125            retry_count = retry_count,
126            delay_ms = delay,
127            "fallback backoff: waiting before retry"
128        );
129        tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
130    }
131
132    delay
133}
134
135/// Outcome signal for the engine to update router weights.
136///
137/// Returned by the task runner so the engine can feed rate limit and
138/// success signals back to the router's weighted round-robin implementation.
139#[derive(Debug, Clone)]
140pub enum WeightSignal {
141    /// Agent completed a task successfully.
142    Success { agent: String },
143    /// Agent hit a rate limit / usage limit.
144    RateLimited { agent: String },
145    /// Task is blocked on child tasks (delegations). Do not trigger review agent.
146    Blocked,
147    /// Task was rerouted (silence detection, timeout, parse error) — reset to new for re-routing.
148    /// Distinct from None so the engine never converts a silent-reset task into needs_review.
149    Rerouted,
150    /// No weight-relevant signal (guard skipped task, unrecognised status, etc.)
151    None,
152}
153
154/// Read the agent's output file, trying multiple locations.
155///
156/// Checks per-task attempt directory first, then legacy flat paths.
157/// Output is truncated to `MAX_OUTPUT_SIZE_BYTES` to prevent runaway memory usage.
158pub async fn read_output_file(task_id: &str, primary_path: &Path, repo: &str) -> String {
159    // Primary: explicit output file (already points to attempt dir)
160    if let Some(content) = tokio::task::spawn_blocking({
161        let p = primary_path.to_path_buf();
162        move || read_file_with_limit(p, MAX_OUTPUT_SIZE_BYTES)
163    })
164    .await
165    .ok()
166    .and_then(|r| r.ok())
167    {
168        if !content.is_empty() {
169            return content;
170        }
171    }
172
173    // Fallback: check all attempt dirs for this task (newest first)
174    if let Ok(task_dir) = crate::home::task_dir_async(repo, task_id).await {
175        let attempts_dir = task_dir.join("attempts");
176        // Use async metadata for is_dir check
177        if tokio::fs::metadata(&attempts_dir)
178            .await
179            .map(|m| m.is_dir())
180            .unwrap_or(false)
181        {
182            let mut attempt_nums: Vec<u32> = tokio::task::spawn_blocking({
183                let a = attempts_dir.clone();
184                move || {
185                    match std::fs::read_dir(&a) {
186                        Ok(entries) => {
187                            let mut nums = Vec::new();
188                            for entry in entries {
189                                match entry {
190                                    Ok(e) => {
191                                        if let Some(n) =
192                                            e.file_name().to_str().and_then(|n| n.parse().ok())
193                                        {
194                                            nums.push(n);
195                                        }
196                                    }
197                                    Err(e) => tracing::warn!(
198                                        path = %a.display(),
199                                        err = %e,
200                                        "error reading attempt dir entry in output fallback"
201                                    ),
202                                }
203                            }
204                            nums
205                        }
206                        Err(e) => {
207                            tracing::warn!(path = %a.display(), err = %e, "failed to read attempts dir in output fallback");
208                            Vec::new()
209                        }
210                    }
211                }
212            })
213            .await
214            .unwrap_or_default();
215
216            attempt_nums.sort_unstable_by(|a, b| b.cmp(a)); // newest first
217            for n in attempt_nums {
218                let p = attempts_dir.join(n.to_string()).join("output.json");
219                if let Some(content) = tokio::task::spawn_blocking({
220                    let p = p.clone();
221                    move || read_file_with_limit(p, MAX_OUTPUT_SIZE_BYTES)
222                })
223                .await
224                .ok()
225                .and_then(|r| r.ok())
226                {
227                    if !content.is_empty() {
228                        tracing::info!(task_id, path = %p.display(), "read output from attempt dir");
229                        return content;
230                    }
231                }
232            }
233        }
234    }
235
236    // Legacy fallback locations
237    let state_dir = crate::home::state_dir().unwrap_or_else(|_| PathBuf::from("/tmp"));
238
239    let mut fallbacks = vec![
240        PathBuf::from(format!("/tmp/output-{task_id}.json")),
241        state_dir.join(format!("output-{task_id}.json")),
242    ];
243
244    if let Ok(legacy_path) = crate::home::state_file(&format!("output-{task_id}.json")) {
245        if !fallbacks.contains(&legacy_path) {
246            fallbacks.push(legacy_path);
247        }
248    }
249
250    for path in &fallbacks {
251        if let Some(content) = tokio::task::spawn_blocking({
252            let p = path.clone();
253            move || read_file_with_limit(p, MAX_OUTPUT_SIZE_BYTES)
254        })
255        .await
256        .ok()
257        .and_then(|r| r.ok())
258        {
259            if !content.is_empty() {
260                tracing::info!(task_id, path = %path.display(), "read output from legacy fallback");
261                return content;
262            }
263        }
264    }
265
266    String::new()
267}
268
269// Cooldown tracking is implemented in `crate::engine::cooldown` (shared with the router).
270pub use crate::engine::cooldown::{
271    clear_expired_cooldowns, is_agent_in_cooldown, is_model_in_cooldown,
272    record_agent_failure_with_message, record_model_failure, set_agent_cooldown,
273};
274
275/// Pick a fallback agent, avoiding agents already in the reroute chain and agents in cooldown.
276pub fn pick_fallback_agent(
277    current_agent: &str,
278    chain: &str,
279    available_agents: &[String],
280) -> Option<String> {
281    // Clear expired cooldowns first
282    clear_expired_cooldowns();
283
284    let chain_set: std::collections::HashSet<&str> = if chain.is_empty() {
285        std::collections::HashSet::new()
286    } else {
287        chain.split(',').collect()
288    };
289
290    // Prefer agents that are not in cooldown and are not heavily degraded
291    // from recent rate-limits. This prevents immediate failover to agents
292    // that have been heavily penalized and likely to fail as well.
293    for agent in available_agents {
294        if agent == current_agent || chain_set.contains(agent.as_str()) {
295            continue;
296        }
297        if is_agent_in_cooldown(agent) {
298            continue;
299        }
300        // Weight-based filtering was removed from this module because it used
301        // a default-constructed AgentWeights (dead code that always returned
302        // true). Keep failover behavior simple here: prefer the first agent
303        // that is not in cooldown and not in the reroute chain. If we later
304        // expose the router's AgentWeights snapshot to this module we can add
305        // weight-based avoidance back in a non-dead way.
306        return Some(agent.clone());
307    }
308
309    None
310}
311
312/// Retryable error types that should trigger agent failover.
313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
314pub enum RetryableError {
315    /// Agent timed out.
316    Timeout,
317    /// Usage/rate limit hit.
318    UsageLimit,
319    /// Auth/billing error.
320    AuthError,
321    /// General failure (non-retryable but we still try fallback agents).
322    Failed,
323    /// Missing tooling - fallback might help if another agent has the tool.
324    MissingTooling,
325    /// A specific model was unavailable (e.g. "Model not found"). The agent
326    /// itself is fine — only the model is in cooldown. Failover may still pick
327    /// a different agent, but we must not bump the agent-level failure counter.
328    ModelUnavailable,
329}
330
331impl RetryableError {
332    /// Return a short classified string for this error type.
333    /// Used in DB rate-limit metrics and test assertions.
334    #[allow(dead_code)]
335    pub fn type_str(self) -> &'static str {
336        match self {
337            RetryableError::Timeout => "timeout",
338            RetryableError::UsageLimit => "rate_limit",
339            RetryableError::AuthError => "auth_error",
340            RetryableError::ModelUnavailable => "model_unavailable",
341            RetryableError::Failed | RetryableError::MissingTooling => "failed",
342        }
343    }
344}
345
346/**
347 * Handle failover for any retryable error type. Returns "new" on reroute (or
348 * retryable exhaustion), "blocked" on hard exhaustion, "needs_review" when no
349 * fallback agents are available. `credit_recorded` means the caller already ran
350 * `record_credit_exhaustion`; the generic `failure_count:` counter must not be
351 * bumped here or the next ordinary failure starts at the extended backoff tier
352 * (issue #3652). Rate-limit event DB recording is done by the caller (mod.rs)
353 **/
354pub async fn handle_failover(
355    task_id: &str,
356    agent_name: &str,
357    error_type: RetryableError,
358    error_message: &str,
359    credit_recorded: bool,
360    store: &Option<Arc<TaskStore>>,
361    repo: &str,
362) -> String {
363    // Get the reroute chain
364    let chain = get_reroute_chain(task_id, store, repo).await;
365    let chain = update_reroute_chain(task_id, agent_name, &chain, store, repo).await;
366
367    // Get all available agents
368    let available: Vec<String> = crate::engine::configured_agents()
369        .into_iter()
370        .filter(|a| crate::cmd_cache::command_exists(a))
371        .collect();
372
373    // Check if we've exhausted all agents (build chain_set once)
374    let chain_set: std::collections::HashSet<&str> = if chain.is_empty() {
375        std::collections::HashSet::new()
376    } else {
377        chain.split(',').collect()
378    };
379    let is_exhausted = available.iter().all(|a| chain_set.contains(a.as_str()));
380
381    if is_exhausted {
382        // Retryable failures (rate limits, quota, model unavailable) will resolve once
383        // cooldowns expire — reset to "new" so the router picks it up again then.
384        // Hard failures (generic agent crash, missing tooling) won't improve on retry;
385        // block immediately with a clear reason rather than wasting 63 minutes in the
386        // review-refire loop before getting a misleading "review agent rebroadcast" message.
387        let is_retryable = matches!(
388            error_type,
389            RetryableError::UsageLimit
390                | RetryableError::AuthError
391                | RetryableError::ModelUnavailable
392        );
393        let next_status = if is_retryable { "new" } else { "blocked" };
394
395        tracing::warn!(
396            task_id,
397            agent = agent_name,
398            error_type = ?error_type,
399            next_status,
400            "all agents exhausted"
401        );
402
403        let mut store_fields: Vec<(&str, serde_json::Value)> = Vec::new();
404
405        if is_retryable {
406            // Clear reroute chain so the next dispatch builds a fresh one rather than
407            // immediately seeing "all agents in chain" and exhausting again.
408            let msg = format!("{error_message} (all agents exhausted, will retry when available)");
409            store_fields.push(("last_error", serde_json::json!(msg)));
410            store_fields.push(("limit_reroute_chain", serde_json::json!("")));
411        } else {
412            let msg = format!("{error_message} (all agents exhausted)");
413            let block_reason = format!(
414                "all agents exhausted: {} — {}",
415                error_type.type_str(),
416                error_message
417            );
418            store_fields.push(("last_error", serde_json::json!(msg)));
419            store_fields.push(("block_reason", serde_json::json!(block_reason)));
420        }
421
422        if let Err(e) = store::store_set_result(store, repo, task_id, &store_fields).await {
423            tracing::warn!(task_id, err = %e, "failed to write agents_exhausted fields to store");
424        }
425
426        // If this was a timeout, ensure the agent is placed into cooldown
427        // so the router's round-robin avoids it for a while.
428        if matches!(error_type, RetryableError::Timeout) {
429            record_agent_failure_with_message(agent_name, error_message).await;
430        }
431
432        // Log reroute activity for exhausted agents
433        let details = serde_json::json!({
434            "failure_reason": error_type.type_str(),
435            "error_message": error_message,
436            "chain": chain,
437            "agents_exhausted": true,
438            "is_retryable": is_retryable,
439        });
440        crate::store::store_log_activity(
441            store,
442            repo,
443            task_id,
444            "rerouted",
445            Some("in_progress"),
446            Some(next_status),
447            None::<&str>,
448            None::<&str>,
449            Some(&details),
450        )
451        .await;
452
453        return next_status.to_string();
454    }
455
456    // Pick a fallback agent
457    if let Some(next) = pick_fallback_agent(agent_name, &chain, &available) {
458        tracing::info!(
459            task_id,
460            from = agent_name,
461            to = next,
462            error_type = ?error_type,
463            "failover: switching to fallback agent"
464        );
465
466        // Record agent failure for cooldown tracking. Skipped for
467        // MissingTooling/ModelUnavailable; see handle_failover docs above
468        if !matches!(
469            error_type,
470            RetryableError::MissingTooling | RetryableError::ModelUnavailable
471        ) {
472            // Credit errors skip the generic counter (already counted via
473            // credit_failure_count); the 120s cooldown below still applies
474            if !credit_recorded {
475                record_agent_failure_with_message(agent_name, error_message).await;
476            }
477
478            // Apply brief 120s cooldown on the failed agent so the router skips it
479            // on the next routing attempt. This prevents the router from immediately
480            // re-selecting the same agent after clearing both agent and model (#1492).
481            // Also skipped for ModelUnavailable: the agent is healthy.
482            set_agent_cooldown(agent_name, 120).await;
483        }
484
485        let msg = format!("{error_message}, clearing agent/model for re-route");
486        if let Err(e) = store::store_set_result(
487            store,
488            repo,
489            task_id,
490            &[
491                ("agent", serde_json::json!("")),
492                ("model", serde_json::json!("")),
493                ("last_error", serde_json::json!(msg)),
494            ],
495        )
496        .await
497        {
498            tracing::warn!(task_id, err = %e, "failed to write agent/model clear to store");
499        }
500
501        // Apply exponential backoff with jitter before retry.
502        // Return "new" (not "routed") so the task goes through Phase 3a routing
503        // again. This ensures the router actually re-selects a compatible agent+model
504        // via model_for_complexity() instead of bypassing routing and defaulting to
505        // claude in the dispatch loop (#1604).
506        wait_for_fallback_backoff(task_id, store, repo).await;
507
508        // Log reroute activity for successful failover
509        let details = serde_json::json!({
510            "failure_reason": error_type.type_str(),
511            "error_message": error_message,
512            "from_agent": agent_name,
513            "to_agent": next,
514            "chain": chain,
515        });
516        crate::store::store_log_activity(
517            store,
518            repo,
519            task_id,
520            "rerouted",
521            Some("in_progress"),
522            Some("new"),
523            Some(&next),
524            None::<&str>,
525            Some(&details),
526        )
527        .await;
528
529        return "new".to_string();
530    }
531
532    // No fallback available
533    tracing::warn!(task_id, agent = agent_name, "no fallback agents available");
534
535    // Record agent failure for cooldown tracking. Skipped for
536    // MissingTooling/ModelUnavailable and already-counted credit errors
537    if !matches!(
538        error_type,
539        RetryableError::MissingTooling | RetryableError::ModelUnavailable
540    ) && !credit_recorded
541    {
542        record_agent_failure_with_message(agent_name, error_message).await;
543    }
544
545    let msg = format!("{error_message}, no fallback agents");
546    if let Err(e) = store::store_set_result(
547        store,
548        repo,
549        task_id,
550        &[("last_error", serde_json::json!(msg))],
551    )
552    .await
553    {
554        tracing::warn!(task_id, err = %e, "failed to write no_fallback last_error to store");
555    }
556
557    // Log reroute activity for no fallback available
558    let details = serde_json::json!({
559        "failure_reason": error_type.type_str(),
560        "error_message": error_message,
561        "chain": chain,
562        "no_fallback_available": true,
563    });
564    crate::store::store_log_activity(
565        store,
566        repo,
567        task_id,
568        "rerouted",
569        Some("in_progress"),
570        Some("needs_review"),
571        None::<&str>,
572        None::<&str>,
573        Some(&details),
574    )
575    .await;
576
577    "needs_review".to_string()
578}
579
580/// Get the reroute chain from store.
581pub async fn get_reroute_chain(
582    task_id: &str,
583    store: &Option<Arc<TaskStore>>,
584    repo: &str,
585) -> String {
586    store::opt_store_get_task(store, repo, task_id)
587        .await
588        .map(|t| t.limit_reroute_chain)
589        .unwrap_or_default()
590        .trim()
591        .to_string()
592}
593
594/// Update the reroute chain in store.
595pub async fn update_reroute_chain(
596    task_id: &str,
597    current_agent: &str,
598    existing_chain: &str,
599    store: &Option<Arc<TaskStore>>,
600    repo: &str,
601) -> String {
602    let mut chain = existing_chain.to_string();
603    if chain.is_empty() {
604        chain = current_agent.to_string();
605    } else if !chain.split(',').any(|a| a == current_agent) {
606        chain = format!("{chain},{current_agent}");
607    }
608
609    if let Err(e) = store::store_set_result(
610        store,
611        repo,
612        task_id,
613        &[("limit_reroute_chain", serde_json::json!(chain))],
614    )
615    .await
616    {
617        tracing::warn!(task_id, err = %e, "failed to write limit_reroute_chain to store");
618    }
619    chain
620}
621
622/// Review response from the review agent.
623#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
624pub struct ReviewResponse {
625    /// Decision: "approve" | "request_changes"
626    pub decision: String,
627    /// Detailed review feedback.
628    pub notes: String,
629    /// Test results: "pass" | "fail" | "skipped"
630    pub test_results: Option<String>,
631    /// List of issues found.
632    pub issues: Vec<ReviewIssue>,
633}
634
635/// A single issue found during review.
636#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
637pub struct ReviewIssue {
638    /// File path.
639    pub file: String,
640    /// Line number (optional).
641    pub line: Option<u32>,
642    /// Severity: "error" | "warning"
643    pub severity: String,
644    /// Description of the issue.
645    pub description: String,
646}
647
648/// Parse a review response from already-unwrapped text.
649///
650/// Expects the raw result text (already extracted from the agent envelope
651/// by the agent-specific parser). Tries direct JSON parse, then markdown
652/// code block extraction.
653pub fn parse_review_response(text: &str) -> anyhow::Result<ReviewResponse> {
654    let resp = parse_review_json(text)?;
655    if matches!(resp.decision.as_str(), "approve" | "request_changes") {
656        return Ok(resp);
657    }
658
659    // Weak models echo the prompt template ("approve|request_changes"), strip it so it
660    // does not match the "request_changes" keyword
661    let stripped = text.replace("approve|request_changes", "");
662    infer_review_response_from_text(&stripped)
663        .ok_or_else(|| anyhow::anyhow!("invalid review decision: {}", resp.decision))
664}
665
666fn parse_review_json(text: &str) -> anyhow::Result<ReviewResponse> {
667    // Try direct JSON parse
668    if let Ok(resp) = serde_json::from_str::<ReviewResponse>(text) {
669        return Ok(resp);
670    }
671
672    // Try extracting JSON from markdown code blocks
673    if let Some(json_str) = extract_json_block(text) {
674        if let Ok(resp) = serde_json::from_str::<ReviewResponse>(&json_str) {
675            return Ok(resp);
676        }
677    }
678
679    if let Some(resp) = extract_review_response_object(text) {
680        return Ok(resp);
681    }
682
683    anyhow::bail!("failed to parse review response")
684}
685
686fn infer_review_response_from_text(text: &str) -> Option<ReviewResponse> {
687    let lower = text.to_ascii_lowercase();
688    let has_changes_requested =
689        lower.contains("changes requested") || lower.contains("request_changes");
690    if has_changes_requested {
691        return Some(ReviewResponse {
692            decision: "request_changes".to_string(),
693            notes: "Inferred decision from plain-text review output.".to_string(),
694            test_results: None,
695            issues: Vec::new(),
696        });
697    }
698
699    let positive_approval = lower.contains("lgtm")
700        || lower.contains("looks good")
701        || lower.contains("all checks passed")
702        || lower.contains("all tests passed")
703        || lower.contains("no issues found")
704        // "decision is `approve`" or "decision: `approve`" — LLMs often echo the JSON field value
705        || lower.contains("decision is `approve`")
706        || lower.contains("decision: `approve`")
707        || lower.contains("decision is approve")
708        || lower.contains("decision: approve")
709        || (lower.contains("approved")
710            && !lower.contains("not approved")
711            && !lower.contains("unapproved")
712            && !lower.contains("not approving")
713            && !lower.contains("cannot approve")
714            && !lower.contains("can't approve"));
715    if positive_approval {
716        return Some(ReviewResponse {
717            decision: "approve".to_string(),
718            notes: "Inferred decision from plain-text review output.".to_string(),
719            test_results: None,
720            issues: Vec::new(),
721        });
722    }
723
724    None
725}
726
727/// Public entry point for keyword-based review response inference.
728///
729/// Used by `review.rs` when `parse_review_response` fails on the extracted text.
730pub fn infer_review_response(text: &str) -> Option<ReviewResponse> {
731    infer_review_response_from_text(text)
732}
733
734/// Extract the first valid JSON object from markdown code blocks.
735///
736/// Searches for ```json blocks and returns the first one whose content
737/// starts with `{`, skipping non-JSON code blocks.
738fn extract_json_block(text: &str) -> Option<String> {
739    let mut search_from = 0;
740    while let Some(start) = text[search_from..].find("```json") {
741        let abs_start = search_from + start;
742        let after_tag = abs_start + "```json".len();
743        let Some(rest) = text[after_tag..].strip_prefix('\n') else {
744            search_from = after_tag;
745            continue;
746        };
747        let content_start = text.len() - rest.len();
748        let Some(end_offset) = rest.find("```") else {
749            search_from = content_start;
750            continue;
751        };
752        let end = content_start + end_offset;
753        let content = text[content_start..end].trim();
754        if content.starts_with('{') {
755            return Some(content.to_string());
756        }
757        search_from = end + 3;
758    }
759    None
760}
761
762/// Extract a ReviewResponse JSON object from arbitrary text.
763///
764/// Scans for balanced JSON objects and tries to parse them as ReviewResponse.
765fn extract_review_response_object(text: &str) -> Option<ReviewResponse> {
766    let mut start: Option<usize> = None;
767    let mut depth: i32 = 0;
768    let mut in_string = false;
769    let mut escape = false;
770
771    for (idx, ch) in text.char_indices() {
772        if start.is_some() {
773            if in_string {
774                if escape {
775                    escape = false;
776                } else if ch == '\\' {
777                    escape = true;
778                } else if ch == '"' {
779                    in_string = false;
780                }
781                continue;
782            }
783
784            match ch {
785                '"' => in_string = true,
786                '{' => depth += 1,
787                '}' => {
788                    depth -= 1;
789                    if depth == 0 {
790                        debug_assert!(
791                            start.is_some(),
792                            "start must be Some when depth returns to 0"
793                        );
794                        let start_idx = start.unwrap_or(0);
795                        let candidate = &text[start_idx..=idx];
796                        if let Ok(resp) = serde_json::from_str::<ReviewResponse>(candidate) {
797                            return Some(resp);
798                        }
799                        start = None;
800                    }
801                }
802                _ => {}
803            }
804            continue;
805        }
806
807        if ch == '{' {
808            start = Some(idx);
809            depth = 1;
810            in_string = false;
811            escape = false;
812        }
813    }
814
815    None
816}
817
818/// Extract learnings and store as memory for future attempts.
819#[allow(clippy::too_many_arguments)]
820pub async fn store_learnings_from_response(
821    task_id: &str,
822    attempt: u32,
823    agent: &str,
824    model: Option<&str>,
825    response: &crate::parser::AgentResponse,
826    error: Option<&str>,
827    store: &Option<Arc<TaskStore>>,
828    repo: &str,
829    raw_stdout: &str,
830) {
831    // Use agent self-reported files; fall back to NDJSON tool-call extraction when empty.
832    let files_modified = if response.files.is_empty() {
833        let extracted = crate::cli::ndjson::extract_files_changed(raw_stdout);
834        if !extracted.is_empty() {
835            tracing::debug!(
836                task_id,
837                count = extracted.len(),
838                "files_modified: fell back to NDJSON extraction (agent reported none)"
839            );
840        }
841        extracted
842    } else {
843        response.files.clone()
844    };
845
846    // Build the memory entry
847    let entry = crate::store::MemoryEntry {
848        attempt,
849        agent: agent.to_string(),
850        model: model.map(String::from),
851        learnings: response.learnings.clone(),
852        error: error.map(String::from),
853        files_modified,
854        approach: response.summary.clone(),
855        timestamp: chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
856    };
857
858    if let Some(ref st) = store {
859        if let Ok(Some(store_id)) = st.resolve_task_id(repo, task_id).await {
860            if let Err(e) = st.append_memory(store_id, &entry).await {
861                tracing::warn!(task_id, error = ?e, "failed to store memory");
862            } else {
863                tracing::debug!(task_id, attempt, "stored memory for attempt");
864            }
865        }
866    }
867}
868
869/// Store a memory entry for a failed attempt (without a full AgentResponse).
870pub async fn store_failure_memory(
871    task_id: &str,
872    attempt: u32,
873    agent: &str,
874    model: Option<&str>,
875    error: &str,
876    store: &Option<Arc<TaskStore>>,
877    repo: &str,
878) {
879    let entry = crate::store::MemoryEntry {
880        attempt,
881        agent: agent.to_string(),
882        model: model.map(String::from),
883        learnings: vec![],
884        error: Some(error.to_string()),
885        files_modified: vec![],
886        approach: String::new(),
887        timestamp: chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
888    };
889
890    if let Some(ref st) = store {
891        if let Ok(Some(store_id)) = st.resolve_task_id(repo, task_id).await {
892            if let Err(e) = st.append_memory(store_id, &entry).await {
893                tracing::warn!(task_id, error = ?e, "failed to store failure memory");
894            } else {
895                tracing::debug!(task_id, attempt, "stored failure memory");
896            }
897        }
898    }
899}
900
901#[cfg(test)]
902mod tests {
903    use super::*;
904    use crate::engine::runner::agents::{find_agent_result, patterns, AgentError};
905    use serial_test::serial;
906
907    #[serial(cooldown_state)]
908    #[test]
909    fn calculate_backoff_delay_jitter_is_centered() {
910        // Run many samples and verify the range is [0.7*capped, 1.3*capped].
911        // We can't control `now` directly, but calling the function many times
912        // exercises different microsecond values and lets us check bounds.
913        let base = crate::engine::router::config::retry_base_delay_ms();
914        let max = crate::engine::router::config::retry_max_delay_ms();
915
916        // retry_count=0 → exponential = base, capped = base (assuming base < max)
917        let capped = base.min(max);
918        let jitter_range = (capped as f64 * JITTER_FACTOR) as u64;
919        let lo = capped.saturating_sub(jitter_range);
920        let hi = capped + jitter_range;
921
922        for _ in 0..200 {
923            let delay = calculate_backoff_delay(0);
924            assert!(
925                delay >= lo && delay <= hi,
926                "delay {delay} out of expected range [{lo}, {hi}]"
927            );
928        }
929    }
930
931    #[serial(cooldown_state)]
932    #[test]
933    fn fallback_retry_count_uses_larger_network_retry_streak() {
934        let task = crate::store::Task {
935            id: 1,
936            external_id: None,
937            repo: "owner/repo".to_string(),
938            origin: "internal".to_string(),
939            title: "test".to_string(),
940            body: String::new(),
941            status: crate::store::TaskStatus::New,
942            source: String::new(),
943            source_id: String::new(),
944            author: String::new(),
945            url: String::new(),
946            labels: vec![],
947            agent: None,
948            model: None,
949            complexity: "simple".to_string(),
950            estimate: 0,
951            route_reason: String::new(),
952            agent_profile: String::new(),
953            selected_skills: String::new(),
954            route_attempts: 0,
955            attempts: 0,
956            branch: String::new(),
957            worktree: String::new(),
958            worktree_cleaned: false,
959            summary: String::new(),
960            last_error: String::new(),
961            parent_id: None,
962            block_reason: None,
963            pr_number: None,
964            pr_review_context: String::new(),
965            last_review_ts: String::new(),
966            review_ts_map: "{}".to_string(),
967            last_comment_review_ts: String::new(),
968            merge_conflict_retries: 0,
969            ci_merge_failures: 0,
970            pr_create_failures: 0,
971            push_failures: 0,
972            network_retries: 3,
973            review_agent_failures: 0,
974            review_cycles: 0,
975            review_invocations: 0,
976            needs_review_refires: 0,
977            review_session_expected: false,
978            input_tokens: 0,
979            output_tokens: 0,
980            input_cost_usd: 0.0,
981            output_cost_usd: 0.0,
982            total_cost_usd: 0.0,
983            model_reroute_chain: String::new(),
984            limit_reroute_chain: "claude".to_string(),
985            memory: vec![],
986            delegations: vec![],
987            auto_unblock_count: 0,
988            auto_unblock_last_at: String::new(),
989            auto_unblock_last_reason: String::new(),
990            ci_recovery_count: 0,
991            no_code_reroutes: 0,
992            no_code_last_agent: String::new(),
993            created_at: String::new(),
994            updated_at: String::new(),
995        };
996
997        assert_eq!(fallback_retry_count(Some(&task)), 3);
998    }
999
1000    #[serial(cooldown_state)]
1001    #[test]
1002    fn retryable_type_str_returns_correct_labels() {
1003        assert_eq!(RetryableError::Timeout.type_str(), "timeout");
1004        assert_eq!(RetryableError::UsageLimit.type_str(), "rate_limit");
1005        assert_eq!(RetryableError::AuthError.type_str(), "auth_error");
1006        assert_eq!(RetryableError::Failed.type_str(), "failed");
1007        assert_eq!(RetryableError::MissingTooling.type_str(), "failed");
1008    }
1009
1010    #[serial(cooldown_state)]
1011    #[test]
1012    fn is_usage_limit_detects_rate_limit() {
1013        assert!(patterns::detect_rate_limit("Error: rate limit exceeded").is_some());
1014        assert!(patterns::detect_rate_limit("HTTP 429 Too Many Requests").is_some());
1015        assert!(patterns::detect_rate_limit("quota exceeded for model").is_some());
1016        // context_length_exceeded is handled by detect_context_overflow, not detect_rate_limit
1017        assert!(patterns::detect_context_overflow("context_length_exceeded").is_some());
1018    }
1019
1020    #[serial(cooldown_state)]
1021    #[test]
1022    fn is_usage_limit_rejects_normal_text() {
1023        assert!(patterns::detect_rate_limit("task completed successfully").is_none());
1024        assert!(patterns::detect_rate_limit("").is_none());
1025    }
1026
1027    #[serial(cooldown_state)]
1028    #[test]
1029    fn is_auth_error_detects_common_patterns() {
1030        assert!(patterns::detect_auth_error("401 Unauthorized").is_some());
1031        assert!(patterns::detect_auth_error("invalid api key provided").is_some());
1032        assert!(patterns::detect_auth_error("Your billing plan has expired").is_some());
1033        assert!(patterns::detect_auth_error("Error: 403 Forbidden").is_some());
1034    }
1035
1036    #[serial(cooldown_state)]
1037    #[test]
1038    fn is_auth_error_rejects_normal_text() {
1039        assert!(patterns::detect_auth_error("task completed successfully").is_none());
1040        assert!(patterns::detect_auth_error("").is_none());
1041    }
1042
1043    #[serial(cooldown_state)]
1044    #[test]
1045    fn detect_missing_tooling_finds_known_tools() {
1046        let result = patterns::detect_missing_tool("bun: command not found");
1047        assert!(result.is_some());
1048        if let AgentError::MissingTool { tool } = result.unwrap() {
1049            assert_eq!(tool, "bun");
1050        } else {
1051            panic!("expected MissingTool error");
1052        }
1053
1054        let result = patterns::detect_missing_tool("env: anchor: no such file");
1055        assert!(result.is_some());
1056        if let AgentError::MissingTool { tool } = result.unwrap() {
1057            assert_eq!(tool, "anchor");
1058        } else {
1059            panic!("expected MissingTool error");
1060        }
1061
1062        let result = patterns::detect_missing_tool("spawn docker enoent");
1063        assert!(result.is_some());
1064        if let AgentError::MissingTool { tool } = result.unwrap() {
1065            assert_eq!(tool, "docker");
1066        } else {
1067            panic!("expected MissingTool error");
1068        }
1069    }
1070
1071    #[serial(cooldown_state)]
1072    #[test]
1073    fn detect_missing_tooling_returns_none_for_normal() {
1074        assert!(patterns::detect_missing_tool("everything works fine").is_none());
1075        assert!(patterns::detect_missing_tool("").is_none());
1076    }
1077
1078    // ── Cooldown tests ────────────────────────────────────────────
1079
1080    #[serial(cooldown_state)]
1081    #[tokio::test]
1082    async fn record_and_check_agent_cooldown() {
1083        crate::engine::cooldown::reset_global_state().await;
1084        // Use unique names to avoid interference from other tests
1085        let agent = "test_cooldown_agent_1";
1086        assert!(!is_agent_in_cooldown(agent));
1087        record_agent_failure_with_message(agent, "").await;
1088        assert!(is_agent_in_cooldown(agent));
1089    }
1090
1091    #[serial(cooldown_state)]
1092    #[tokio::test]
1093    async fn record_and_check_model_cooldown() {
1094        crate::engine::cooldown::reset_global_state().await;
1095        let agent = "test_cooldown_agent_2";
1096        let model = "test_model_x";
1097        assert!(!is_model_in_cooldown(agent, model));
1098        record_model_failure(agent, model).await;
1099        assert!(is_model_in_cooldown(agent, model));
1100        // Different model should not be in cooldown
1101        assert!(!is_model_in_cooldown(agent, "other_model"));
1102    }
1103
1104    #[serial(cooldown_state)]
1105    #[tokio::test]
1106    async fn clear_expired_does_not_remove_fresh_entries() {
1107        crate::engine::cooldown::reset_global_state().await;
1108        let agent = "test_cooldown_agent_3";
1109        record_agent_failure_with_message(agent, "").await;
1110        clear_expired_cooldowns();
1111        // Should still be in cooldown (just recorded)
1112        assert!(is_agent_in_cooldown(agent));
1113    }
1114
1115    // Use fake agent names so other tests don't interfere.
1116    #[serial(cooldown_state)]
1117    #[test]
1118    fn pick_fallback_skips_current_agent() {
1119        let available = vec!["test_agent_a".to_string(), "test_agent_b".to_string()];
1120        let result = pick_fallback_agent("test_agent_a", "", &available);
1121        assert_eq!(result, Some("test_agent_b".to_string()));
1122    }
1123
1124    #[serial(cooldown_state)]
1125    #[test]
1126    fn pick_fallback_skips_chain_agents() {
1127        let available = vec![
1128            "test_agent_a".to_string(),
1129            "test_agent_b".to_string(),
1130            "test_agent_c".to_string(),
1131        ];
1132        let result = pick_fallback_agent("test_agent_a", "test_agent_a,test_agent_b", &available);
1133        assert_eq!(result, Some("test_agent_c".to_string()));
1134    }
1135
1136    #[serial(cooldown_state)]
1137    #[test]
1138    fn pick_fallback_returns_none_when_exhausted() {
1139        let available = vec!["test_agent_a".to_string(), "test_agent_b".to_string()];
1140        let result = pick_fallback_agent("test_agent_a", "test_agent_a,test_agent_b", &available);
1141        assert!(result.is_none());
1142    }
1143
1144    #[serial(cooldown_state)]
1145    #[test]
1146    fn weight_signal_variants() {
1147        let success = WeightSignal::Success {
1148            agent: "claude".to_string(),
1149        };
1150        let limited = WeightSignal::RateLimited {
1151            agent: "codex".to_string(),
1152        };
1153        let none = WeightSignal::None;
1154
1155        // Verify Debug trait
1156        assert!(format!("{success:?}").contains("claude"));
1157        assert!(format!("{limited:?}").contains("codex"));
1158        assert!(format!("{none:?}").contains("None"));
1159    }
1160
1161    #[serial(cooldown_state)]
1162    #[test]
1163    fn parse_review_response_direct_json() {
1164        let json = r#"{"decision":"approve","notes":"LGTM","test_results":"pass","issues":[]}"#;
1165        let resp = parse_review_response(json).unwrap();
1166        assert_eq!(resp.decision, "approve");
1167        assert_eq!(resp.notes, "LGTM");
1168        assert!(resp.issues.is_empty());
1169    }
1170
1171    #[serial(cooldown_state)]
1172    #[test]
1173    fn parse_review_response_from_markdown() {
1174        let md = r#"Here is my review:
1175
1176```json
1177{"decision":"request_changes","notes":"Fix the bug","issues":[{"file":"src/main.rs","line":10,"severity":"error","description":"null deref"}]}
1178```
1179
1180That's all."#;
1181        let resp = parse_review_response(md).unwrap();
1182        assert_eq!(resp.decision, "request_changes");
1183        assert_eq!(resp.issues.len(), 1);
1184        assert_eq!(resp.issues[0].file, "src/main.rs");
1185    }
1186
1187    #[serial(cooldown_state)]
1188    #[test]
1189    fn parse_review_response_embedded_json_object() {
1190        let text = "Review complete.\n\n{\"decision\":\"approve\",\"notes\":\"LGTM\",\"test_results\":\"pass\",\"issues\":[]}\nThanks!";
1191        let resp = parse_review_response(text).unwrap();
1192        assert_eq!(resp.decision, "approve");
1193        assert_eq!(resp.notes, "LGTM");
1194    }
1195
1196    #[serial(cooldown_state)]
1197    #[test]
1198    fn parse_review_response_template_echo_infers_from_notes() {
1199        let json = r#"{"decision":"approve|request_changes","notes":"LGTM","issues":[]}"#;
1200        assert_eq!(parse_review_response(json).unwrap().decision, "approve");
1201
1202        let no_signal = r#"{"decision":"approve|request_changes","notes":"hmm","issues":[]}"#;
1203        assert!(parse_review_response(no_signal).is_err());
1204    }
1205
1206    #[serial(cooldown_state)]
1207    #[test]
1208    fn parse_review_response_invalid() {
1209        let result = parse_review_response("not json at all");
1210        assert!(result.is_err());
1211    }
1212
1213    #[serial(cooldown_state)]
1214    #[test]
1215    fn extract_json_block_basic() {
1216        let md = "text\n```json\n{\"key\": \"value\"}\n```\nmore";
1217        let result = extract_json_block(md);
1218        assert!(result.is_some());
1219        assert!(result.unwrap().contains("\"key\""));
1220    }
1221
1222    #[serial(cooldown_state)]
1223    #[test]
1224    fn extract_json_block_skips_non_json_blocks() {
1225        let md = "```json\nnot-json-array\n```\n\n```json\n{\"real\": true}\n```";
1226        let result = extract_json_block(md);
1227        assert!(result.is_some());
1228        assert!(result.unwrap().contains("\"real\""));
1229    }
1230
1231    #[serial(cooldown_state)]
1232    #[test]
1233    fn extract_json_block_none_when_missing() {
1234        assert!(extract_json_block("no code blocks here").is_none());
1235    }
1236
1237    #[serial(cooldown_state)]
1238    #[test]
1239    fn extract_json_block_skips_malformed_intermediate_blocks() {
1240        let md = "prefix ```json{\"broken\": true}\n\n```json\n{\"real\": true}\n```";
1241        let result = extract_json_block(md);
1242        assert_eq!(result.as_deref(), Some("{\"real\": true}"));
1243    }
1244
1245    #[serial(cooldown_state)]
1246    #[test]
1247    fn extract_json_block_skips_multiple_malformed_intermediate_blocks() {
1248        let md = "prefix ```json{\"broken\": true}\nmid ```json[1, 2, 3]\n\n```json\n{\"real\": true}\n```";
1249        let result = extract_json_block(md);
1250        assert_eq!(result.as_deref(), Some("{\"real\": true}"));
1251    }
1252
1253    // ── parse_review_response + infer_review_response (production path) ─
1254
1255    /// Helper that mirrors the production plain-text path in review.rs:
1256    /// parse_review_response → infer_review_response.
1257    fn parse_review_plain(text: &str) -> anyhow::Result<ReviewResponse> {
1258        parse_review_response(text).or_else(|_| {
1259            infer_review_response(text)
1260                .ok_or_else(|| anyhow::anyhow!("failed to parse review response"))
1261        })
1262    }
1263
1264    #[serial(cooldown_state)]
1265    #[test]
1266    fn parse_review_from_output_direct_json() {
1267        let json = r#"{"decision":"approve","notes":"LGTM","test_results":"pass","issues":[]}"#;
1268        let resp = parse_review_response(json).unwrap();
1269        assert_eq!(resp.decision, "approve");
1270    }
1271
1272    #[serial(cooldown_state)]
1273    #[test]
1274    fn parse_review_from_output_markdown() {
1275        let md = "Review complete.\n\n```json\n{\"decision\":\"request_changes\",\"notes\":\"Fix it\",\"issues\":[]}\n```\n";
1276        let resp = parse_review_response(md).unwrap();
1277        assert_eq!(resp.decision, "request_changes");
1278    }
1279
1280    #[serial(cooldown_state)]
1281    #[test]
1282    fn parse_review_from_output_plain_text_fallback() {
1283        let text = "The review is done — all tests passed and the PR was approved.";
1284        let resp = parse_review_plain(text).unwrap();
1285        assert_eq!(resp.decision, "approve");
1286        assert!(resp.issues.is_empty());
1287    }
1288
1289    /// opencode NDJSON stream — text events use the `part.text` format.
1290    #[serial(cooldown_state)]
1291    #[test]
1292    fn parse_review_from_output_ndjson_part_format() {
1293        let ndjson = concat!(
1294            r#"{"type":"step_start","timestamp":1000,"sessionID":"ses_abc"}"#,
1295            "\n",
1296            r#"{"type":"text","timestamp":1001,"part":{"type":"text","text":"Reviewing the PR...\n\n```json\n{\"decision\":\"approve\",\"notes\":\"All checks pass\",\"test_results\":\"pass\",\"issues\":[]}\n```\n"}}"#,
1297            "\n",
1298            r#"{"type":"step_finish","timestamp":1002,"part":{"type":"step-finish","reason":"stop"}}"#,
1299        );
1300        let resp = parse_via_agent_path("opencode", ndjson).unwrap();
1301        assert_eq!(resp.decision, "approve");
1302        assert_eq!(resp.notes, "All checks pass");
1303    }
1304
1305    /// opencode NDJSON stream — text events use the newer `text` directly-in-event format.
1306    #[serial(cooldown_state)]
1307    #[test]
1308    fn parse_review_from_output_ndjson_direct_text_format() {
1309        let ndjson = concat!(
1310            r#"{"type":"step_start","timestamp":1000,"sessionID":"ses_abc"}"#,
1311            "\n",
1312            r#"{"type":"text","timestamp":1001,"sessionID":"ses_abc","text":"Here is my review:\n\n```json\n{\"decision\":\"request_changes\",\"notes\":\"Fix the bug\",\"test_results\":\"fail\",\"issues\":[]}\n```\n"}"#,
1313            "\n",
1314            r#"{"type":"step_finish","timestamp":1002,"sessionID":"ses_abc"}"#,
1315        );
1316        let resp = parse_via_agent_path("opencode", ndjson).unwrap();
1317        assert_eq!(resp.decision, "request_changes");
1318        assert_eq!(resp.notes, "Fix the bug");
1319    }
1320
1321    /// opencode NDJSON with ReviewResponse JSON directly in a text event (no markdown wrapper).
1322    #[serial(cooldown_state)]
1323    #[test]
1324    fn parse_review_from_output_ndjson_direct_json_in_text_event() {
1325        let ndjson = concat!(
1326            r#"{"type":"step_start","timestamp":1000}"#,
1327            "\n",
1328            r#"{"type":"text","timestamp":1001,"part":{"type":"text","text":"{\"decision\":\"approve\",\"notes\":\"LGTM\",\"test_results\":\"pass\",\"issues\":[]}"}}"#,
1329            "\n",
1330            r#"{"type":"step_finish","timestamp":1002}"#,
1331        );
1332        let resp = parse_via_agent_path("opencode", ndjson).unwrap();
1333        assert_eq!(resp.decision, "approve");
1334    }
1335
1336    #[serial(cooldown_state)]
1337    #[test]
1338    fn parse_review_from_output_ndjson_prefers_final_json_text_event() {
1339        let ndjson = concat!(
1340            r#"{"type":"text","timestamp":1001,"part":{"type":"text","text":"Working on it..."}}"#,
1341            "\n",
1342            r#"{"type":"text","timestamp":1002,"part":{"type":"text","text":"{\"decision\":\"approve\",\"notes\":\"LGTM\",\"test_results\":\"pass\",\"issues\":[]}"}}"#,
1343        );
1344        let resp = parse_via_agent_path("opencode", ndjson).unwrap();
1345        assert_eq!(resp.decision, "approve");
1346        assert_eq!(resp.notes, "LGTM");
1347    }
1348
1349    /// Concatenated text events produce a valid ReviewResponse.
1350    #[serial(cooldown_state)]
1351    #[test]
1352    fn parse_review_from_output_ndjson_concatenated_text() {
1353        let ndjson = concat!(
1354            r#"{"type":"text","timestamp":1001,"part":{"type":"text","text":"Here is my\n"}}"#,
1355            "\n",
1356            r#"{"type":"text","timestamp":1002,"part":{"type":"text","text":"review:\n\n```json\n{\"decision\":\"approve\",\"notes\":\"OK\",\"test_results\":\"pass\",\"issues\":[]}\n```\n"}}"#,
1357        );
1358        let resp = parse_via_agent_path("opencode", ndjson).unwrap();
1359        assert_eq!(resp.decision, "approve");
1360    }
1361
1362    /// codex NDJSON stream — agent_message item carries the ReviewResponse JSON.
1363    ///
1364    /// Real format from codex `exec --json` output (observed 2026-03-06):
1365    /// thread.started / turn.started / item.completed(reasoning) / item.completed(agent_message) / turn.completed
1366    #[serial(cooldown_state)]
1367    #[test]
1368    fn parse_review_from_output_codex_agent_message() {
1369        let ndjson = concat!(
1370            r#"{"type":"thread.started","thread_id":"t1"}"#,
1371            "\n",
1372            r#"{"type":"turn.started"}"#,
1373            "\n",
1374            r#"{"type":"item.completed","item":{"id":"item_0","type":"reasoning","text":"Planning git commands..."}}"#,
1375            "\n",
1376            r#"{"type":"item.completed","item":{"id":"item_1","type":"command_execution","command":"git log --oneline -5","output":"abc123 fix: something"}}"#,
1377            "\n",
1378            r#"{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"{\"decision\":\"approve\",\"notes\":\"All checks pass\",\"test_results\":\"pass\",\"issues\":[]}"}}"#,
1379            "\n",
1380            r#"{"type":"turn.completed"}"#,
1381        );
1382        let resp = parse_via_agent_path("codex", ndjson).unwrap();
1383        assert_eq!(resp.decision, "approve");
1384        assert_eq!(resp.notes, "All checks pass");
1385    }
1386
1387    /// codex NDJSON with ReviewResponse in a markdown code block inside agent_message.
1388    #[serial(cooldown_state)]
1389    #[test]
1390    fn parse_review_from_output_codex_agent_message_markdown() {
1391        let ndjson = concat!(
1392            r#"{"type":"thread.started","thread_id":"t1"}"#,
1393            "\n",
1394            r#"{"type":"turn.started"}"#,
1395            "\n",
1396            r#"{"type":"item.completed","item":{"id":"item_0","type":"reasoning","text":"Reviewing..."}}"#,
1397            "\n",
1398            r#"{"type":"item.completed","item":{"id":"item_1","type":"agent_message","text":"Review complete.\n\n```json\n{\"decision\":\"request_changes\",\"notes\":\"Fix the tests\",\"issues\":[]}\n```\n"}}"#,
1399            "\n",
1400            r#"{"type":"turn.completed"}"#,
1401        );
1402        let resp = parse_via_agent_path("codex", ndjson).unwrap();
1403        assert_eq!(resp.decision, "request_changes");
1404        assert_eq!(resp.notes, "Fix the tests");
1405    }
1406
1407    /// codex reasoning items must NOT be extracted as review text — only agent_message is used.
1408    #[serial(cooldown_state)]
1409    #[test]
1410    fn codex_skips_reasoning_items() {
1411        let ndjson = concat!(
1412            r#"{"type":"item.completed","item":{"type":"reasoning","text":"internal thoughts..."}}"#,
1413            "\n",
1414            r#"{"type":"item.completed","item":{"type":"agent_message","text":"{\"decision\":\"approve\",\"notes\":\"LGTM\",\"issues\":[]}"}}"#,
1415        );
1416        let resp = parse_via_agent_path("codex", ndjson).unwrap();
1417        assert_eq!(resp.decision, "approve");
1418        assert_eq!(resp.notes, "LGTM");
1419    }
1420
1421    /// Negation patterns must NOT trigger a false approval.
1422    #[serial(cooldown_state)]
1423    #[test]
1424    fn infer_review_response_negation_not_approved() {
1425        assert!(
1426            parse_review_plain("The changes were not approved.").is_err(),
1427            "\"not approved\" should not infer approval"
1428        );
1429    }
1430
1431    #[serial(cooldown_state)]
1432    #[test]
1433    fn infer_review_response_negation_unapproved() {
1434        assert!(
1435            parse_review_plain("Unapproved changes found in the diff.").is_err(),
1436            "\"unapproved\" should not infer approval"
1437        );
1438    }
1439
1440    #[serial(cooldown_state)]
1441    #[test]
1442    fn infer_review_response_negation_not_approving() {
1443        assert!(
1444            parse_review_plain("I am not approving this PR.").is_err(),
1445            "\"not approving\" should not infer approval"
1446        );
1447    }
1448
1449    /// Positive plain-text approval signals must still work.
1450    #[serial(cooldown_state)]
1451    #[test]
1452    fn infer_review_response_lgtm() {
1453        let resp = parse_review_plain("LGTM, everything looks fine.").unwrap();
1454        assert_eq!(resp.decision, "approve");
1455    }
1456
1457    #[serial(cooldown_state)]
1458    #[test]
1459    fn infer_review_response_looks_good() {
1460        let resp = parse_review_plain("Looks good to me!").unwrap();
1461        assert_eq!(resp.decision, "approve");
1462    }
1463
1464    /// "All checks passed" should infer approval (real failure observed in task 16393).
1465    #[serial(cooldown_state)]
1466    #[test]
1467    fn infer_review_response_all_checks_passed() {
1468        let resp = parse_review_plain(
1469            "The background task completed but I already got the CI results directly. All checks passed — no action needed.",
1470        )
1471        .unwrap();
1472        assert_eq!(resp.decision, "approve");
1473    }
1474
1475    #[serial(cooldown_state)]
1476    #[test]
1477    fn infer_review_response_checks_passed() {
1478        let resp = parse_review_plain("All checks passed (fmt ✓, clippy ✓, tests ✓).").unwrap();
1479        assert_eq!(resp.decision, "approve");
1480    }
1481
1482    #[serial(cooldown_state)]
1483    #[test]
1484    fn infer_review_response_all_tests_passed() {
1485        let resp =
1486            parse_review_plain("All tests passed and the implementation looks correct.").unwrap();
1487        assert_eq!(resp.decision, "approve");
1488    }
1489
1490    #[serial(cooldown_state)]
1491    #[test]
1492    fn infer_review_response_no_issues_found() {
1493        let resp = parse_review_plain("Review complete. No issues found in the diff.").unwrap();
1494        assert_eq!(resp.decision, "approve");
1495    }
1496
1497    /// Partial "tests passed" mid-sentence must NOT infer approval without "all" prefix.
1498    #[serial(cooldown_state)]
1499    #[test]
1500    fn infer_review_response_partial_tests_passed_no_approve() {
1501        let text = "The existing tests passed before this change but the new payment logic has a null-pointer risk on line 42.";
1502        assert!(parse_review_plain(text).is_err());
1503    }
1504
1505    /// Partial "checks passed" mid-sentence must NOT infer approval without "all" prefix.
1506    #[serial(cooldown_state)]
1507    #[test]
1508    fn infer_review_response_partial_checks_passed_no_approve() {
1509        let text = "CI checks passed for the base branch but this PR adds a broken path.";
1510        assert!(parse_review_plain(text).is_err());
1511    }
1512
1513    /// LLMs sometimes echo the JSON decision field value literally: "Decision is `approve`."
1514    #[serial(cooldown_state)]
1515    #[test]
1516    fn infer_review_response_decision_is_approve_backtick() {
1517        let text = "Already retrieved the output and completed the review above. The CI test check passed (3m11s) and all other checks are green. Decision is `approve`.";
1518        let resp = parse_review_plain(text).unwrap();
1519        assert_eq!(resp.decision, "approve");
1520    }
1521
1522    /// "Decision: approve" without backticks should also match.
1523    #[serial(cooldown_state)]
1524    #[test]
1525    fn infer_review_response_decision_colon_approve() {
1526        let text = "Reviewed the PR. No blocking issues found. Decision: approve";
1527        let resp = parse_review_plain(text).unwrap();
1528        assert_eq!(resp.decision, "approve");
1529    }
1530
1531    /// Bare backtick `approve` in a negative context must NOT infer approval.
1532    /// e.g. "do not `approve`" previously matched the removed `lower.contains("`approve`")` check.
1533    #[serial(cooldown_state)]
1534    #[test]
1535    fn infer_review_response_negation_do_not_approve_backtick() {
1536        let text = "There are unresolved issues — do not `approve` this PR until they are fixed.";
1537        assert!(
1538            parse_review_plain(text).is_err(),
1539            "negative context with backtick approve must not infer approval"
1540        );
1541    }
1542
1543    // ── review parsing via find_agent_result + parse_review_response ────
1544
1545    /// Helper that mirrors the production path in review.rs:
1546    /// find_agent_result → parse_review_response → infer_review_response.
1547    fn parse_via_agent_path(agent: &str, output: &str) -> anyhow::Result<ReviewResponse> {
1548        use crate::engine::runner::agents::find_agent_result;
1549        let text = find_agent_result(agent, output)
1550            .map(|r| r.result_text)
1551            .filter(|t| !t.is_empty())
1552            .unwrap_or_else(|| output.to_string());
1553        if let Ok(r) = parse_review_response(&text) {
1554            return Ok(r);
1555        }
1556        infer_review_response_from_text(&text)
1557            .ok_or_else(|| anyhow::anyhow!("failed to parse review response from {agent} output"))
1558    }
1559
1560    #[serial(cooldown_state)]
1561    #[test]
1562    fn agent_output_claude_ndjson_review() {
1563        let ndjson = concat!(
1564            r#"{"type":"system","subtype":"init","session_id":"s1"}"#,
1565            "\n",
1566            r#"{"type":"assistant","message":{"content":[{"type":"text","text":"Reviewing..."}]}}"#,
1567            "\n",
1568            r#"{"type":"result","subtype":"success","is_error":false,"result":"{\"decision\":\"approve\",\"notes\":\"LGTM\",\"test_results\":\"pass\",\"issues\":[]}","usage":{"input_tokens":100,"output_tokens":20}}"#,
1569        );
1570        let resp = parse_via_agent_path("claude", ndjson).unwrap();
1571        assert_eq!(resp.decision, "approve");
1572    }
1573
1574    #[serial(cooldown_state)]
1575    #[test]
1576    fn agent_output_opencode_ndjson_review() {
1577        let ndjson = concat!(
1578            r#"{"type":"step_start","timestamp":1000}"#,
1579            "\n",
1580            r#"{"type":"text","timestamp":1001,"part":{"type":"text","text":"{\"decision\":\"request_changes\",\"notes\":\"Fix it\",\"issues\":[]}"}}"#,
1581            "\n",
1582            r#"{"type":"step_finish","timestamp":1002,"part":{"type":"step-finish","reason":"stop","tokens":{"input":100,"output":10}}}"#,
1583        );
1584        let resp = parse_via_agent_path("opencode", ndjson).unwrap();
1585        assert_eq!(resp.decision, "request_changes");
1586    }
1587
1588    #[serial(cooldown_state)]
1589    #[test]
1590    fn agent_output_codex_ndjson_review() {
1591        let ndjson = concat!(
1592            r#"{"type":"thread.started","thread_id":"t1"}"#,
1593            "\n",
1594            r#"{"type":"item.completed","item":{"type":"agent_message","text":"{\"decision\":\"approve\",\"notes\":\"All good\",\"issues\":[]}"}}"#,
1595            "\n",
1596            r#"{"type":"turn.completed"}"#,
1597        );
1598        let resp = parse_via_agent_path("codex", ndjson).unwrap();
1599        assert_eq!(resp.decision, "approve");
1600    }
1601
1602    #[serial(cooldown_state)]
1603    #[test]
1604    fn agent_output_plain_text_keyword_fallback() {
1605        let text = "All checks passed, LGTM.";
1606        let resp = parse_via_agent_path("claude", text).unwrap();
1607        assert_eq!(resp.decision, "approve");
1608    }
1609
1610    #[serial(cooldown_state)]
1611    #[test]
1612    fn agent_output_direct_json() {
1613        let json = r#"{"decision":"approve","notes":"LGTM","test_results":"pass","issues":[]}"#;
1614        let resp = parse_via_agent_path("opencode", json).unwrap();
1615        assert_eq!(resp.decision, "approve");
1616    }
1617
1618    /// Regression: plain text containing JSON fragments should NOT trigger false
1619    /// positives. The per-agent extractor returns None for non-NDJSON text,
1620    /// so we fall through to keyword inference instead of generic NDJSON parsing.
1621    #[serial(cooldown_state)]
1622    #[test]
1623    fn agent_output_text_with_json_fragment_no_false_positive() {
1624        let text = r#"I checked the file and found {"type":"text"} in the output. No issues."#;
1625        // This should NOT extract a review from the JSON fragment.
1626        // With the generic parser, this would match as a "text" NDJSON event.
1627        // With per-agent extraction, it returns None (not valid agent NDJSON).
1628        let result = parse_via_agent_path("claude", text);
1629        // Should either fail or infer from keywords, NOT parse the JSON fragment
1630        assert!(
1631            result.is_err() || result.as_ref().is_ok_and(|r| r.decision != "text"),
1632            "should not extract review from embedded JSON fragment"
1633        );
1634    }
1635
1636    /// Prose containing the word "decision" and a JSON-like fragment must not
1637    /// be misidentified as a review response by `extract_review_response_object`.
1638    #[serial(cooldown_state)]
1639    #[test]
1640    fn parse_review_response_ignores_prose_with_decision_word() {
1641        let text = r#"The decision was made. Here is a debug trace: {"trace":123}"#;
1642        assert!(
1643            parse_review_response(text).is_err(),
1644            "prose with 'decision' word and unrelated JSON should not parse as ReviewResponse"
1645        );
1646    }
1647
1648    /// Plain text with an embedded JSON object that has unrelated keys should
1649    /// not be extracted as a review response.
1650    #[serial(cooldown_state)]
1651    #[test]
1652    fn parse_review_response_ignores_embedded_json_without_decision_key() {
1653        let text = r#"Analysis complete. Config: {"timeout":30,"retries":3}. Done."#;
1654        assert!(
1655            parse_review_response(text).is_err(),
1656            "embedded JSON without 'decision' key should not parse as ReviewResponse"
1657        );
1658    }
1659
1660    // ── read_file_with_limit tests ───────────────────────────────────────────
1661
1662    #[serial(cooldown_state)]
1663    #[test]
1664    fn read_file_with_limit_reads_small_file_completely() {
1665        let temp_dir = std::env::temp_dir();
1666        let file_path = temp_dir.join(format!("orch_test_small_{}.txt", std::process::id()));
1667        let content = "Hello, World!";
1668        std::fs::write(&file_path, content).unwrap();
1669
1670        let result = read_file_with_limit(&file_path, 1024);
1671        assert!(result.is_ok());
1672        assert_eq!(result.unwrap(), content);
1673
1674        let _ = std::fs::remove_file(&file_path);
1675    }
1676
1677    #[serial(cooldown_state)]
1678    #[test]
1679    fn read_file_with_limit_truncates_large_file() {
1680        let temp_dir = std::env::temp_dir();
1681        let file_path = temp_dir.join(format!("orch_test_large_{}.txt", std::process::id()));
1682
1683        // Create a file larger than the limit (100 bytes)
1684        let large_content = "x".repeat(200);
1685        std::fs::write(&file_path, &large_content).unwrap();
1686
1687        // Read with a 50-byte limit
1688        let result = read_file_with_limit(&file_path, 50);
1689        assert!(result.is_ok());
1690
1691        let read_content = result.unwrap();
1692        // Should only read 50 bytes (the tail of the file)
1693        assert_eq!(read_content.len(), 50);
1694        assert_eq!(read_content, "x".repeat(50));
1695
1696        let _ = std::fs::remove_file(&file_path);
1697    }
1698
1699    #[serial(cooldown_state)]
1700    #[test]
1701    fn read_file_with_limit_handles_empty_file() {
1702        let temp_dir = std::env::temp_dir();
1703        let file_path = temp_dir.join(format!("orch_test_empty_{}.txt", std::process::id()));
1704        std::fs::write(&file_path, "").unwrap();
1705
1706        let result = read_file_with_limit(&file_path, 1024);
1707        assert!(result.is_ok());
1708        assert_eq!(result.unwrap(), "");
1709
1710        let _ = std::fs::remove_file(&file_path);
1711    }
1712
1713    #[serial(cooldown_state)]
1714    #[test]
1715    fn read_file_with_limit_handles_nonexistent_file() {
1716        let temp_dir = std::env::temp_dir();
1717        let file_path = temp_dir.join("orch_test_nonexistent_xyz123.txt");
1718
1719        let result = read_file_with_limit(&file_path, 1024);
1720        assert!(result.is_err());
1721    }
1722
1723    #[serial(cooldown_state)]
1724    #[test]
1725    fn read_file_with_limit_reads_exact_limit() {
1726        let temp_dir = std::env::temp_dir();
1727        let file_path = temp_dir.join(format!("orch_test_exact_{}.txt", std::process::id()));
1728
1729        // Create exactly 100 bytes
1730        let content = "y".repeat(100);
1731        std::fs::write(&file_path, &content).unwrap();
1732
1733        // Read with exactly 100-byte limit (should read all)
1734        let result = read_file_with_limit(&file_path, 100);
1735        assert!(result.is_ok());
1736        assert_eq!(result.unwrap().len(), 100);
1737
1738        let _ = std::fs::remove_file(&file_path);
1739    }
1740
1741    #[serial(cooldown_state)]
1742    #[test]
1743    fn read_file_with_limit_handles_unicode_truncation() {
1744        let temp_dir = std::env::temp_dir();
1745        let file_path = temp_dir.join(format!("orch_test_unicode_{}.txt", std::process::id()));
1746
1747        // Create content with multi-byte UTF-8 characters
1748        let emoji = "🎉".repeat(100); // Each emoji is 4 bytes
1749        std::fs::write(&file_path, &emoji).unwrap();
1750
1751        // Read with a limit that cuts into the emoji sequence
1752        let result = read_file_with_limit(&file_path, 50);
1753        assert!(result.is_ok());
1754
1755        let read_content = result.unwrap();
1756        // from_utf8_lossy should handle invalid sequences
1757        assert!(!read_content.is_empty());
1758
1759        let _ = std::fs::remove_file(&file_path);
1760    }
1761
1762    // ── Fixture-based review integration tests ──────────────────────────────────
1763
1764    /// Full review pipeline: find_agent_result → parse_review_response → infer_review_response.
1765    fn parse_review_via_agent(agent: &str, output: &str) -> anyhow::Result<ReviewResponse> {
1766        let text = find_agent_result(agent, output)
1767            .map(|r| r.result_text)
1768            .filter(|t| !t.is_empty())
1769            .unwrap_or_else(|| output.to_string());
1770        if let Ok(r) = parse_review_response(&text) {
1771            return Ok(r);
1772        }
1773        infer_review_response(&text)
1774            .ok_or_else(|| anyhow::anyhow!("failed to parse review from {agent} output"))
1775    }
1776
1777    // ── Claude review fixtures ─────────────────────────────────────────────────
1778
1779    #[serial(cooldown_state)]
1780    #[test]
1781    fn fixture_claude_review_approve() {
1782        let raw = include_str!("../../../tests/fixtures/review_claude_approve.jsonl");
1783        let resp = parse_review_via_agent("claude", raw).unwrap();
1784        assert_eq!(resp.decision, "approve");
1785        assert_eq!(resp.notes, "All checks pass");
1786        assert_eq!(resp.test_results.as_deref(), Some("pass"));
1787        assert!(resp.issues.is_empty());
1788    }
1789
1790    #[serial(cooldown_state)]
1791    #[test]
1792    fn fixture_claude_review_request_changes() {
1793        let raw = include_str!("../../../tests/fixtures/review_claude_request_changes.jsonl");
1794        let resp = parse_review_via_agent("claude", raw).unwrap();
1795        assert_eq!(resp.decision, "request_changes");
1796        assert_eq!(resp.notes, "Fix the null deref on line 42");
1797        assert_eq!(resp.test_results.as_deref(), Some("fail"));
1798        assert_eq!(resp.issues.len(), 1);
1799        assert_eq!(resp.issues[0].file, "src/main.rs");
1800        assert_eq!(resp.issues[0].line, Some(42));
1801        assert_eq!(resp.issues[0].severity, "error");
1802    }
1803
1804    #[serial(cooldown_state)]
1805    #[test]
1806    fn fixture_claude_review_rate_limit_returns_error() {
1807        // find_claude_result on an is_error=true result returns Some with is_error=true.
1808        // The integration test verifies this is captured, not that it's a ReviewResponse.
1809        let raw = include_str!("../../../tests/fixtures/review_claude_rate_limit.jsonl");
1810        let result = find_agent_result("claude", raw);
1811        assert!(
1812            result.is_some(),
1813            "should find result even for error envelope"
1814        );
1815        let result = result.unwrap();
1816        assert!(result.is_error, "rate limit should be flagged as error");
1817        assert!(result.result_text.contains("rate limit"));
1818    }
1819
1820    // ── OpenCode review fixtures ────────────────────────────────────────────────
1821
1822    #[serial(cooldown_state)]
1823    #[test]
1824    fn fixture_opencode_review_approve() {
1825        let raw = include_str!("../../../tests/fixtures/review_opencode_approve.jsonl");
1826        let resp = parse_review_via_agent("opencode", raw).unwrap();
1827        assert_eq!(resp.decision, "approve");
1828        assert_eq!(resp.notes, "All checks pass");
1829        assert!(resp.issues.is_empty());
1830    }
1831
1832    #[serial(cooldown_state)]
1833    #[test]
1834    fn fixture_opencode_review_request_changes() {
1835        let raw = include_str!("../../../tests/fixtures/review_opencode_request_changes.jsonl");
1836        let resp = parse_review_via_agent("opencode", raw).unwrap();
1837        assert_eq!(resp.decision, "request_changes");
1838        assert_eq!(resp.notes, "Fix the memory leak");
1839        assert_eq!(resp.test_results.as_deref(), Some("fail"));
1840        assert_eq!(resp.issues.len(), 1);
1841        assert_eq!(resp.issues[0].file, "src/lib.rs");
1842        assert_eq!(resp.issues[0].line, Some(100));
1843    }
1844
1845    #[serial(cooldown_state)]
1846    #[test]
1847    fn fixture_opencode_review_plain_text_approve() {
1848        // OpenCode with plain-text review (no JSON) — should infer approval via keywords.
1849        let raw = include_str!("../../../tests/fixtures/review_opencode_plain_text.jsonl");
1850        let resp = parse_review_via_agent("opencode", raw).unwrap();
1851        assert_eq!(resp.decision, "approve");
1852    }
1853
1854    // ── Codex review fixtures ────────────────────────────────────────────────────
1855
1856    #[serial(cooldown_state)]
1857    #[test]
1858    fn fixture_codex_review_approve() {
1859        let raw = include_str!("../../../tests/fixtures/review_codex_approve.jsonl");
1860        let resp = parse_review_via_agent("codex", raw).unwrap();
1861        assert_eq!(resp.decision, "approve");
1862        assert_eq!(resp.notes, "Clean implementation");
1863        assert!(resp.issues.is_empty());
1864    }
1865
1866    #[serial(cooldown_state)]
1867    #[test]
1868    fn fixture_codex_review_request_changes() {
1869        let raw = include_str!("../../../tests/fixtures/review_codex_request_changes.jsonl");
1870        let resp = parse_review_via_agent("codex", raw).unwrap();
1871        assert_eq!(resp.decision, "request_changes");
1872        assert_eq!(resp.notes, "Race condition on line 15");
1873        assert_eq!(resp.issues.len(), 1);
1874        assert_eq!(resp.issues[0].file, "src/server.rs");
1875        assert_eq!(resp.issues[0].line, Some(15));
1876    }
1877
1878    #[serial(cooldown_state)]
1879    #[test]
1880    fn fixture_codex_review_plain_text_approve() {
1881        // Codex with plain-text review — should infer approval via "LGTM" keyword.
1882        let raw = include_str!("../../../tests/fixtures/review_codex_plain_text.jsonl");
1883        let resp = parse_review_via_agent("codex", raw).unwrap();
1884        assert_eq!(resp.decision, "approve");
1885    }
1886
1887    // ── Kimi review fixtures ────────────────────────────────────────────────────
1888
1889    #[serial(cooldown_state)]
1890    #[test]
1891    fn fixture_kimi_review_approve() {
1892        let raw = include_str!("../../../tests/fixtures/review_kimi_approve.jsonl");
1893        let resp = parse_review_via_agent("kimi", raw).unwrap();
1894        assert_eq!(resp.decision, "approve");
1895        assert_eq!(resp.notes, "LGTM");
1896        assert_eq!(resp.test_results.as_deref(), Some("pass"));
1897        assert!(resp.issues.is_empty());
1898    }
1899
1900    // ── MiniMax review fixtures ────────────────────────────────────────────────
1901
1902    #[serial(cooldown_state)]
1903    #[test]
1904    fn fixture_minimax_review_request_changes() {
1905        let raw = include_str!("../../../tests/fixtures/review_minimax_request_changes.jsonl");
1906        let resp = parse_review_via_agent("minimax", raw).unwrap();
1907        assert_eq!(resp.decision, "request_changes");
1908        assert_eq!(resp.notes, "Fix the bug");
1909        assert_eq!(resp.test_results.as_deref(), Some("fail"));
1910        assert_eq!(resp.issues.len(), 1);
1911        assert_eq!(resp.issues[0].file, "src/foo.rs");
1912        assert_eq!(resp.issues[0].line, Some(42));
1913        assert_eq!(resp.issues[0].severity, "error");
1914    }
1915
1916    // ── Cross-agent token/metadata extraction ───────────────────────────────────
1917
1918    /// Verify that find_agent_result extracts token counts from each agent's format.
1919    #[serial(cooldown_state)]
1920    #[test]
1921    fn find_agent_result_extracts_tokens_claude() {
1922        let raw = include_str!("../../../tests/fixtures/review_claude_approve.jsonl");
1923        let result = find_agent_result("claude", raw).expect("should find result");
1924        assert_eq!(result.input_tokens, Some(200));
1925        assert_eq!(result.output_tokens, Some(30));
1926        assert!(result.cost_usd.is_none()); // review fixtures don't include cost
1927    }
1928
1929    #[serial(cooldown_state)]
1930    #[test]
1931    fn find_agent_result_extracts_tokens_opencode() {
1932        let raw = include_str!("../../../tests/fixtures/review_opencode_approve.jsonl");
1933        let result = find_agent_result("opencode", raw).expect("should find result");
1934        assert_eq!(result.input_tokens, Some(2900));
1935        assert_eq!(result.output_tokens, Some(100));
1936        assert_eq!(result.cost_usd, Some(0.002));
1937    }
1938
1939    /// Verify that find_agent_result returns None for empty/unparseable input.
1940    #[serial(cooldown_state)]
1941    #[test]
1942    fn find_agent_result_returns_none_for_empty() {
1943        assert!(find_agent_result("claude", "").is_none());
1944        assert!(find_agent_result("opencode", "").is_none());
1945        assert!(find_agent_result("codex", "").is_none());
1946        assert!(find_agent_result("kimi", "").is_none());
1947        assert!(find_agent_result("minimax", "").is_none());
1948    }
1949
1950    #[serial(cooldown_state)]
1951    #[test]
1952    fn find_agent_result_returns_none_for_plain_text() {
1953        assert!(find_agent_result("claude", "just some plain text").is_none());
1954        assert!(find_agent_result("codex", "just some plain text").is_none());
1955        // OpenCode is a special case — it can sometimes return a result for plain text.
1956        // This is acceptable because opencode's extract_ndjson_text falls back gracefully.
1957    }
1958
1959    // ── Error propagation via find_agent_result ─────────────────────────────────
1960
1961    /// Verify that find_agent_result surfaces rate-limit errors from Claude.
1962    #[serial(cooldown_state)]
1963    #[test]
1964    fn find_agent_result_propagates_claude_rate_limit() {
1965        let raw = include_str!("../../../tests/fixtures/review_claude_rate_limit.jsonl");
1966        let result = find_agent_result("claude", raw).expect("should find result");
1967        assert!(result.is_error, "should be flagged as error");
1968        assert!(result.result_text.contains("rate limit"));
1969    }
1970}