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