Skip to main content

blyte_agent/
run.rs

1//! The turn loop, and the gate the worker cannot call.
2//!
3//! # Where the gate sits, and why it is not a tool
4//!
5//! Invariant II: an LLM must never grade its own homework. A gate the model can invoke is a
6//! gate it can decline to invoke, or invoke selectively, or report the result of. So the gate
7//! is not in the tool surface at all -- the runtime runs it when the model stops calling tools,
8//! and the model learns the verdict the same way it learns anything else: as an observation it
9//! did not choose.
10//!
11//! This is the piece blyte asserted as doctrine for months while the code let a
12//! worker-authored test become the gate.
13//!
14//! # Why a failed gate resets the tree
15//!
16//! Invariant III. A failing attempt's edits must not accumulate across retries; the worker
17//! begins each attempt from a verified checkpoint, carrying the failure telemetry rather than a
18//! corrupted workspace. Measured independently at 3/3 against 2/3 and 25.3% fewer tokens per
19//! solve (EXP-059). Rollback is on by default and switchable, because it is not free -- one run
20//! reset a worker's committed feature five times (FINDINGS 13.2).
21
22use std::collections::{BTreeMap, HashMap, HashSet};
23use std::path::{Path, PathBuf};
24use std::time::Duration;
25
26use blyte_provider::{Message, Provider, ProviderError, Request, StreamTiming, Usage};
27
28use crate::claim_check;
29use crate::context::ContextStrategy;
30use crate::fs::Fs;
31use crate::gate_slots;
32use crate::quote_expand;
33use crate::research_check;
34use crate::shell::Shell;
35use crate::state::State;
36use crate::tools;
37
38/// How a run ended.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum Outcome {
41    /// The verification command exited 0. The only way to succeed.
42    Verified,
43    /// The task completed without a verification gate (e.g. conversation model task).
44    Finished,
45    /// Budget spent without the gate passing.
46    BudgetExhausted,
47    /// The model stopped calling tools and the gate kept failing.
48    GateFailed,
49    /// The check already fails at the base commit, so the task cannot pass until that is fixed.
50    Blocked(String),
51    /// The provider or environment broke. Distinct from failing work.
52    Error(String),
53}
54
55#[derive(Debug, Clone)]
56pub struct Budget {
57    pub max_turns: u32,
58    pub max_gate_attempts: u32,
59    /// Wall-clock limit, checked before each turn. The harness stops itself and reports, rather
60    /// than being killed from outside with its telemetry lost (FINDINGS 13.5).
61    pub max_duration: Option<Duration>,
62}
63
64impl Default for Budget {
65    fn default() -> Self {
66        Self {
67            max_turns: 60,
68            max_gate_attempts: 5,
69            max_duration: None,
70        }
71    }
72}
73
74/// One call of the main loop: what it cost, and how its prompt related to the previous call's.
75/// `appended` means the prompt was the previous one plus `new_chars` of new messages, the only
76/// case where a prefix cache can serve everything but the new part. Fresh input far above
77/// `new_chars / 4` on an appended call is a cache miss; on a rewritten one (a fold) it is expected.
78#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
79pub struct TurnUsage {
80    pub turn: u32,
81    pub input: u64,
82    pub cached: u64,
83    pub output: u64,
84    pub thinking: u64,
85    pub prompt_messages: usize,
86    pub appended: bool,
87    pub new_chars: usize,
88    /// The fold budget in force for this call, for strategies that fold.
89    #[serde(default)]
90    pub fold_budget: Option<usize>,
91    /// Wall time of this turn's model call, including any provider retries and their waits.
92    #[serde(default)]
93    pub model_ms: u64,
94    /// Wall time spent executing this turn's tool calls (0 for a turn with none).
95    #[serde(default)]
96    pub tools_ms: u64,
97    /// Milliseconds to the first data of the model call that ended this turn's calling
98    /// (`None`: the provider does not stream, or no data arrived).
99    #[serde(default)]
100    pub first_data_ms: Option<u64>,
101    /// Longest silence, in milliseconds, in that same call (0 when the provider does not stream).
102    #[serde(default)]
103    pub max_gap_ms: u64,
104    /// One entry per attempt of this turn's model call that failed and was retried, in order.
105    #[serde(default, skip_serializing_if = "Vec::is_empty")]
106    pub failed_attempts: Vec<FailedAttempt>,
107}
108
109/// A model call attempt that failed and was retried.
110#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
111pub struct FailedAttempt {
112    /// Wall time of the attempt, in milliseconds.
113    pub elapsed_ms: u64,
114    /// Whether the error was a timeout (`ProviderError::is_timeout`).
115    pub timed_out: bool,
116    /// As in [`blyte_provider::StreamTiming`]; `None` and 0 when the provider reported none.
117    pub first_data_ms: Option<u64>,
118    pub max_gap_ms: u64,
119}
120
121/// Characters a message contributes to a prompt, as the context strategies size them.
122fn message_chars(m: &Message) -> usize {
123    match m {
124        Message::User(t) | Message::Assistant(t) => t.len(),
125        Message::ToolCall { arguments, .. } => arguments.to_string().len(),
126        Message::ToolResult { content, .. } => content.len(),
127    }
128}
129
130#[derive(Debug, Clone, Default)]
131pub struct RunReport {
132    pub outcome_turns: u32,
133    pub usage: Usage,
134    /// Turns whose response contained neither text nor a tool call -- pure waste, tracked
135    /// because 47.6% of a previous harness's tokens went to turns that only waited (13.29).
136    pub empty_turns: u32,
137    /// Turns whose reply hit the output token limit and was cut off.
138    pub truncated_turns: u32,
139    /// Whether the run stopped because it kept repeating read/grep/glob calls without changing the workspace.
140    pub read_loop: bool,
141    /// Most repeated read/grep/glob calls seen between two workspace changes (the read-loop count).
142    pub peak_read_repeats: u32,
143    /// Whether the run stopped because consecutive turns kept folding the previous turn's results.
144    pub fold_thrash: bool,
145    /// Run stopped because a fix run made no change and kept calling tools after the last call.
146    pub stalled: bool,
147    /// Turns whose tool output exceeded half of the fold budget.
148    pub big_read_turns: u32,
149    pub tool_calls: u32,
150    pub gate_attempts: u32,
151    /// Transient provider failures (rate limits, overload) waited out during the run.
152    pub provider_retries: u32,
153    /// One entry per main-loop model call, in order.
154    pub turn_usage: Vec<TurnUsage>,
155    /// Wall time of each gate attempt, in order.
156    pub gate_ms: Vec<u64>,
157    /// The turn on which each gate attempt ran, in order (one entry per gate attempt).
158    pub gate_turns: Vec<u32>,
159    /// Time spent waiting for a gate slot on each attempt, in order (0 when acquired at once).
160    pub gate_wait_ms: Vec<u64>,
161    /// Gate output for each failed attempt, bounded to 4,000 characters (keeps the head and the tail).
162    pub gate_failures: Vec<String>,
163    /// Calls per tool name.
164    pub tool_counts: BTreeMap<String, u32>,
165    /// Whether the run stopped because spending reached `--max-cost`.
166    pub cost_capped: bool,
167    /// The model's last non-empty text response (trimmed).
168    pub final_message: Option<String>,
169    /// Problems with `report.md`'s quotes (`None` when the check did not run, `Some(vec![])` when it passed).
170    pub quote_problems: Option<Vec<String>>,
171    /// Model check of `report.md`'s claims against their cited lines (`None` when the check did not run).
172    pub claim_check: Option<claim_check::ClaimCheck>,
173    /// Reason the claim check did not run or stopped early (for example, out of time).
174    pub claim_check_skipped: Option<String>,
175    /// Elapsed seconds for the base check when it ran to completion.
176    pub base_check_seconds: Option<f64>,
177    /// Outcome of the base check when it ran to completion (`Some(true)` if passed, `Some(false)` if failed).
178    pub base_check_passed: Option<bool>,
179}
180
181/// What happened on one turn, emitted as it happens.
182///
183/// A harness whose selling point is observability printed nothing until the run finished, so a
184/// working run and one stuck on `find /` looked identical for three and a half minutes. Progress
185/// is reported as it occurs, not summarised at the end.
186#[derive(Debug, Clone)]
187pub enum Event<'e> {
188    Turn {
189        n: u32,
190        text: &'e str,
191        usage: Usage,
192    },
193    /// Emitted immediately before a tool call executes, with the same abbreviated `input` as `Tool`.
194    ToolStart {
195        name: &'e str,
196        input: String,
197    },
198    /// `input` is the call's arguments, abbreviated. Logging only the RESULT made a run
199    /// undiagnosable: twenty bash calls that changed nothing, with no record of what was run.
200    Tool {
201        name: &'e str,
202        input: String,
203        summary: String,
204        is_error: bool,
205    },
206    /// Emitted before sleeping to retry a transient model call error.
207    Retry {
208        attempt: u32,
209        max: u32,
210        wait_ms: u64,
211        reason: String,
212    },
213    /// A gate attempt is starting (the check runs next). Emitted so a watcher can tell a run
214    /// that is waiting on its gate from one that is thinking (`blyte dashboard`, 2026-09-30).
215    GateStart {
216        attempt: u32,
217    },
218    /// A gate waited for a machine-wide slot before running.
219    GateSlotWait {
220        ms: u64,
221    },
222    Gate {
223        attempt: u32,
224        passed: bool,
225        output: &'e str,
226    },
227    RolledBack {
228        to: &'e str,
229    },
230}
231
232/// Retries allowed for one model call before a transient failure ends the run.
233pub const MAX_PROVIDER_RETRIES: u32 = 6;
234
235pub const CONVERSATION_FIXED: &str = "\
236Change nothing outside the repository yourself (blyte's own files under `.wt/` and its records are fine).\n\n\
237## Working efficiently\n\
238Independent reads, searches and commands can be issued as several tool calls in one \
239turn: they run in order and you see every result together. Batch them whenever one \
240does not depend on another's result; every turn you save is a full model call.\n";
241
242/// Turns a fix run may spend without changing a file or running the gate before getting a nudge.
243pub const NO_PROGRESS_TURNS: u32 = 20;
244/// Minimum turns before the time-based no-progress nudge may fire.
245pub const NO_PROGRESS_MIN_TURNS: u32 = 8;
246/// Fraction of `max_duration` after which the no-progress nudge may fire (past `NO_PROGRESS_MIN_TURNS`).
247pub const NO_PROGRESS_TIME_FRACTION: f64 = 0.25;
248/// Turns after the no-progress nudge before the last call is sent.
249pub const LAST_CALL_TURNS: u32 = 10;
250/// Fraction of `max_duration` after which the last call may fire (once nudged).
251pub const LAST_CALL_TIME_FRACTION: f64 = 0.5;
252
253/// Turn on which a research run reminds the model to start `report.md` if it is still missing or empty.
254pub const RESEARCH_FIRST_REPORT_TURN: u32 = 8;
255/// Repeated read/grep/glob calls without a workspace change in a research run before warning.
256pub const READ_LOOP_WARN: u32 = 20;
257/// Repeated read/grep/glob calls without a workspace change allowed before ending the run.
258const READ_LOOP_LIMIT: u32 = 30;
259/// Extra turns a research run gets after reaching `READ_LOOP_LIMIT` to write `report.md` and stop.
260pub const READ_LOOP_GRACE_TURNS: u32 = 3;
261
262/// Most time a research run's main loop leaves for the claim check.
263pub const CLAIM_CHECK_RESERVE_MAX: Duration = Duration::from_secs(180);
264
265/// Time the main loop of a research run leaves before its deadline for the claim check:
266/// a tenth of the time budget, at most `CLAIM_CHECK_RESERVE_MAX`.
267pub fn claim_check_reserve(max_duration: Duration) -> Duration {
268    (max_duration / 10).min(CLAIM_CHECK_RESERVE_MAX)
269}
270
271fn truncated(reason: Option<&str>) -> bool {
272    matches!(
273        reason,
274        Some("MAX_TOKENS" | "CONTINUATION" | "max_tokens" | "length" | "incomplete")
275    )
276}
277
278fn parse_resets_in_seconds(body: &str) -> Option<u64> {
279    let key = "\"resets_in_seconds\"";
280    let pos = body.find(key)?;
281    let rest = body[pos + key.len()..].trim_start();
282    let after_colon = rest.strip_prefix(':')?.trim_start();
283    let digits: String = after_colon
284        .chars()
285        .take_while(|c| c.is_ascii_digit())
286        .collect();
287    if digits.is_empty() {
288        return None;
289    }
290    digits.parse().ok()
291}
292
293/// Identifies provider errors caused by an exhausted usage quota (as opposed to a transient
294/// burst rate limit). Returns `Some(message)` describing the exhaustion and reset duration if known.
295pub fn quota_exhausted(e: &ProviderError) -> Option<String> {
296    let ProviderError::Api { status: 429, body } = e else {
297        return None;
298    };
299    let resets_in_seconds = parse_resets_in_seconds(body);
300    let is_quota = body.contains("usage_limit_reached")
301        || body.contains("insufficient_quota")
302        || body.contains("PerDay")
303        || resets_in_seconds.is_some_and(|s| s > 300);
304
305    if !is_quota {
306        return None;
307    }
308
309    let mut msg = "usage quota exhausted; not retrying".to_string();
310    if let Some(secs) = resets_in_seconds {
311        let human = if secs >= 86400 {
312            format!("{}d {}h", secs / 86400, (secs % 86400) / 3600)
313        } else if secs >= 3600 {
314            format!("{}h {}m", secs / 3600, (secs % 3600) / 60)
315        } else {
316            format!("{}m", secs / 60)
317        };
318        msg.push_str(&format!(" (resets in {human})"));
319    }
320    Some(msg)
321}
322
323/// Transient provider failures worth waiting out: rate limits, overload, server errors and
324/// dropped connections. Anything else (a malformed request, a bad key) fails the run at once.
325pub fn is_transient(e: &ProviderError) -> bool {
326    if quota_exhausted(e).is_some() {
327        return false;
328    }
329    match e {
330        ProviderError::Api { status, .. } => matches!(status, 429 | 500 | 502 | 503 | 504),
331        ProviderError::Transport(_) | ProviderError::NoAnswer { .. } => true,
332        _ => false,
333    }
334}
335
336fn max_retries_for(e: &ProviderError) -> u32 {
337    match e {
338        ProviderError::NoAnswer { .. } => 1,
339        _ => MAX_PROVIDER_RETRIES,
340    }
341}
342
343/// Wait before retry `attempt` (1-based): 2, 4, 8, 16, 32, then 60 seconds.
344pub fn retry_delay(attempt: u32) -> Duration {
345    if let Ok(ms) = std::env::var("BLYTE_RETRY_DELAY_MS") {
346        if let Ok(ms) = ms.trim().parse::<u64>() {
347            return Duration::from_millis(ms);
348        }
349    }
350    let exp = attempt.saturating_sub(1).min(5);
351    Duration::from_secs((2u64 << exp).min(60))
352}
353
354/// How long the server asked us to wait, if it said: Gemini puts `"retryDelay": "37s"` in a
355/// 429's body. Capped at 120 seconds.
356pub fn server_retry_hint(e: &ProviderError) -> Option<Duration> {
357    let ProviderError::Api { body, .. } = e else {
358        return None;
359    };
360    let key = "\"retryDelay\"";
361    let rest = &body[body.find(key)? + key.len()..];
362    let value = &rest[rest.find('"')? + 1..];
363    let secs: f64 = value[..value.find('s')?].trim().parse().ok()?;
364    Some(Duration::from_secs_f64(secs.max(0.0)).min(Duration::from_secs(120)))
365}
366
367/// Wait before retry `attempt` (1-based): the backoff, or the server's hint when it is longer.
368pub fn retry_wait(e: &ProviderError, attempt: u32) -> Duration {
369    let backoff = retry_delay(attempt);
370    server_retry_hint(e).map_or(backoff, |hint| hint.max(backoff))
371}
372
373/// State of a base check running beside the model's turns.
374#[derive(Debug, Clone, PartialEq, Eq)]
375pub enum BaseCheckState {
376    Pending,
377    Passed,
378    Failed { steps: Vec<String>, tail: String },
379}
380
381/// Handle to a background base check polled by [`Runner`].
382pub trait BaseCheckHandle: Sync {
383    fn poll(&self) -> BaseCheckState;
384    fn wait(&self) -> BaseCheckState;
385    fn stop(&self) {}
386    fn elapsed_seconds(&self) -> Option<f64> {
387        None
388    }
389}
390
391/// How [`Runner`] checks the untouched base tree against the verification gate.
392#[derive(Default)]
393pub enum BaseCheck<'a> {
394    #[default]
395    None,
396    BeforeFirstTurn,
397    Polled(&'a dyn BaseCheckHandle),
398}
399
400/// Last 20 lines of gate output, formatted for base-check failure reports.
401pub fn base_check_tail(output: &str) -> String {
402    let lines: Vec<&str> = output.lines().collect();
403    if lines.len() > 20 {
404        lines[lines.len() - 20..].join("\n")
405    } else {
406        lines.join("\n")
407    }
408}
409
410/// Convert a [`GateRunResult`] into a [`BaseCheckState`].
411pub fn base_check_state_from_gate(result: &GateRunResult) -> BaseCheckState {
412    if result.passed {
413        BaseCheckState::Passed
414    } else {
415        BaseCheckState::Failed {
416            steps: result.failures.iter().map(|f| f.step.clone()).collect(),
417            tail: base_check_tail(&result.output),
418        }
419    }
420}
421
422fn base_check_blocked_message(failing_steps: &[String], tail: &str) -> String {
423    let steps = failing_steps.join("; ");
424    format!(
425        "the check fails before any change ({steps}): {tail}. Fix the environment or the base commit, or pass --no-base-check if this task is meant to fix that check."
426    )
427}
428
429pub struct Runner<'a> {
430    pub provider: &'a dyn Provider,
431    pub shell: &'a dyn Shell,
432    pub fs: &'a dyn Fs,
433    pub context: &'a dyn ContextStrategy,
434    pub root: PathBuf,
435    pub budget: Budget,
436    /// Reset the tree to the checkpoint when the gate fails. Invariant III; default on.
437    pub rollback: bool,
438    /// Called as the run proceeds. Default is silent.
439    pub on_event: Option<&'a dyn Fn(Event<'_>)>,
440    /// Research run: periodically remind the model to keep report.md updated.
441    pub research: bool,
442    /// Research runs: check report.md's claims with the run's model (`claim_check`).
443    pub claim_check: bool,
444    /// How to check the verification gate against the untouched base tree.
445    pub base_check: BaseCheck<'a>,
446}
447
448const CLAIM_PHRASES: &[&str] = &[
449    "not caused by",
450    "pre-existing",
451    "preexisting",
452    "already fail",
453    "unrelated to",
454    "fails on main",
455    "fails on the base",
456    "was failing before",
457];
458
459fn sh_quote(s: &str) -> String {
460    format!("'{}'", s.replace('\'', r"'\''"))
461}
462
463impl<'a> Runner<'a> {
464    fn emit(&self, e: Event<'_>) {
465        if let Some(f) = self.on_event {
466            f(e)
467        }
468    }
469}
470
471impl<'a> Runner<'a> {
472    /// The immutable part of the prompt: who the worker is, what it may touch, where it runs.
473    ///
474    /// Held constant for the whole run so it caches.
475    fn system_prompt(&self, state: &State, goal: &str) -> Result<String, String> {
476        let bins = tools::available_binaries(self.shell, &self.root)?.join(", ");
477        let where_ = self.shell.describe();
478
479        if let Some(text) = &state.brief.instructions {
480            return Ok(format!(
481                "{text}## Your user's first request\n{goal}\n\n\
482                 ## Environment\n{where_}\nAvailable: {bins}\n\n\
483                 {CONVERSATION_FIXED}",
484            ));
485        }
486
487        let rules = crate::rules::prompt_section(&self.root);
488
489        let steps = gate_steps(&state.brief.verification_cmd);
490        // Ungated runs have no check command, so the model must verify the work itself before stopping.
491        let completion = if steps.is_empty() {
492            "No command checks your work. When you stop, the result is judged by tests you \
493             cannot see, so verify it yourself first: run the project's existing test suite and \
494             the tests that cover your change, and check the edge cases the task describes. \
495             If you searched for problems (with grep or other commands), run those same searches \
496             again before you stop and confirm they find nothing left to fix. Stop \
497             only when you are confident the task is complete."
498                .to_string()
499        } else {
500            let verify = steps.join(" && ");
501            format!(
502                "Your work is accepted when `{verify}` exits 0. That command is run for you when \
503                 you stop calling tools, and you do not decide the verdict. A failure costs a full \
504                 rerun after your fix, so before you stop, run its quick parts yourself \
505                 (formatting, lint) together with the tests that cover your change; leave the slow \
506                 full run to it. Do not claim to be finished; simply stop when you believe the \
507                 command will pass, and you will be told."
508            )
509        };
510        Ok(format!(
511            "You are a software engineer working in a repository.\n\n\
512             ## Goal\n{goal}\n\n\
513             ## How completion is decided\n\
514             {completion}\n\n\
515             ## Environment\n{where_}\nAvailable: {bins}\n\n\
516             Change nothing outside the repository: no caches, other repositories, \
517             home-directory files or system settings. If something outside it blocks you \
518             (disk space, network, a missing tool), say so and stop.\n\n\
519             {rules}\
520             ## Working efficiently\n\
521             Independent reads, searches and commands can be issued as several tool calls in one \
522             turn: they run in order and you see every result together. Batch them whenever one \
523             does not depend on another's result; every turn you save is a full model call.\n",
524            goal = goal,
525            completion = completion,
526            where_ = where_,
527            bins = bins,
528            rules = rules,
529        ))
530    }
531
532    /// Run the verification command. Runtime-only: nothing in the tool surface reaches this.
533    ///
534    /// A gate of several lines is several steps. On the first attempt, every step runs and all
535    /// failures come back in one message. On retries, previously failing steps run first, and if
536    /// any of them still fails, the attempt stops without re-running the passing steps.
537    fn run_gate(
538        &self,
539        state: &State,
540        last_failed: &[String],
541        deadline: &mut Option<std::time::Instant>,
542        now: &(dyn Fn() -> std::time::Instant + Sync),
543    ) -> (bool, String, u64, Vec<String>) {
544        let result = run_gate_steps(
545            self.shell,
546            &state.brief.verification_cmd,
547            &self.root,
548            last_failed,
549            deadline,
550            |ms| self.emit(Event::GateSlotWait { ms }),
551            now,
552        );
553        let failed = result.failures.into_iter().map(|f| f.step).collect();
554        (result.passed, result.output, result.wait_ms, failed)
555    }
556
557    fn run_step_in(
558        &self,
559        cmd: &str,
560        dir: &Path,
561        deadline: Option<std::time::Instant>,
562        now: &(dyn Fn() -> std::time::Instant + Sync),
563    ) -> (bool, String) {
564        run_gate_step(self.shell, cmd, dir, deadline, now)
565    }
566
567    fn fingerprint(&self) -> Option<String> {
568        let head = self
569            .shell
570            .exec("git rev-parse HEAD", &self.root, Duration::from_secs(30))
571            .ok()?;
572        if head.exit_code != 0 {
573            return None;
574        }
575        let status = self
576            .shell
577            .exec(
578                "git status --porcelain",
579                &self.root,
580                Duration::from_secs(30),
581            )
582            .ok()?;
583        if status.exit_code != 0 {
584            return None;
585        }
586        Some(format!("{}\n{}", head.stdout, status.stdout))
587    }
588
589    fn check_blocked_at_base(&self, base_commit: &str, failing_steps: &[String]) -> bool {
590        if failing_steps.is_empty() {
591            return false;
592        }
593
594        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
595        let unique = format!(
596            "blyte-base-{}-{}-{}",
597            std::process::id(),
598            std::time::SystemTime::now()
599                .duration_since(std::time::UNIX_EPOCH)
600                .map(|d| d.as_nanos())
601                .unwrap_or(0),
602            COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
603        );
604        let wt_path = std::env::temp_dir().join(unique);
605
606        let add_cmd = format!(
607            "git worktree add --detach {} {}",
608            sh_quote(&wt_path.to_string_lossy()),
609            sh_quote(base_commit)
610        );
611        let add_out = match self
612            .shell
613            .exec(&add_cmd, &self.root, Duration::from_secs(60))
614        {
615            Ok(o) if o.exit_code == 0 => o,
616            _ => return false,
617        };
618        let _ = add_out;
619
620        struct Guard<'a> {
621            shell: &'a dyn Shell,
622            root: &'a Path,
623            path: PathBuf,
624        }
625        impl<'a> Drop for Guard<'a> {
626            fn drop(&mut self) {
627                let cmd = format!(
628                    "git worktree remove --force {}",
629                    sh_quote(&self.path.to_string_lossy())
630                );
631                let _ = self.shell.exec(&cmd, self.root, Duration::from_secs(60));
632                let _ = std::fs::remove_dir_all(&self.path);
633            }
634        }
635
636        let _guard = Guard {
637            shell: self.shell,
638            root: &self.root,
639            path: wt_path.clone(),
640        };
641
642        let mut all_failed = true;
643        for step in failing_steps {
644            let (passed, _) = self.run_step_in(step, &wt_path, None, &std::time::Instant::now);
645            if passed {
646                all_failed = false;
647            }
648        }
649        all_failed
650    }
651
652    fn checkpoint(&self) -> Option<String> {
653        let out = self
654            .shell
655            .exec("git rev-parse HEAD", &self.root, Duration::from_secs(30))
656            .ok()?;
657        (out.exit_code == 0).then(|| out.stdout.trim().to_string())
658    }
659
660    /// Problems with report.md's quotes, line citations and unseen names (see `research_check`).
661    fn check_report_quotes(&self, seen_names: &HashSet<String>) -> Vec<String> {
662        let Ok(raw) = self.fs.read(&self.root.join("report.md")) else {
663            return Vec::new();
664        };
665        // A directive may name only what the `read` tool may read: the workspace and the read
666        // roots. Anything else would paste a file the run is not allowed to see into the report.
667        let expand_read = |p: &Path| {
668            let allowed = tools::resolve_for_read(self.fs, &self.root, &p.to_string_lossy())?;
669            self.fs.read(&allowed)
670        };
671        let (report, mut problems) = quote_expand::expand(&raw, &expand_read);
672        if report != raw {
673            if let Err(e) = self.fs.write(&self.root.join("report.md"), &report) {
674                problems.push(format!(
675                    "report.md: could not write the expanded quotes: {e}"
676                ));
677            }
678        }
679        let read_roots = tools::read_roots();
680        let mut listing = Vec::new();
681        // A read root can be any repository; `core.fsmonitor` in its config would run a command
682        // on `ls-files` (GitSpawn, 2026-10).
683        for dir in std::iter::once(&self.root).chain(read_roots.iter()) {
684            if let Ok(o) = self.shell.exec(
685                "git -c core.quotePath=off -c core.fsmonitor=false ls-files -co --exclude-standard",
686                dir,
687                Duration::from_secs(60),
688            ) {
689                if o.exit_code == 0 {
690                    listing.extend(o.stdout.lines().map(|l| dir.join(l)));
691                }
692            }
693        }
694        let read = |p: &Path| self.fs.read(p);
695        let sources = research_check::Sources {
696            workspace: &self.root,
697            read_roots: &read_roots,
698            listing: &listing,
699            read: &read,
700        };
701        problems.extend(research_check::check(&report, &sources));
702        problems.extend(research_check::unseen_names(&report, seen_names));
703        problems.extend(research_check::unseen_paths(&report, &sources, seen_names));
704        problems
705    }
706
707    fn run_claim_check(
708        &self,
709        deadline: Option<std::time::Instant>,
710        now: &(dyn Fn() -> std::time::Instant + Sync),
711    ) -> Option<claim_check::ClaimCheck> {
712        if !self.claim_check {
713            return None;
714        }
715        let report = self.fs.read(&self.root.join("report.md")).ok()?;
716        if report.is_empty() {
717            return None;
718        }
719        let read_roots = tools::read_roots();
720        let mut listing = Vec::new();
721        for dir in std::iter::once(&self.root).chain(read_roots.iter()) {
722            if let Ok(o) = self.shell.exec(
723                "git -c core.quotePath=off -c core.fsmonitor=false ls-files -co --exclude-standard",
724                dir,
725                Duration::from_secs(60),
726            ) {
727                if o.exit_code == 0 {
728                    listing.extend(o.stdout.lines().map(|l| dir.join(l)));
729                }
730            }
731        }
732        let read = |p: &Path| self.fs.read(p);
733        let claims = research_check::claims(
734            &report,
735            &research_check::Sources {
736                workspace: &self.root,
737                read_roots: &read_roots,
738                listing: &listing,
739                read: &read,
740            },
741        );
742        Some(claim_check::check_claims_with_clock(
743            self.provider,
744            &claims,
745            deadline,
746            now,
747        ))
748    }
749
750    fn reset_to(&self, commit: &str) -> Result<(), String> {
751        let out = self
752            .shell
753            .exec(
754                &format!("git reset --hard {commit} && git clean -fd"),
755                &self.root,
756                Duration::from_secs(120),
757            )
758            .map_err(|e| format!("could not roll back to {commit}: {e}"))?;
759        if out.exit_code != 0 {
760            let detail = out.merged();
761            let detail = detail.trim();
762            return if detail.is_empty() {
763                Err(format!(
764                    "could not roll back to {commit}: exit {}",
765                    out.exit_code
766                ))
767            } else {
768                Err(format!(
769                    "could not roll back to {commit}: exit {}: {detail}",
770                    out.exit_code
771                ))
772            };
773        }
774        Ok(())
775    }
776
777    fn elapsed_fraction(
778        &self,
779        deadline: Option<std::time::Instant>,
780        now: &(dyn Fn() -> std::time::Instant + Sync),
781    ) -> Option<f64> {
782        let max_duration = self.budget.max_duration?;
783        let deadline = deadline?;
784        let remaining = deadline.saturating_duration_since(now());
785        Some(max_duration.saturating_sub(remaining).as_secs_f64() / max_duration.as_secs_f64())
786    }
787
788    pub fn run(&self, state: &mut State) -> (Outcome, RunReport) {
789        self.run_with_clock(state, &std::time::Instant::now)
790    }
791
792    /// Like [`run`](Self::run), reading the current time from `now`.
793    pub fn run_with_clock(
794        &self,
795        state: &mut State,
796        now: &(dyn Fn() -> std::time::Instant + Sync),
797    ) -> (Outcome, RunReport) {
798        self.run_until(state, now, &std::thread::sleep)
799    }
800
801    /// Like [`run_with_clock`](Self::run_with_clock), using `sleep` for retry waits.
802    pub fn run_with_clock_and_sleep(
803        &self,
804        state: &mut State,
805        now: &(dyn Fn() -> std::time::Instant + Sync),
806        sleep: &(dyn Fn(std::time::Duration) + Sync),
807    ) -> (Outcome, RunReport) {
808        self.run_until(state, now, sleep)
809    }
810
811    fn run_until(
812        &self,
813        state: &mut State,
814        now: &(dyn Fn() -> std::time::Instant + Sync),
815        sleep: &(dyn Fn(std::time::Duration) + Sync),
816    ) -> (Outcome, RunReport) {
817        let is_empty_conversation = state
818            .runtime
819            .conversation
820            .as_ref()
821            .map(|c| c.is_empty())
822            .unwrap_or(false);
823        if is_empty_conversation {
824            state.runtime.conversation_goal = Some(state.brief.goal.clone());
825        }
826
827        let mut history = match &state.runtime.conversation {
828            None => vec![Message::User(format!("Begin. {}", state.brief.goal))],
829            Some(prev) if prev.is_empty() => {
830                vec![Message::User(format!("Begin. {}", state.brief.goal))]
831            }
832            Some(prev) => {
833                let mut h = prev.clone();
834                h.push(Message::User(state.brief.goal.clone()));
835                h
836            }
837        };
838
839        let goal = match &state.runtime.conversation_goal {
840            Some(g) => g.as_str(),
841            None => state.brief.goal.as_str(),
842        };
843        let system = match self.system_prompt(state, goal) {
844            Ok(s) => s,
845            Err(err) => {
846                if let BaseCheck::Polled(handle) = self.base_check {
847                    handle.stop();
848                }
849                if state.runtime.conversation.is_some() {
850                    state.runtime.conversation = Some(history);
851                }
852                return (Outcome::Error(err), RunReport::default());
853            }
854        };
855
856        let mut seen_names = HashSet::new();
857        if self.research {
858            seen_names.extend(research_check::identifiers(goal).map(str::to_owned));
859            seen_names.extend(research_check::identifiers(&state.brief.goal).map(str::to_owned));
860            // Tool results only: restored user messages include gate feedback that names the
861            // very identifiers the check flagged.
862            for msg in &history {
863                if let Message::ToolResult { content, .. } = msg {
864                    seen_names.extend(research_check::identifiers(content).map(str::to_owned));
865                }
866            }
867        }
868
869        let baseline = self.checkpoint();
870        let start_fp = self.fingerprint();
871        let deadline = self.budget.max_duration.map(|d| now() + d);
872
873        let loop_deadline = match (
874            self.research && self.claim_check,
875            deadline,
876            self.budget.max_duration,
877        ) {
878            (true, Some(d), Some(max_d)) => d.checked_sub(claim_check_reserve(max_d)).or(deadline),
879            _ => deadline,
880        };
881
882        let (outcome, mut report) = self.run_loop(
883            state,
884            &mut history,
885            &mut seen_names,
886            &system,
887            baseline,
888            start_fp,
889            loop_deadline,
890            deadline,
891            now,
892            sleep,
893        );
894        if let BaseCheck::Polled(handle) = self.base_check {
895            if outcome != Outcome::Verified && report.base_check_passed.is_none() {
896                match handle.poll() {
897                    BaseCheckState::Pending => {
898                        handle.stop();
899                    }
900                    BaseCheckState::Passed => {
901                        report.base_check_passed = Some(true);
902                        report.base_check_seconds = handle.elapsed_seconds();
903                    }
904                    BaseCheckState::Failed { .. } => {
905                        report.base_check_passed = Some(false);
906                        report.base_check_seconds = handle.elapsed_seconds();
907                    }
908                }
909            }
910        }
911        if self.research
912            && outcome != Outcome::Verified
913            && self
914                .fs
915                .read(&self.root.join("report.md"))
916                .is_ok_and(|s| !s.is_empty())
917        {
918            if report.quote_problems.is_none() {
919                let mut problems = self.check_report_quotes(&seen_names);
920                problems.truncate(research_check::MAX_PROBLEMS);
921                report.quote_problems = Some(problems);
922            }
923            if report.claim_check.is_none() && report.claim_check_skipped.is_none() {
924                if let Some(cc) = self.run_claim_check(deadline, now) {
925                    report.usage.input += cc.usage.input;
926                    report.usage.cached += cc.usage.cached;
927                    report.usage.output += cc.usage.output;
928                    report.usage.thinking += cc.usage.thinking;
929                    report.claim_check_skipped = cc.skipped.clone();
930                    if cc.calls > 0 || cc.skipped.is_none() {
931                        report.claim_check = Some(cc);
932                    }
933                }
934            }
935        }
936
937        if state.runtime.conversation.is_some() {
938            state.runtime.conversation = Some(history);
939        }
940
941        (outcome, report)
942    }
943
944    #[allow(clippy::too_many_arguments)]
945    fn run_loop(
946        &self,
947        state: &mut State,
948        history: &mut Vec<Message>,
949        seen_names: &mut HashSet<String>,
950        system: &str,
951        baseline: Option<String>,
952        start_fp: Option<String>,
953        deadline: Option<std::time::Instant>,
954        claim_deadline: Option<std::time::Instant>,
955        now: &(dyn Fn() -> std::time::Instant + Sync),
956        sleep: &(dyn Fn(std::time::Duration) + Sync),
957    ) -> (Outcome, RunReport) {
958        let mut deadline = deadline;
959        let mut report = RunReport::default();
960        let specs = tools::specs();
961        let mut last_sent: Option<Vec<Message>> = None;
962        let mut last_failed: Vec<String> = Vec::new();
963        let mut last_fingerprint: Option<String> = None;
964        let mut call_counts: HashMap<String, u32> = HashMap::new();
965        let mut repeats: u32 = 0;
966        let mut read_warn_sent = false;
967        let mut read_loop_turn: Option<u32> = None;
968        let mut change_fp = start_fp.clone();
969        let mut progressed = false;
970        let mut nudge_turn: Option<u32> = None;
971        let mut last_call_sent = false;
972        let mut last_turn_called_tools = false;
973        let mut last_report = if self.research {
974            self.fs.read(&self.root.join("report.md")).ok()
975        } else {
976            None
977        };
978        let mut claim_round_done = false;
979        let mut prev_turn_start: Option<usize> = None;
980        let mut thrash: u32 = 0;
981        let mut last_big_read_warn: Option<u32> = None;
982        let mut wrap_up_sent = false;
983        let mut wrap_up_tools_closed = false;
984        let mut wrap_up_report: Option<String> = None;
985
986        if matches!(self.base_check, BaseCheck::BeforeFirstTurn)
987            && !gate_steps(&state.brief.verification_cmd).is_empty()
988        {
989            let bc_start = now();
990            let (passed, output, _wait_ms, failing_steps) =
991                self.run_gate(state, &[], &mut deadline, now);
992            report.base_check_seconds =
993                Some(now().saturating_duration_since(bc_start).as_secs_f64());
994            report.base_check_passed = Some(passed);
995            if !passed {
996                let tail = base_check_tail(&output);
997                let msg = base_check_blocked_message(&failing_steps, &tail);
998                report.final_message = Some(msg.clone());
999                return (Outcome::Blocked(msg), report);
1000            }
1001        }
1002
1003        for turn in 1..=self.budget.max_turns {
1004            if read_loop_turn.is_some_and(|t| turn > t + READ_LOOP_GRACE_TURNS) {
1005                return (Outcome::BudgetExhausted, report);
1006            }
1007            if deadline.is_some_and(|d| now() >= d) {
1008                return (Outcome::BudgetExhausted, report);
1009            }
1010            if let Some(cap) = state.brief.max_cost_usd {
1011                if let Some(price) = blyte_provider::pricing(&self.provider.model_id()) {
1012                    if price.cost(&report.usage) >= cap {
1013                        report.cost_capped = true;
1014                        return (Outcome::BudgetExhausted, report);
1015                    }
1016                }
1017            }
1018            if let BaseCheck::Polled(handle) = self.base_check {
1019                if report.base_check_passed.is_none() {
1020                    match handle.poll() {
1021                        BaseCheckState::Pending => {}
1022                        BaseCheckState::Passed => {
1023                            report.base_check_passed = Some(true);
1024                            report.base_check_seconds = handle.elapsed_seconds();
1025                        }
1026                        BaseCheckState::Failed { steps, tail } => {
1027                            report.base_check_passed = Some(false);
1028                            report.base_check_seconds = handle.elapsed_seconds();
1029                            let msg = base_check_blocked_message(&steps, &tail);
1030                            report.final_message = Some(msg.clone());
1031                            return (Outcome::Blocked(msg), report);
1032                        }
1033                    }
1034                }
1035            }
1036            report.outcome_turns = turn;
1037            let turn_start = history.len();
1038
1039            if !wrap_up_sent {
1040                if self.budget.max_turns >= 20 && turn == self.budget.max_turns - 9 {
1041                    wrap_up_sent = true;
1042                    history.push(Message::User(format!(
1043                        "You have 10 turns left of {}. Wrap up now: make sure your work is saved before you run out: committed, or written to the file the task asks for. Then stop calling tools.",
1044                        self.budget.max_turns
1045                    )));
1046                } else if let (Some(max_duration), Some(deadline)) =
1047                    (self.budget.max_duration, deadline)
1048                {
1049                    let time_left = deadline.saturating_duration_since(now());
1050                    if time_left.as_secs_f64() < max_duration.as_secs_f64() * 0.1 {
1051                        wrap_up_sent = true;
1052                        let m = ((time_left.as_secs_f64() / 60.0).ceil() as u64).max(1);
1053                        let total = ((max_duration.as_secs_f64() / 60.0).ceil() as u64).max(1);
1054                        history.push(Message::User(format!(
1055                            "You have about {m} minutes left of {total}. Wrap up now: make sure your work is saved before you run out: committed, or written to the file the task asks for. Then stop calling tools."
1056                        )));
1057                    }
1058                }
1059                if wrap_up_sent && self.research {
1060                    wrap_up_tools_closed = true;
1061                    wrap_up_report = self.fs.read(&self.root.join("report.md")).ok();
1062                }
1063            }
1064
1065            if self.research && turn == RESEARCH_FIRST_REPORT_TURN {
1066                let has_report = self
1067                    .fs
1068                    .read(&self.root.join("report.md"))
1069                    .is_ok_and(|s| !s.trim().is_empty());
1070                if !has_report {
1071                    history.push(Message::User(
1072                        "Start report.md now with what you have found so far, even if unfinished, then carry on.".to_string(),
1073                    ));
1074                }
1075            }
1076
1077            if self.research && turn % 30 == 0 {
1078                let current_report = self.fs.read(&self.root.join("report.md")).ok();
1079                if current_report == last_report {
1080                    history.push(Message::User(
1081                        "Update report.md now with what you have found so far, even if unfinished, then carry on.".to_string(),
1082                    ));
1083                }
1084                last_report = current_report;
1085            }
1086
1087            if !self.research
1088                && state.brief.instructions.is_none()
1089                && state.runtime.conversation.is_none()
1090                && !progressed
1091            {
1092                let elapsed = self.elapsed_fraction(deadline, now);
1093                if nudge_turn.is_none()
1094                    && (turn > NO_PROGRESS_TURNS
1095                        || (turn > NO_PROGRESS_MIN_TURNS
1096                            && elapsed.is_some_and(|f| f >= NO_PROGRESS_TIME_FRACTION)))
1097                {
1098                    if self.fingerprint() != start_fp {
1099                        progressed = true;
1100                    } else {
1101                        let n = turn - 1;
1102                        history.push(Message::User(format!(
1103                            "[blyte] You have spent {n} turns without changing any file or running the gate. Stop exploring and decide now: make the change the task asks for, or, if the task needs no code change or the problem cannot be reproduced, stop calling tools and explain why in your reply."
1104                        )));
1105                        nudge_turn = Some(turn);
1106                    }
1107                } else if let Some(t) = nudge_turn {
1108                    if !last_call_sent
1109                        && (turn >= t + LAST_CALL_TURNS
1110                            || elapsed.is_some_and(|f| f >= LAST_CALL_TIME_FRACTION))
1111                    {
1112                        if self.fingerprint() != start_fp {
1113                            progressed = true;
1114                        } else {
1115                            history.push(Message::User(
1116                                "[blyte] Still no change after the last reminder. Reply now with your conclusion and why, and do not call any tools: the run stops if this reply calls a tool without changing anything."
1117                                    .to_string(),
1118                            ));
1119                            last_call_sent = true;
1120                        }
1121                    } else if last_call_sent && last_turn_called_tools {
1122                        if self.fingerprint() != start_fp {
1123                            progressed = true;
1124                        } else {
1125                            report.stalled = true;
1126                            return (Outcome::BudgetExhausted, report);
1127                        }
1128                    }
1129                }
1130            }
1131
1132            let fold_budget = self.context.fold_budget(history);
1133            if let Some(prev_start) = prev_turn_start {
1134                if let Some(budget) = fold_budget {
1135                    let n: usize = history[prev_start..]
1136                        .iter()
1137                        .filter(|m| matches!(m, Message::ToolResult { .. }))
1138                        .map(crate::context::approx_tokens)
1139                        .sum();
1140                    if n > budget / 2 {
1141                        report.big_read_turns += 1;
1142                        if last_big_read_warn.is_none_or(|last| turn >= last + 5) {
1143                            last_big_read_warn = Some(turn);
1144                            history.push(Message::User(format!(
1145                                "[blyte] Your last turn's tool output was about {n} tokens, more than half of what stays in context ({budget}). Read narrower ranges so it is not dropped before you use it."
1146                            )));
1147                        }
1148                    }
1149                }
1150                if self
1151                    .context
1152                    .folds(history)
1153                    .last()
1154                    .is_some_and(|&(_, b)| b + 1 > prev_start)
1155                {
1156                    thrash += 1;
1157                    if thrash >= 5 {
1158                        report.fold_thrash = true;
1159                        return (Outcome::BudgetExhausted, report);
1160                    }
1161                    if thrash == 2 {
1162                        let budget = fold_budget.unwrap_or_default();
1163                        history.push(Message::User(format!(
1164                            "[blyte] Your recent tool results are being dropped from your context because each turn reads more than fits (about {budget} tokens stay verbatim). Read narrower ranges (at most 200 lines), one or two files per turn, and act on what you have read before reading more."
1165                        )));
1166                    }
1167                } else {
1168                    thrash = 0;
1169                }
1170            }
1171            prev_turn_start = Some(turn_start);
1172
1173            let mut req = Request {
1174                system: system.to_string(),
1175                messages: self.context.build(state, history),
1176                tools: specs.clone(),
1177                max_output_tokens: None,
1178                timeout: None,
1179            };
1180            let (appended, new_chars) = match &last_sent {
1181                Some(prev)
1182                    if req.messages.len() >= prev.len()
1183                        && req.messages[..prev.len()] == prev[..] =>
1184                {
1185                    (
1186                        true,
1187                        req.messages[prev.len()..].iter().map(message_chars).sum(),
1188                    )
1189                }
1190                _ => (false, req.messages.iter().map(message_chars).sum()),
1191            };
1192            last_sent = Some(req.messages.clone());
1193            // A burst rate limit ended a run after 28 calls (2026-09-23). Transient failures are
1194            // waited out, but never past the deadline: a run that cannot finish in time reports.
1195            let model_start = now();
1196            let mut attempt = 0;
1197            let mut failed_attempts: Vec<FailedAttempt> = Vec::new();
1198            let resp = loop {
1199                if let Some(d) = deadline {
1200                    let time_left = d.saturating_duration_since(now());
1201                    if time_left.is_zero() {
1202                        return (Outcome::BudgetExhausted, report);
1203                    }
1204                    req.timeout = Some(time_left);
1205                }
1206                let call_start = std::time::Instant::now();
1207                match self.provider.complete(&req) {
1208                    Ok(r) => break r,
1209                    Err(e) => {
1210                        let (u_in, u_cached, u_out, u_think) = match &e {
1211                            ProviderError::NoAnswer { usage, .. } => {
1212                                report.usage.input += usage.input;
1213                                report.usage.cached += usage.cached;
1214                                report.usage.output += usage.output;
1215                                report.usage.thinking += usage.thinking;
1216                                (usage.input, usage.cached, usage.output, usage.thinking)
1217                            }
1218                            _ => (0, 0, 0, 0),
1219                        };
1220                        let push_deadline_turn = |report: &mut RunReport| {
1221                            let timing = self.provider.last_stream_timing().unwrap_or_default();
1222                            report.turn_usage.push(TurnUsage {
1223                                turn,
1224                                input: u_in,
1225                                cached: u_cached,
1226                                output: u_out,
1227                                thinking: u_think,
1228                                prompt_messages: req.messages.len(),
1229                                appended,
1230                                new_chars,
1231                                fold_budget,
1232                                model_ms: now().saturating_duration_since(model_start).as_millis()
1233                                    as u64,
1234                                tools_ms: 0,
1235                                first_data_ms: timing.first_data_ms,
1236                                max_gap_ms: timing.max_gap_ms,
1237                                failed_attempts: failed_attempts.clone(),
1238                            });
1239                        };
1240                        // An exhausted quota is reported as an error even past the deadline:
1241                        // the operator needs to see it to switch provider.
1242                        if quota_exhausted(&e).is_none() && deadline.is_some_and(|d| now() >= d) {
1243                            push_deadline_turn(&mut report);
1244                            return (Outcome::BudgetExhausted, report);
1245                        }
1246                        let max_retries = max_retries_for(&e);
1247                        if is_transient(&e) && attempt < max_retries {
1248                            let elapsed = call_start.elapsed().as_secs_f64().round() as u64;
1249                            let s = if elapsed > 0 {
1250                                elapsed
1251                            } else {
1252                                blyte_provider::model_timeout_secs()
1253                            };
1254                            attempt += 1;
1255                            let wait = retry_wait(&e, attempt);
1256                            if deadline.is_some_and(|d| now() + wait >= d) {
1257                                push_deadline_turn(&mut report);
1258                                return (Outcome::BudgetExhausted, report);
1259                            }
1260                            report.provider_retries += 1;
1261                            let timing = self.provider.last_stream_timing().unwrap_or_default();
1262                            failed_attempts.push(FailedAttempt {
1263                                elapsed_ms: call_start.elapsed().as_millis() as u64,
1264                                timed_out: e.is_timeout(),
1265                                first_data_ms: timing.first_data_ms,
1266                                max_gap_ms: timing.max_gap_ms,
1267                            });
1268                            let reason = if e.is_timeout() {
1269                                format!(
1270                                    "model call timed out after {s} s; retrying ({attempt} of {max_retries}; raise BLYTE_MODEL_IDLE_TIMEOUT_SECS for silence or BLYTE_MODEL_TIMEOUT_SECS for whole call)"
1271                                )
1272                            } else {
1273                                format!(
1274                                    "provider: {e}; retrying in {}s ({attempt}/{max_retries})",
1275                                    wait.as_secs()
1276                                )
1277                            };
1278                            eprintln!("{reason}");
1279                            self.emit(Event::Retry {
1280                                attempt,
1281                                max: max_retries,
1282                                wait_ms: wait.as_millis() as u64,
1283                                reason,
1284                            });
1285                            sleep(wait);
1286                        } else {
1287                            let err_msg = match quota_exhausted(&e) {
1288                                Some(msg) => format!("{msg}: {e}"),
1289                                None => e.to_string(),
1290                            };
1291                            return (Outcome::Error(err_msg), report);
1292                        }
1293                    }
1294                }
1295            };
1296            let model_ms = now().saturating_duration_since(model_start).as_millis() as u64;
1297            let timing: StreamTiming = self.provider.last_stream_timing().unwrap_or_default();
1298            report.usage.input += resp.usage.input;
1299            report.usage.cached += resp.usage.cached;
1300            report.usage.output += resp.usage.output;
1301            report.usage.thinking += resp.usage.thinking;
1302            report.turn_usage.push(TurnUsage {
1303                turn,
1304                input: resp.usage.input,
1305                cached: resp.usage.cached,
1306                output: resp.usage.output,
1307                thinking: resp.usage.thinking,
1308                prompt_messages: req.messages.len(),
1309                appended,
1310                new_chars,
1311                fold_budget,
1312                model_ms,
1313                tools_ms: 0,
1314                first_data_ms: timing.first_data_ms,
1315                max_gap_ms: timing.max_gap_ms,
1316                failed_attempts,
1317            });
1318
1319            let trimmed = resp.text.trim();
1320            self.emit(Event::Turn {
1321                n: turn,
1322                text: trimmed,
1323                usage: resp.usage,
1324            });
1325            if truncated(resp.finish_reason.as_deref()) {
1326                last_turn_called_tools = false;
1327                report.truncated_turns += 1;
1328                history.push(Message::User(
1329                    "Your last reply hit the output token limit and was cut off, so none of it was used. Reply again more briefly: make one tool call at a time and keep edits small.".to_string(),
1330                ));
1331                continue;
1332            }
1333            if trimmed.is_empty() && resp.tool_calls.is_empty() {
1334                report.empty_turns += 1;
1335            }
1336            if !trimmed.is_empty() {
1337                report.final_message = Some(trimmed.to_string());
1338                history.push(Message::Assistant(resp.text.clone()));
1339            }
1340
1341            // --- the model is still working -------------------------------------------------
1342            if !resp.tool_calls.is_empty() {
1343                last_turn_called_tools = true;
1344                let tools_start = now();
1345                // A turn's calls are recorded together, then its results together, in call
1346                // order. Providers encode one model turn carrying several calls and one reply
1347                // carrying their results; interleaving them split a parallel batch into turns
1348                // Gemini rejects (it signs only the first call of a batch).
1349                for call in &resp.tool_calls {
1350                    history.push(Message::ToolCall {
1351                        id: call.id.clone(),
1352                        name: call.name.clone(),
1353                        arguments: call.arguments.clone(),
1354                        signature: call.signature.clone(),
1355                    });
1356                }
1357                let current_fp = self.fingerprint();
1358                if current_fp != start_fp {
1359                    progressed = true;
1360                }
1361                if current_fp != change_fp {
1362                    call_counts.clear();
1363                    repeats = 0;
1364                    read_warn_sent = false;
1365                    change_fp = current_fp;
1366                }
1367                for call in &resp.tool_calls {
1368                    if deadline.is_some_and(|d| now() >= d) {
1369                        report.turn_usage.last_mut().unwrap().tools_ms =
1370                            now().saturating_duration_since(tools_start).as_millis() as u64;
1371                        return (Outcome::BudgetExhausted, report);
1372                    }
1373                    report.tool_calls += 1;
1374                    *report.tool_counts.entry(call.name.clone()).or_default() += 1;
1375
1376                    if wrap_up_tools_closed
1377                        && self
1378                            .fs
1379                            .read(&self.root.join("report.md"))
1380                            .ok()
1381                            .is_some_and(|s| {
1382                                !s.is_empty() && Some(s.as_str()) != wrap_up_report.as_deref()
1383                            })
1384                    {
1385                        wrap_up_tools_closed = false;
1386                    }
1387                    let read_closed = read_loop_turn.is_some()
1388                        && matches!(call.name.as_str(), "read" | "grep" | "glob");
1389                    let wrap_up_closed =
1390                        wrap_up_tools_closed && !matches!(call.name.as_str(), "write" | "edit");
1391                    let tool_closed = read_closed || wrap_up_closed;
1392                    let input = if call.name == "read" {
1393                        extract_action_target(&call.name, &call.arguments)
1394                            .chars()
1395                            .take(100)
1396                            .collect()
1397                    } else {
1398                        let clean = |s: &str| s.trim_end().replace('\n', " ↵ ");
1399                        let text = if call.name == "blyte" {
1400                            format_blyte_tool_input(&call.arguments)
1401                                .map(|s| clean(&s))
1402                                .unwrap_or_else(|| clean(&call.arguments.to_string()))
1403                        } else {
1404                            call.arguments
1405                                .get("command")
1406                                .or_else(|| call.arguments.get("pattern"))
1407                                .or_else(|| call.arguments.get("path"))
1408                                .and_then(|v| v.as_str())
1409                                .map(clean)
1410                                .unwrap_or_else(|| clean(&call.arguments.to_string()))
1411                        };
1412                        if text.chars().count() > 2000 {
1413                            let mut cut: String = text.chars().take(2000).collect();
1414                            cut.push('…');
1415                            cut
1416                        } else {
1417                            text
1418                        }
1419                    };
1420                    self.emit(Event::ToolStart {
1421                        name: &call.name,
1422                        input: input.clone(),
1423                    });
1424                    let mut outcome = if read_closed {
1425                        tools::ToolOutcome {
1426                            content: "[blyte] reading is closed; write report.md now from what you have found.".to_string(),
1427                            is_error: true,
1428                        }
1429                    } else if wrap_up_closed {
1430                        tools::ToolOutcome {
1431                            content: "[blyte] almost out of budget: write report.md now (write or edit). Other tools are closed until report.md has changed.".to_string(),
1432                            is_error: true,
1433                        }
1434                    } else {
1435                        let tool_timeout = deadline
1436                            .map(|d| d.saturating_duration_since(now()))
1437                            // No run deadline: each tool's own ceiling applies (300 s for most,
1438                            // longer for `blyte edit-finish`, which runs the check).
1439                            .unwrap_or(Duration::MAX);
1440                        tools::execute_with_timeout(
1441                            &self.root,
1442                            self.shell,
1443                            self.fs,
1444                            &call.name,
1445                            &call.arguments,
1446                            tool_timeout,
1447                        )
1448                    };
1449
1450                    let summary = outcome
1451                        .content
1452                        .lines()
1453                        .next()
1454                        .unwrap_or("")
1455                        .chars()
1456                        .take(90)
1457                        .collect::<String>();
1458                    self.emit(Event::Tool {
1459                        name: &call.name,
1460                        input,
1461                        summary,
1462                        is_error: outcome.is_error,
1463                    });
1464
1465                    if self.research && !tool_closed {
1466                        seen_names.extend(
1467                            research_check::identifiers(&outcome.content).map(str::to_owned),
1468                        );
1469                    }
1470                    if !outcome.is_error && matches!(call.name.as_str(), "edit" | "write") {
1471                        progressed = true;
1472                        call_counts.clear();
1473                        repeats = 0;
1474                        read_warn_sent = false;
1475                    } else if !tool_closed && matches!(call.name.as_str(), "read" | "grep" | "glob")
1476                    {
1477                        let key = format!("{}:{}", call.name, call.arguments);
1478                        let n = call_counts.entry(key).or_insert(0);
1479                        *n += 1;
1480                        let n = *n;
1481                        if n >= 2 {
1482                            repeats += 1;
1483                            report.peak_read_repeats = report.peak_read_repeats.max(repeats);
1484                        }
1485                        if n >= 3 {
1486                            let tail = if self.research {
1487                                "write what you need into report.md"
1488                            } else {
1489                                "and make your change"
1490                            };
1491                            outcome.content.push_str(&format!(
1492                                "\n\n[blyte] You have made this exact call {n} times since the workspace last changed; earlier results were dropped from your context to save space. Do not read it again: note what you need from it in your reply, read only the lines you need, {tail}."
1493                            ));
1494                        }
1495                        if self.research && !read_warn_sent && repeats >= READ_LOOP_WARN {
1496                            read_warn_sent = true;
1497                            outcome.content.push_str(&format!(
1498                                "\n\n[blyte] You have re-read {READ_LOOP_WARN} files or searches since the workspace last changed; earlier results were dropped to save space. Write what you need into report.md now; reading stops at {READ_LOOP_LIMIT}."
1499                            ));
1500                        }
1501                    }
1502                    history.push(Message::ToolResult {
1503                        id: call.id.clone(),
1504                        name: call.name.clone(),
1505                        content: outcome.content,
1506                        is_error: outcome.is_error,
1507                    });
1508                    if repeats >= READ_LOOP_LIMIT && read_loop_turn.is_none() {
1509                        report.read_loop = true;
1510                        if !self.research {
1511                            report.turn_usage.last_mut().unwrap().tools_ms =
1512                                now().saturating_duration_since(tools_start).as_millis() as u64;
1513                            return (Outcome::BudgetExhausted, report);
1514                        }
1515                        read_loop_turn = Some(turn);
1516                    }
1517                }
1518                if read_loop_turn == Some(turn) {
1519                    history.push(Message::User(
1520                        "[blyte] Stop reading; write report.md now from what you have found, mark what you could not confirm as open questions, then stop calling tools.".to_string(),
1521                    ));
1522                }
1523                report.turn_usage.last_mut().unwrap().tools_ms =
1524                    now().saturating_duration_since(tools_start).as_millis() as u64;
1525                continue;
1526            }
1527
1528            // --- the model stopped calling tools: the runtime decides -----------------------
1529            last_turn_called_tools = false;
1530            if report.gate_attempts > 0
1531                && CLAIM_PHRASES
1532                    .iter()
1533                    .any(|&p| resp.text.to_lowercase().contains(p))
1534            {
1535                if let (Some(last_fp), Some(curr_fp), Some(base_commit)) =
1536                    (&last_fingerprint, self.fingerprint(), &baseline)
1537                {
1538                    if *last_fp == curr_fp && self.check_blocked_at_base(base_commit, &last_failed)
1539                    {
1540                        let steps = last_failed.join("; ");
1541                        let text: String = resp.text.chars().take(300).collect();
1542                        return (
1543                            Outcome::Blocked(format!(
1544                                "the check fails at the base commit too ({steps}); the model said: {text}"
1545                            )),
1546                            report,
1547                        );
1548                    }
1549                }
1550            }
1551
1552            if state.brief.verification_cmd.trim().is_empty() {
1553                if state.brief.instructions.is_some() {
1554                    return (Outcome::Finished, report);
1555                }
1556                self.finalize_polled_base_check(&mut report);
1557                return (Outcome::Verified, report);
1558            }
1559
1560            progressed = true;
1561            report.gate_attempts += 1;
1562            report.gate_turns.push(turn);
1563            self.emit(Event::GateStart {
1564                attempt: report.gate_attempts,
1565            });
1566            let gate_start = now();
1567            let (mut passed, mut output, wait_ms, failing) =
1568                self.run_gate(state, &last_failed, &mut deadline, now);
1569            last_failed = failing;
1570            if passed && self.research {
1571                let mut problems = self.check_report_quotes(seen_names);
1572                if !problems.is_empty() {
1573                    passed = false;
1574                    output = format!("exit 1\n{}", research_check::render(&problems));
1575                }
1576                problems.truncate(research_check::MAX_PROBLEMS);
1577                report.quote_problems = Some(problems);
1578                if passed {
1579                    if let Some(cc) = self.run_claim_check(claim_deadline, now) {
1580                        report.usage.input += cc.usage.input;
1581                        report.usage.cached += cc.usage.cached;
1582                        report.usage.output += cc.usage.output;
1583                        report.usage.thinking += cc.usage.thinking;
1584                        report.claim_check_skipped = cc.skipped.clone();
1585                        if !cc.contradicted.is_empty() && !claim_round_done {
1586                            claim_round_done = true;
1587                            passed = false;
1588                            let mut lines: Vec<String> = cc
1589                                .contradicted
1590                                .iter()
1591                                .map(|f| {
1592                                    let text: String = f.text.chars().take(200).collect();
1593                                    format!("report.md:{}: {text}\n  checker: {}", f.line, f.reason)
1594                                })
1595                                .collect();
1596                            lines.push(
1597                                "These claims do not match the lines they cite. Fix each claim, cite the lines that support it, or remove it."
1598                                    .to_string(),
1599                            );
1600                            output = format!("exit 1\n{}", lines.join("\n"));
1601                        }
1602                        if cc.calls > 0 || cc.skipped.is_none() {
1603                            report.claim_check = Some(cc);
1604                        }
1605                    }
1606                }
1607            }
1608            report
1609                .gate_ms
1610                .push(now().saturating_duration_since(gate_start).as_millis() as u64);
1611            report.gate_wait_ms.push(wait_ms);
1612            self.emit(Event::Gate {
1613                attempt: report.gate_attempts,
1614                passed,
1615                output: output.lines().next().unwrap_or(""),
1616            });
1617            if passed {
1618                self.finalize_polled_base_check(&mut report);
1619                return (Outcome::Verified, report);
1620            }
1621            report.gate_failures.push(cut_gate_output(&output));
1622            if deadline.is_some_and(|d| now() >= d) {
1623                return (Outcome::BudgetExhausted, report);
1624            }
1625
1626            last_fingerprint = self.fingerprint();
1627            if last_fingerprint != start_fp {
1628                progressed = true;
1629            }
1630
1631            if self.rollback {
1632                if let Some(base) = &baseline {
1633                    if let Err(msg) = self.reset_to(base) {
1634                        return (Outcome::Error(msg), report);
1635                    }
1636                    state.runtime.rollbacks += 1;
1637                    let short_sha = &base[..base.len().min(8)];
1638                    self.emit(Event::RolledBack { to: short_sha });
1639                }
1640            }
1641            if report.gate_attempts >= self.budget.max_gate_attempts {
1642                return (Outcome::GateFailed, report);
1643            }
1644
1645            // Fed back as an observation, not a request to try harder. The worker is told what
1646            // the command said and, if the tree was reset, that its edits are gone -- silently
1647            // resetting would leave it editing against a file it no longer has.
1648            let reset_note = if self.rollback && baseline.is_some() {
1649                "\n\nYour changes have been reverted to the last verified state. Start from \
1650                 the current files, not from what you remember writing."
1651            } else {
1652                ""
1653            };
1654            let advice = if self.research {
1655                "Fix report.md as listed above, then reply with one line."
1656            } else {
1657                "If the failure is caused by your change, fix your change, not the machine. \
1658                 If it is not caused by your change (disk space, network, a missing service), \
1659                 say so and stop."
1660            };
1661            history.push(Message::User(format!(
1662                "Verification did not pass.\n\n{output}\n\n{advice}{reset_note}"
1663            )));
1664        }
1665        (Outcome::BudgetExhausted, report)
1666    }
1667
1668    fn finalize_polled_base_check(&self, report: &mut RunReport) {
1669        let BaseCheck::Polled(handle) = self.base_check else {
1670            return;
1671        };
1672        if report.base_check_passed == Some(true) {
1673            if report.base_check_seconds.is_none() {
1674                report.base_check_seconds = handle.elapsed_seconds();
1675            }
1676            return;
1677        }
1678        let final_state = match handle.poll() {
1679            BaseCheckState::Pending => handle.wait(),
1680            other => other,
1681        };
1682        report.base_check_seconds = handle.elapsed_seconds();
1683        match final_state {
1684            BaseCheckState::Passed => {
1685                report.base_check_passed = Some(true);
1686            }
1687            BaseCheckState::Failed { .. } => {
1688                report.base_check_passed = Some(false);
1689                let note = "the check failed on the untouched code but passes with this change";
1690                report.final_message = Some(match report.final_message.take() {
1691                    Some(existing) if !existing.is_empty() => format!("{existing}\n\n{note}"),
1692                    _ => note.to_string(),
1693                });
1694            }
1695            BaseCheckState::Pending => {}
1696        }
1697    }
1698}
1699
1700/// A single failing gate step and its bounded output.
1701const SANDBOX_DENIAL_HINT: &str = "hint: \"Operation not permitted\" usually means blyte's sandbox denied a path outside the worktree (for example a .env in the main checkout). Make the check independent of files outside the worktree.";
1702
1703/// Returns a sandbox hint when `output` mentions `operation not permitted` in any letter case.
1704pub fn sandbox_denial_hint(output: &str) -> Option<&'static str> {
1705    if output
1706        .to_ascii_lowercase()
1707        .contains("operation not permitted")
1708    {
1709        Some(SANDBOX_DENIAL_HINT)
1710    } else {
1711        None
1712    }
1713}
1714
1715fn append_hint_line(output: &mut String, hint: &str) {
1716    if output.trim_end_matches(['\r', '\n']).ends_with(hint) {
1717        return;
1718    }
1719    if !output.ends_with('\n') {
1720        output.push('\n');
1721    }
1722    output.push_str(hint);
1723}
1724
1725/// Appends the sandbox denial hint to `output` once when applicable.
1726pub fn append_sandbox_denial_hint(output: &mut String) {
1727    if let Some(hint) = sandbox_denial_hint(output) {
1728        append_hint_line(output, hint);
1729    }
1730}
1731
1732fn attach_sandbox_denial_hint(result: &mut GateRunResult) {
1733    if result.passed {
1734        return;
1735    }
1736    let hint = sandbox_denial_hint(&result.output).or_else(|| {
1737        result
1738            .failures
1739            .iter()
1740            .find_map(|f| sandbox_denial_hint(&f.output))
1741    });
1742    let Some(hint) = hint else {
1743        return;
1744    };
1745    append_hint_line(&mut result.output, hint);
1746    if let Some(last) = result.failures.last_mut() {
1747        append_hint_line(&mut last.output, hint);
1748    }
1749}
1750
1751#[derive(Debug, Clone, PartialEq, Eq)]
1752pub struct GateStepFailure {
1753    pub step: String,
1754    pub output: String,
1755}
1756
1757/// Result of running a verification gate across all of its steps.
1758#[derive(Debug, Clone, PartialEq, Eq)]
1759pub struct GateRunResult {
1760    pub passed: bool,
1761    pub output: String,
1762    pub wait_ms: u64,
1763    pub failures: Vec<GateStepFailure>,
1764}
1765
1766/// Run one gate step in `dir` through `shell`, returning `(passed, bounded_output)`.
1767pub fn run_gate_step(
1768    shell: &dyn Shell,
1769    cmd: &str,
1770    dir: &Path,
1771    deadline: Option<std::time::Instant>,
1772    now: &(dyn Fn() -> std::time::Instant + Sync),
1773) -> (bool, String) {
1774    let timeout = match deadline {
1775        Some(d) => {
1776            let left = d.saturating_duration_since(now());
1777            if left.is_zero() {
1778                return (false, "exit 124\ngate ran out of time".into());
1779            }
1780            Duration::from_secs(1800).min(left)
1781        }
1782        None => Duration::from_secs(1800),
1783    };
1784    let wrapped = format!("(export {}=1\n{cmd}\n)", gate_slots::IN_GATE_ENV);
1785    match shell.exec(&wrapped, dir, timeout) {
1786        Ok(o) => {
1787            let merged = o.merged();
1788            let raw = merged.trim_end();
1789            let body = tools::bound_output(raw);
1790            let dropped: Vec<&str> = if o.exit_code != 0 {
1791                let kept: std::collections::HashSet<&str> = body.lines().map(str::trim).collect();
1792                summary_lines(raw)
1793                    .into_iter()
1794                    .filter(|l| !kept.contains(l))
1795                    .collect()
1796            } else {
1797                Vec::new()
1798            };
1799            let content = if dropped.is_empty() {
1800                body
1801            } else {
1802                let block = format!("Failing, in lines blyte left out:\n{}", dropped.join("\n"));
1803                if body.is_empty() {
1804                    block
1805                } else {
1806                    format!("{block}\n\n{body}")
1807                }
1808            };
1809            if o.exit_code != 0 && deadline.is_some_and(|d| now() >= d) {
1810                if content.is_empty() {
1811                    return (false, format!("exit {}\ngate ran out of time", o.exit_code));
1812                }
1813                return (
1814                    false,
1815                    format!("exit {}\ngate ran out of time\n{content}", o.exit_code),
1816                );
1817            }
1818            (o.exit_code == 0, format!("exit {}\n{content}", o.exit_code))
1819        }
1820        Err(e) => {
1821            if deadline.is_some_and(|d| now() >= d) {
1822                return (false, format!("gate ran out of time: {e}"));
1823            }
1824            (false, format!("verification command could not run: {e}"))
1825        }
1826    }
1827}
1828
1829/// Run a multi-line verification gate in `dir` through `shell`, acquiring a gate slot if enabled.
1830pub fn run_gate_steps(
1831    shell: &dyn Shell,
1832    gate: &str,
1833    dir: &Path,
1834    last_failed: &[String],
1835    deadline: &mut Option<std::time::Instant>,
1836    on_slot_wait: impl FnOnce(u64),
1837    now: &(dyn Fn() -> std::time::Instant + Sync),
1838) -> GateRunResult {
1839    run_gate_steps_cancellable(
1840        shell,
1841        gate,
1842        dir,
1843        last_failed,
1844        deadline,
1845        on_slot_wait,
1846        now,
1847        None,
1848    )
1849}
1850
1851/// Run a multi-line verification gate in `dir` through `shell`, stopping early if `cancel` is triggered.
1852#[allow(clippy::too_many_arguments)]
1853pub fn run_gate_steps_cancellable(
1854    shell: &dyn Shell,
1855    gate: &str,
1856    dir: &Path,
1857    last_failed: &[String],
1858    deadline: &mut Option<std::time::Instant>,
1859    on_slot_wait: impl FnOnce(u64),
1860    now: &(dyn Fn() -> std::time::Instant + Sync),
1861    cancel: Option<&crate::shell::CancelHandle>,
1862) -> GateRunResult {
1863    let (_guard, wait_ms) = if gate_slots::enabled() && !gate_slots::nested() {
1864        let max_slots = gate_slots::slots();
1865        let slot_dir = gate_slots::slot_dir();
1866        match gate_slots::acquire_cancellable(
1867            max_slots,
1868            &slot_dir,
1869            Duration::from_millis(500),
1870            cancel.map(crate::shell::CancelHandle::flag),
1871        ) {
1872            Ok(Some((guard, waited))) => {
1873                let wait_ms = waited.as_millis() as u64;
1874                if let Some(d) = deadline.as_mut() {
1875                    *d += waited;
1876                }
1877                if wait_ms > 0 {
1878                    eprintln!(
1879                        "gate: waited {}s for a gate slot ({max_slots} in use)",
1880                        waited.as_secs()
1881                    );
1882                    on_slot_wait(wait_ms);
1883                }
1884                (Some(guard), wait_ms)
1885            }
1886            Ok(None) => {
1887                return GateRunResult {
1888                    passed: false,
1889                    output: "cancelled".into(),
1890                    wait_ms: 0,
1891                    failures: Vec::new(),
1892                };
1893            }
1894            Err(e) => {
1895                eprintln!("gate: slot acquisition failed: {e}");
1896                (None, 0)
1897            }
1898        }
1899    } else {
1900        (None, 0)
1901    };
1902
1903    if cancel.is_some_and(crate::shell::CancelHandle::is_cancelled) {
1904        return GateRunResult {
1905            passed: false,
1906            output: "cancelled".into(),
1907            wait_ms,
1908            failures: Vec::new(),
1909        };
1910    }
1911
1912    let steps = gate_steps(gate);
1913    if steps.len() <= 1 {
1914        let step_cmd = steps.first().copied().unwrap_or(gate);
1915        let (passed, output) = run_gate_step(shell, step_cmd, dir, *deadline, now);
1916        let failures = if passed {
1917            Vec::new()
1918        } else {
1919            vec![GateStepFailure {
1920                step: step_cmd.to_string(),
1921                output: output.clone(),
1922            }]
1923        };
1924        let mut result = GateRunResult {
1925            passed,
1926            output,
1927            wait_ms,
1928            failures,
1929        };
1930        attach_sandbox_denial_hint(&mut result);
1931        return result;
1932    }
1933    let (first_group, second_group) = {
1934        let (f, s) = retry_order(&steps, last_failed);
1935        if f.is_empty() {
1936            (steps.clone(), Vec::new())
1937        } else {
1938            (f, s)
1939        }
1940    };
1941    let mut formatted_failures = Vec::new();
1942    let mut failures = Vec::new();
1943    for &step in &first_group {
1944        if cancel.is_some_and(crate::shell::CancelHandle::is_cancelled) {
1945            break;
1946        }
1947        let (passed, output) = run_gate_step(shell, step, dir, *deadline, now);
1948        if !passed {
1949            formatted_failures.push(format!("$ {step}\n{output}"));
1950            failures.push(GateStepFailure {
1951                step: step.to_string(),
1952                output,
1953            });
1954            if deadline.is_some_and(|d| now() >= d)
1955                || cancel.is_some_and(crate::shell::CancelHandle::is_cancelled)
1956            {
1957                break;
1958            }
1959        }
1960    }
1961    if !failures.is_empty() {
1962        let body = tools::bound_output(&formatted_failures.join("\n\n"));
1963        let failed_names: Vec<&str> = failures.iter().map(|f| f.step.as_str()).collect();
1964        let not_rerun = if !second_group.is_empty() {
1965            format!(
1966                "\nNot re-run this attempt: {} step(s) that passed last time ({}).",
1967                second_group.len(),
1968                second_group.join(", ")
1969            )
1970        } else {
1971            String::new()
1972        };
1973        let mut result = GateRunResult {
1974            passed: false,
1975            output: format!(
1976                "{} of {} steps failed: {}{not_rerun}\n\n{body}",
1977                failures.len(),
1978                steps.len(),
1979                failed_names.join(", ")
1980            ),
1981            wait_ms,
1982            failures,
1983        };
1984        attach_sandbox_denial_hint(&mut result);
1985        return result;
1986    }
1987    for &step in &second_group {
1988        if cancel.is_some_and(crate::shell::CancelHandle::is_cancelled) {
1989            break;
1990        }
1991        let (passed, output) = run_gate_step(shell, step, dir, *deadline, now);
1992        if !passed {
1993            formatted_failures.push(format!("$ {step}\n{output}"));
1994            failures.push(GateStepFailure {
1995                step: step.to_string(),
1996                output,
1997            });
1998            if deadline.is_some_and(|d| now() >= d)
1999                || cancel.is_some_and(crate::shell::CancelHandle::is_cancelled)
2000            {
2001                break;
2002            }
2003        }
2004    }
2005    if failures.is_empty() {
2006        return GateRunResult {
2007            passed: true,
2008            output: "exit 0".into(),
2009            wait_ms,
2010            failures: Vec::new(),
2011        };
2012    }
2013    let body = tools::bound_output(&formatted_failures.join("\n\n"));
2014    let failed_names: Vec<&str> = failures.iter().map(|f| f.step.as_str()).collect();
2015    let mut result = GateRunResult {
2016        passed: false,
2017        output: format!(
2018            "{} of {} steps failed: {}\n\n{body}",
2019            failures.len(),
2020            steps.len(),
2021            failed_names.join(", ")
2022        ),
2023        wait_ms,
2024        failures,
2025    };
2026    attach_sandbox_denial_hint(&mut result);
2027    result
2028}
2029
2030/// The steps of a gate: its non-blank lines, trimmed.
2031pub fn gate_steps(gate: &str) -> Vec<&str> {
2032    gate.lines()
2033        .map(str::trim)
2034        .filter(|s| !s.is_empty())
2035        .collect()
2036}
2037
2038/// Splits `steps` into (the steps whose text is in `last_failed`, in gate order; the
2039/// others, in gate order). With an empty `last_failed`, returns (all steps, nothing).
2040pub fn retry_order<'a>(steps: &[&'a str], last_failed: &[String]) -> (Vec<&'a str>, Vec<&'a str>) {
2041    if last_failed.is_empty() {
2042        return (steps.to_vec(), Vec::new());
2043    }
2044    let mut failed = Vec::new();
2045    let mut others = Vec::new();
2046    for &step in steps {
2047        if last_failed.iter().any(|f| f == step) {
2048            failed.push(step);
2049        } else {
2050            others.push(step);
2051        }
2052    }
2053    (failed, others)
2054}
2055
2056/// Summary lines from test runners (cargo, pytest, rustc).
2057fn is_summary_line(line: &str) -> bool {
2058    let t = line.trim();
2059    ((t.starts_with("FAILED ") || t.starts_with("ERROR "))
2060        && (t.contains("::") || t.contains(".py")))
2061        || (t.starts_with('=') && (t.contains(" failed") || t.contains(" error")))
2062        || (t.starts_with("test ") && t.ends_with("FAILED"))
2063        || t.starts_with("error[")
2064        || t.starts_with("error:")
2065        || t.starts_with("test result: FAILED")
2066}
2067
2068/// Collects up to 40 unique summary lines in order of appearance.
2069fn summary_lines(output: &str) -> Vec<&str> {
2070    let mut lines = Vec::new();
2071    let mut seen = std::collections::HashSet::new();
2072    for line in output.lines() {
2073        let t = line.trim();
2074        if is_summary_line(t) && seen.insert(t) {
2075            lines.push(t);
2076            if lines.len() == 40 {
2077                break;
2078            }
2079        }
2080    }
2081    lines
2082}
2083
2084/// Checks if a line matches blyte's own "N of M steps failed: …" header format.
2085fn is_blyte_header(line: &str) -> bool {
2086    let t = line.trim();
2087    let Some((n, rest)) = t.split_once(" of ") else {
2088        return false;
2089    };
2090    if !n.chars().all(|c| c.is_ascii_digit()) || n.is_empty() {
2091        return false;
2092    }
2093    let Some((m, _)) = rest.split_once(" steps failed:") else {
2094        return false;
2095    };
2096    m.chars().all(|c| c.is_ascii_digit()) && !m.is_empty()
2097}
2098
2099/// Cuts gate output longer than 4,000 characters, keeping test runner summary lines,
2100/// the header, and the head and tail.
2101pub fn cut_gate_output(output: &str) -> String {
2102    const MAX_CHARS: usize = 4_000;
2103
2104    let total_chars = output.chars().count();
2105    if total_chars <= MAX_CHARS {
2106        return output.to_string();
2107    }
2108
2109    let sum_lines = summary_lines(output);
2110    let has_summary = !sum_lines.is_empty();
2111
2112    let first_line = output.lines().next().unwrap_or("");
2113    let has_blyte_header = is_blyte_header(first_line);
2114
2115    let (header, rem) = if has_summary && has_blyte_header {
2116        let rem = &output[first_line.len()..];
2117        let rem = rem.trim_start_matches(['\r', '\n']);
2118        (Some(first_line), rem)
2119    } else {
2120        (None, output)
2121    };
2122
2123    let summary_block = if has_summary {
2124        let mut block = String::from("Failing, from the full output:\n");
2125        block.push_str(&sum_lines.join("\n"));
2126        Some(block)
2127    } else {
2128        None
2129    };
2130
2131    let prefix_chars = header.map(|h| h.chars().count() + 1).unwrap_or(0)
2132        + summary_block
2133            .as_ref()
2134            .map(|s| s.chars().count() + 1)
2135            .unwrap_or(0);
2136
2137    let available = MAX_CHARS.saturating_sub(prefix_chars);
2138    let head_budget = available / 4;
2139    let tail_budget = available - head_budget;
2140
2141    let head = if head_budget == 0 || rem.is_empty() {
2142        ""
2143    } else {
2144        let head_cand_end = rem
2145            .char_indices()
2146            .nth(head_budget)
2147            .map(|(i, _)| i)
2148            .unwrap_or(rem.len());
2149        let head_cand = &rem[..head_cand_end];
2150        match head_cand.rfind('\n') {
2151            Some(idx) => &head_cand[..idx],
2152            None => head_cand,
2153        }
2154    };
2155
2156    let tail = if tail_budget == 0 {
2157        ""
2158    } else {
2159        let tail_cand_start = output
2160            .char_indices()
2161            .nth(total_chars.saturating_sub(tail_budget))
2162            .map(|(i, _)| i)
2163            .unwrap_or(output.len());
2164        let tail_cand = &output[tail_cand_start..];
2165        match tail_cand.find('\n') {
2166            Some(idx) => &tail_cand[idx + 1..],
2167            None => tail_cand,
2168        }
2169    };
2170
2171    let dropped = total_chars.saturating_sub(head.chars().count() + tail.chars().count());
2172
2173    let mut pieces = Vec::new();
2174    if let Some(h) = header {
2175        pieces.push(h);
2176    }
2177    if let Some(sb) = &summary_block {
2178        pieces.push(sb.as_str());
2179    }
2180    if !head.is_empty() {
2181        pieces.push(head);
2182    }
2183    let marker = format!("… [{dropped} characters cut] …");
2184    pieces.push(&marker);
2185    if !tail.is_empty() {
2186        pieces.push(tail);
2187    }
2188    let mut joined = pieces.join("\n");
2189    if output
2190        .trim_end_matches(['\r', '\n'])
2191        .ends_with(SANDBOX_DENIAL_HINT)
2192    {
2193        append_hint_line(&mut joined, SANDBOX_DENIAL_HINT);
2194    }
2195    joined
2196}
2197
2198fn format_blyte_arg(arg: &str) -> String {
2199    if arg.is_empty()
2200        || arg
2201            .chars()
2202            .any(|c| c.is_whitespace() || c == '"' || c == '\'')
2203    {
2204        serde_json::to_string(arg).unwrap_or_else(|_| format!("\"{arg}\""))
2205    } else {
2206        arg.to_string()
2207    }
2208}
2209
2210pub fn format_blyte_tool_input(args: &serde_json::Value) -> Option<String> {
2211    let raw_args = args.get("args")?.as_array()?;
2212    let mut parts = Vec::with_capacity(raw_args.len() + 1);
2213    parts.push("blyte".to_string());
2214    for item in raw_args {
2215        parts.push(format_blyte_arg(item.as_str()?));
2216    }
2217    let mut cmd = parts.join(" ");
2218    if args.get("background").and_then(|v| v.as_bool()) == Some(true) {
2219        cmd.push_str(" (background)");
2220    }
2221    Some(cmd)
2222}
2223
2224/// Extracts a concise, human-readable target descriptor from a tool call's arguments.
2225///
2226/// Deterministic and zero-latency: formats tool targets without LLM invocation to
2227/// bound the prompt footprint in episodic action ledgers.
2228///
2229/// # Arguments
2230/// * `tool` - The name of the tool invoked (e.g. "read", "bash", "write").
2231/// * `args` - The JSON arguments supplied to the tool.
2232///
2233/// # Returns
2234/// A compact string identifying the target file, command, or parameter.
2235pub fn extract_action_target(tool: &str, args: &serde_json::Value) -> String {
2236    // Discriminate on known tool types to extract their canonical target representations.
2237    match tool {
2238        "read" => {
2239            // Extract the target file path and optionally the requested line range.
2240            if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
2241                let start = args.get("start_line").and_then(|v| {
2242                    v.as_u64()
2243                        .map(|n| n.to_string())
2244                        .or_else(|| v.as_str().map(|s| s.to_string()))
2245                });
2246                let end = args.get("end_line").and_then(|v| {
2247                    v.as_u64()
2248                        .map(|n| n.to_string())
2249                        .or_else(|| v.as_str().map(|s| s.to_string()))
2250                });
2251                // When line bounds are specified, annotate the path with 1-indexed line boundaries.
2252                match (start, end) {
2253                    (Some(s), Some(e)) => return format!("{path} (L{s}-L{e})"),
2254                    (Some(s), None) => return format!("{path} (L{s}+)"),
2255                    (None, Some(e)) => return format!("{path} (L1-L{e})"),
2256                    (None, None) => return path.to_string(),
2257                }
2258            }
2259        }
2260        "write" => {
2261            // Extract the destination path and include byte size for visibility into write volume.
2262            if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
2263                if let Some(content) = args.get("content").and_then(|v| v.as_str()) {
2264                    return format!("{path} ({} bytes)", content.len());
2265                }
2266                return path.to_string();
2267            }
2268        }
2269        "edit" => {
2270            // Edit targets are identified primarily by the target file being modified.
2271            if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
2272                return path.to_string();
2273            }
2274        }
2275        "bash" => {
2276            // Bash commands are bounded at 60 characters so long pipelines do not dominate context.
2277            // Newlines are sanitized to spaces to preserve single-line formatting in the action ledger.
2278            if let Some(cmd) = args.get("command").and_then(|v| v.as_str()) {
2279                let single_line = cmd.replace('\n', " ");
2280                if single_line.chars().count() > 60 {
2281                    let prefix: String = single_line.chars().take(57).collect();
2282                    return format!("{prefix}...");
2283                }
2284                return single_line;
2285            }
2286        }
2287        "glob" => {
2288            // Glob targets are represented by the file search pattern.
2289            if let Some(pattern) = args.get("pattern").and_then(|v| v.as_str()) {
2290                return pattern.to_string();
2291            }
2292        }
2293        "grep" => {
2294            // Grep targets represent the regex pattern and, when restricted, the target subtree.
2295            if let Some(pattern) = args.get("pattern").and_then(|v| v.as_str()) {
2296                if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
2297                    if !path.is_empty() {
2298                        return format!("pattern '{pattern}' in {path}");
2299                    }
2300                }
2301                return format!("pattern '{pattern}'");
2302            }
2303        }
2304        "blyte" => {
2305            if let Some(cmd) = format_blyte_tool_input(args) {
2306                return cmd;
2307            }
2308        }
2309        _ => {}
2310    }
2311
2312    // Fallback: extract the first string argument value found, or default to the tool name.
2313    if let Some(obj) = args.as_object() {
2314        for val in obj.values() {
2315            if let Some(s) = val.as_str() {
2316                return s.to_string();
2317            }
2318        }
2319    }
2320    tool.to_string()
2321}
2322
2323/// Extracts a one-line deterministic outcome summary from a tool execution result.
2324///
2325/// # Arguments
2326/// * `tool` - The name of the tool executed.
2327/// * `content` - Raw string output produced by the tool.
2328/// * `is_error` - Whether the tool execution resulted in an error status.
2329///
2330/// # Returns
2331/// A single-line summary string describing the outcome.
2332pub fn extract_action_summary(tool: &str, content: &str, is_error: bool) -> String {
2333    // Produce deterministic, bounded status summaries per tool category.
2334    match tool {
2335        "read" => {
2336            if is_error {
2337                let first = content
2338                    .lines()
2339                    .find(|l| !l.trim().is_empty())
2340                    .unwrap_or("read failed");
2341                let clamped: String = first.chars().take(80).collect();
2342                format!("failed: {clamped}")
2343            } else {
2344                // Count lines returned to indicate the volume read without including full content.
2345                let count = content.lines().count();
2346                format!("{count} lines read")
2347            }
2348        }
2349        "write" => {
2350            if is_error {
2351                let first = content
2352                    .lines()
2353                    .find(|l| !l.trim().is_empty())
2354                    .unwrap_or("write failed");
2355                let clamped: String = first.chars().take(80).collect();
2356                format!("failed: {clamped}")
2357            } else {
2358                // Static confirmation of file write completion.
2359                "file written".to_string()
2360            }
2361        }
2362        "edit" => {
2363            // Distinguish successful replacements from rejection/failure reasons.
2364            if is_error {
2365                let first = content
2366                    .lines()
2367                    .find(|l| !l.trim().is_empty())
2368                    .unwrap_or("edit failed");
2369                let clamped: String = first.chars().take(80).collect();
2370                format!("failed: {clamped}")
2371            } else {
2372                "string replaced".to_string()
2373            }
2374        }
2375        "bash" => {
2376            // Non-zero bash exits extract the terminal failure line to preserve diagnostics.
2377            if !is_error {
2378                "exit 0".to_string()
2379            } else {
2380                let last_line = content
2381                    .lines()
2382                    .rev()
2383                    .find(|l| !l.trim().is_empty())
2384                    .unwrap_or("command failed");
2385                let clamped: String = last_line.chars().take(80).collect();
2386                format!("failed: {clamped}")
2387            }
2388        }
2389        "glob" => {
2390            if is_error {
2391                let first = content
2392                    .lines()
2393                    .find(|l| !l.trim().is_empty())
2394                    .unwrap_or("glob failed");
2395                let clamped: String = first.chars().take(80).collect();
2396                format!("failed: {clamped}")
2397            } else {
2398                // Count matching file entries in the glob output.
2399                let count = content.lines().filter(|l| !l.trim().is_empty()).count();
2400                format!("{count} files matched")
2401            }
2402        }
2403        "grep" => {
2404            if is_error {
2405                let first = content
2406                    .lines()
2407                    .find(|l| !l.trim().is_empty())
2408                    .unwrap_or("grep failed");
2409                let clamped: String = first.chars().take(80).collect();
2410                format!("failed: {clamped}")
2411            } else {
2412                // Count matching occurrences found in content search.
2413                let count = content.lines().filter(|l| !l.trim().is_empty()).count();
2414                format!("{count} matches found")
2415            }
2416        }
2417        _ => {
2418            // Fallback for custom or unknown tools clamps the first line to 80 chars.
2419            let first = content.lines().next().unwrap_or("");
2420            first.chars().take(80).collect()
2421        }
2422    }
2423}