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