Skip to main content

harness_loop/
lib.rs

1//! ReAct agent loop with self-correction.
2//!
3//! Minimal v0.0.1 implementation:
4//! - Applies guides once at the start.
5//! - Sends `Context` (with `tools`) to the model.
6//! - Dispatches each returned tool call via [`ToolRegistry`].
7//! - Runs `Sensor::SelfCorrect` sensors after each action; auto-fix patches are
8//!   applied directly to the world, blocking signals are fed back to the model.
9//! - Stops when the model returns no tool calls, when `policy.max_iters` is
10//!   hit, or when a stuck-detector ([`StuckPolicy`], [`MonotonyPolicy`]) says
11//!   the run is spinning.
12
13// ── crates that used to be their own ───────────────────────────────────────
14// Ten of them, and not one carried a dependency a caller would want to avoid.
15// The boundaries bought nothing and cost every release ten more publishes and
16// every host ten more version pins; a crate boundary here has to name a
17// dependency you might not want, and these did not.
18pub mod blueprint;
19pub mod compactor;
20pub mod daemon;
21pub mod experience;
22pub mod hooks;
23pub mod loop_engine;
24pub mod orchestrator;
25pub mod sandbox;
26pub mod scheduler;
27pub mod templates;
28
29pub mod acceptance;
30pub mod goal;
31pub mod learning;
32pub mod memory_layer;
33pub mod meters;
34#[cfg(feature = "otel")]
35pub mod otel;
36pub mod profile_guide;
37pub mod recall_layer;
38pub mod receipt;
39pub mod registry;
40pub mod seal;
41pub use acceptance::{Acceptance, FilesExist, NonEmptyAnswer, Verdict};
42pub use goal::{Goal, GoalStore, Phase, PhaseStatus};
43pub use receipt::{Receipt, ReceiptBuilder};
44pub use seal::{SealBreach, SealSet};
45/// The token `AgentLoop::with_cancellation` takes, re-exported so a caller can
46/// cancel a run without depending on `tokio-util` directly.
47pub use tokio_util::sync::CancellationToken;
48pub mod replay;
49pub mod subagent;
50pub mod telemetry;
51pub mod timeline;
52pub mod trajectory;
53pub use trajectory::{
54    GoldenDiff, Report, Rule, RuleSet, Step, Trajectory, TrajectoryCheck, Violation,
55};
56
57pub use learning::*;
58pub use memory_layer::*;
59pub mod boundary_guide;
60pub use boundary_guide::*;
61pub mod events;
62pub use events::{HostEvent, NoticeGuide};
63pub use profile_guide::*;
64pub use recall_layer::*;
65pub use registry::*;
66pub use replay::*;
67pub use subagent::*;
68pub use telemetry::*;
69
70use crate::compactor::{CALIBRATION_KEY, DefaultCompactor};
71use crate::hooks::HookBus;
72use harness_core::{
73    Action, Block, CompactionStage, Compactor, Context, Event, Guide, HarnessError, HookOutcome,
74    Model, ModelDelta, ModelOutput, ResponseFormat, Sensor, SessionSource, SignalSet, Stage,
75    StopReason, Task, ToolCall, ToolResult, Turn, TurnRole, Usage, World,
76};
77use std::collections::HashMap;
78use std::sync::Arc;
79use std::time::Duration;
80use tracing::Instrument;
81use tracing::field::Empty;
82
83/// What a finished model call leaves behind: fields on its `chat` span, and
84/// its duration and tokens as metrics.
85fn finish_chat(
86    span: &tracing::Span,
87    info: &harness_core::ModelInfo,
88    started: std::time::Instant,
89    result: Option<Result<&ModelOutput, String>>,
90) {
91    let end = match &result {
92        Some(Ok(out)) => {
93            span.record("gen_ai.usage.input_tokens", out.usage.input_tokens)
94                .record("gen_ai.usage.output_tokens", out.usage.output_tokens)
95                .record(
96                    "gen_ai.usage.cached_input_tokens",
97                    out.usage.cached_input_tokens,
98                )
99                .record(
100                    "gen_ai.response.finish_reasons",
101                    format!("{:?}", out.stop_reason),
102                )
103                .record("tool_calls", out.tool_calls.len());
104            meters::ModelCallEnd::Done(&out.usage)
105        }
106        Some(Err(e)) => {
107            span.record("otel.status_code", "error")
108                .record("otel.status_message", e.as_str());
109            meters::ModelCallEnd::Failed
110        }
111        None => {
112            span.record("otel.status_message", "cancelled");
113            meters::ModelCallEnd::Cancelled
114        }
115    };
116    meters::model_call(info, started.elapsed(), end);
117}
118
119/// A tool call's result and when it ran, by the World clock — the figures
120/// behind [`Event::ToolTimed`].
121struct Dispatched {
122    result: ToolResult,
123    started_ms: i64,
124    finished_ms: i64,
125}
126
127/// The span one model call runs in. Named `chat {model}` for OTLP backends,
128/// which group by span name; fields per the GenAI conventions.
129fn chat_span(info: &harness_core::ModelInfo) -> tracing::Span {
130    tracing::info_span!(
131        target: "harness.telemetry",
132        "chat",
133        "otel.name" = %format!("chat {}", info.model),
134        "otel.kind" = "client",
135        "otel.status_code" = Empty,
136        "otel.status_message" = Empty,
137        "gen_ai.operation.name" = "chat",
138        "gen_ai.provider.name" = %info.provider,
139        "gen_ai.request.model" = %info.model,
140        "gen_ai.usage.input_tokens" = Empty,
141        "gen_ai.usage.output_tokens" = Empty,
142        "gen_ai.usage.cached_input_tokens" = Empty,
143        "gen_ai.response.finish_reasons" = Empty,
144        tool_calls = Empty,
145    )
146}
147
148/// Governs the loop's stuck-detector. When the model repeats the *same* tool
149/// call (name + args) round after round without making progress, the loop first
150/// nudges it to change approach, then terminates cleanly with [`Outcome::Stuck`]
151/// rather than burning the rest of the budget spinning on a loop.
152///
153/// Enabled by default with conservative thresholds — the calls must be
154/// *byte-identical*, so genuine "read the same file twice" work never trips it.
155#[derive(Debug, Clone)]
156pub struct StuckPolicy {
157    pub enabled: bool,
158    /// Consecutive identical tool-call rounds before injecting a "you are
159    /// repeating yourself, change your approach" feedback signal.
160    pub nudge_after: u32,
161    /// Consecutive identical rounds before terminating with [`Outcome::Stuck`].
162    pub abort_after: u32,
163}
164
165impl Default for StuckPolicy {
166    fn default() -> Self {
167        Self {
168            enabled: true,
169            nudge_after: 3,
170            abort_after: 6,
171        }
172    }
173}
174
175/// A second stuck signal, orthogonal to [`StuckPolicy`]: the model calls *one*
176/// tool round after round — a different argument every time, so nothing ever
177/// repeats — and never moves on to anything else.
178///
179/// [`StuckPolicy`] cannot see this and must not be changed so that it can. It
180/// keys on *byte-identical consecutive* rounds precisely so that genuine "read
181/// the same file twice" work never trips it, and `graph_find("Xen")` followed
182/// by `graph_find("KVM")` is correctly not a repeat — the request changed. Two
183/// identical calls in a row and one tool worked for twenty rounds are different
184/// shapes, and want different thresholds and different reasons.
185///
186/// Measured on a real run: asked which platforms a product integrates with, an
187/// agent that could not retrieve the anchor entity began guessing candidates
188/// and looking them up one at a time — `graph_find("Nomad")`,
189/// `graph_find("Docker")`, `graph_find("VMware")`, `graph_find("Xen")`,
190/// `graph_find("KVM")` — twelve calls to one tool across twenty rounds, each
191/// with a different argument, none of them useful. Every individual call looked
192/// like progress. The *shape* did not, and the shape is something the loop can
193/// see without knowing anything about what `graph_find` means.
194///
195/// **Off by default, and it has to be.** The predicate is "one tool, many
196/// rounds, nothing else", and there is a large class of healthy agents whose
197/// every round is one tool: give an agent a shell and nothing else and
198/// `run_shell` is the only name it will ever emit, thirty rounds running,
199/// legitimately. No threshold rescues that — the false positive is unbounded in
200/// N, not merely rare — so a default-on version of this guard would terminate
201/// working agents, which is worse than the problem it fixes. A host that knows
202/// its agent has several tools and is meant to use them can switch it on;
203/// nobody else pays anything for its existence.
204#[derive(Debug, Clone)]
205pub struct MonotonyPolicy {
206    /// Off by default. See the type docs for why no default-on threshold is
207    /// safe for this predicate.
208    pub enabled: bool,
209    /// Consecutive single-tool rounds before injecting a "you are working one
210    /// tool and nothing else" feedback signal.
211    ///
212    /// 8, argued rather than rounded. The honest single-tool runs are surveys —
213    /// read five files, grep four paths — and a survey ends by using a
214    /// *different* tool, which resets the count; reaching eight rounds of one
215    /// name with nothing else touched is already past what surveying does. The
216    /// cost of being wrong here is one sentence of feedback, not a terminated
217    /// run, which is why the nudge can sit this close to ordinary work. This is
218    /// also the half of the policy that does the work: in the measured case a
219    /// nudge at round eight arrives with two thirds of the budget unspent.
220    pub nudge_after: u32,
221    /// Consecutive single-tool rounds before terminating with [`Outcome::Stuck`].
222    ///
223    /// 16 — twice the nudge, mirroring [`StuckPolicy`]'s own 3→6 ratio, and
224    /// 2.6× its abort so the two can never race: a byte-identical spiral is
225    /// always caught by the older policy first, under its own reason. Deliberately
226    /// generous, because this end of the policy is fatal and its only job is to
227    /// be a backstop for budgets long enough that the nudge was ignored.
228    pub abort_after: u32,
229}
230
231impl Default for MonotonyPolicy {
232    fn default() -> Self {
233        Self {
234            enabled: false,
235            nudge_after: 8,
236            abort_after: 16,
237        }
238    }
239}
240
241/// A ceiling on how much of one tool result reaches the context.
242///
243/// A single call can return more than the whole conversation: a lock file, a
244/// `SELECT *`, an MCP tool the framework does not control. Measured on a real
245/// run, "search these files for a word" cost 53,487 input tokens because one
246/// `read_file` returned a lock file — the model then paid for it on every
247/// subsequent turn, and compaction started throwing away real history to make
248/// room. A per-result ceiling is the only place to stop that: the tools cannot
249/// all be trusted (third-party MCP), and the compactor only runs after the
250/// damage is in the context.
251#[derive(Debug, Clone)]
252pub struct ToolResultPolicy {
253    /// Max serialized bytes of a single tool result. `None` disables the guard.
254    /// Default ~24 KiB — roughly 6k tokens of English, generous for a file page
255    /// or a query result, far below what blows a window.
256    pub max_bytes: Option<usize>,
257    /// Replace the payload of a read-only call that exactly repeats an earlier
258    /// one in the same run, when nothing has modified the world in between.
259    ///
260    /// [`StuckPolicy`] only sees *consecutive* identical rounds. Reading a file
261    /// at iteration 1 and again at iteration 5 is not that, and looks like
262    /// progress — but the same bytes land in the context twice and the model
263    /// learns nothing the second time. Measured on a real run, model wait was
264    /// 36.7s against 3ms of tool execution: a repeat costs context, not time,
265    /// so what is suppressed is the payload, not the call.
266    ///
267    /// Only `ToolRisk::ReadOnly` qualifies (`Network` is a separate risk, and an
268    /// external endpoint may answer differently), and any non-read-only call
269    /// clears the record — after a write, re-reading is the correct move.
270    ///
271    /// **Off by default, on the evidence.** Measured on the completion
272    /// benchmark: ceilings alone solved 6/6 tasks for 160k effective tokens;
273    /// adding repeat-suppression cut that to 32k — and lost a task. An agent
274    /// working through a file larger than one page re-reads it because it cannot
275    /// hold it, gets told it already has the answer, and does not: the content
276    /// was paged away. Five times cheaper is not worth a task a framework could
277    /// otherwise do, so this is opt-in for callers who would rather have the
278    /// tokens. (Suppressing from the *third* identical call rather than the
279    /// second would likely keep most of the saving without the failure — it
280    /// needs measuring before it becomes the default.)
281    pub dedupe_repeats: bool,
282    /// When a result exceeds `max_bytes`, save the *full* payload to a file
283    /// under `.harness/spill/` in the workspace and inline a bounded preview
284    /// plus the path, instead of cutting the tail off and throwing it away.
285    ///
286    /// Truncation destroys information: the model is told "narrow your
287    /// request", but the bytes it needed may be exactly the ones dropped, and
288    /// the only recovery is re-running the call to be truncated again.
289    /// Measured on the completion benchmark, that loop is visible as a single
290    /// task paying 184k input tokens. Spilling keeps the ceiling — the context
291    /// gets a preview, never the flood — while the whole result stays
292    /// retrievable through the file tools the agent already has (`read_file`
293    /// with offset/limit, `grep` on the spill path), because the spill lives
294    /// inside the workspace jail. Borrowed from DeepSeek Harness's `spill`
295    /// family (preview + retrieval locator), which is the same judgement.
296    ///
297    /// Costs nothing until it fires: the write happens only on the oversized
298    /// path, which the default ceiling makes rare. When the write fails (e.g.
299    /// read-only workspace) the guard falls back to plain truncation.
300    pub spill: bool,
301}
302
303impl Default for ToolResultPolicy {
304    fn default() -> Self {
305        Self {
306            max_bytes: Some(24 * 1024),
307            dedupe_repeats: false,
308            spill: true,
309        }
310    }
311}
312
313/// Governs *when* and *how far* the loop compacts context. Hysteresis: only
314/// start compacting once usage crosses `high_water`, and stop as soon as it's
315/// back under `target` — instead of running every stage above a threshold on
316/// every turn. This avoids over-compacting (needlessly reaching the lossy,
317/// main-model `AutoCompact` stage) and, because compaction rewrites history and
318/// invalidates the provider prefix cache, avoids nibbling the context every
319/// single turn.
320#[derive(Debug, Clone)]
321pub struct CompactPolicy {
322    /// Start compacting when `used/window` exceeds this. Default 0.75.
323    pub high_water: f32,
324    /// Stop as soon as `used/window` is back at/under this. Default 0.55.
325    pub target: f32,
326}
327
328impl Default for CompactPolicy {
329    fn default() -> Self {
330        Self {
331            high_water: 0.75,
332            target: 0.55,
333        }
334    }
335}
336
337/// Inline preview size for a spilled result. Deliberately smaller than the
338/// ceiling: the point of spilling is that the context gets a *glimpse* and a
339/// path, not four-fifths of the flood.
340const SPILL_PREVIEW_BYTES: usize = 4 * 1024;
341
342/// Told to the model when the step budget ran out and the loop stripped its
343/// tools. See `force_final_synthesis`.
344const BUDGET_SYNTHESIS_PROMPT: &str = "[system: budget exhausted] \
345    You have run out of budget for tool calls. Write your final answer \
346    NOW using only the tool results already in this conversation. Do not \
347    request more tools. Mark facts you could not verify as UNKNOWN. \
348    Include source URLs for every claim that is not UNKNOWN.";
349
350/// Told to the model when [`MonotonyPolicy`] stopped the run. Deliberately
351/// names the shape it was caught in: the failure mode this ends is a model
352/// guessing arguments to one tool, and such a model has usually *found*
353/// something it never got round to reporting. "Say what you could not
354/// determine" is the instruction it needs; "mark it UNKNOWN" is the same
355/// instruction the budget prompt gives for the same reason.
356const MONOTONY_SYNTHESIS_PROMPT: &str = "[system: stopped — no progress] \
357    You have called the same tool many rounds in a row without using any other \
358    tool, so no further tool calls will be granted. Write your final answer NOW \
359    using only the tool results already in this conversation. Do not request \
360    more tools. State plainly which parts you could not determine instead of \
361    guessing at them.";
362
363/// First `n` bytes of `s`, cut on a char boundary.
364fn head_of(s: &str, n: usize) -> &str {
365    let mut end = n.min(s.len());
366    while end > 0 && !s.is_char_boundary(end) {
367        end -= 1;
368    }
369    &s[..end]
370}
371
372/// The string field that dominates an oversized result, if one does.
373///
374/// Most oversized results are one big string in a small envelope — a file
375/// body, a command's stdout — and the right spill for those is the *raw text*:
376/// multi-line, so `read_file`'s line paging and `grep`'s line matching work on
377/// it. Spilling the serialized JSON instead would fold the whole payload onto
378/// one escaped line that line-oriented tools can neither page nor match
379/// (`read_file` pages by line; a 68 KB single-line file is unreachable past
380/// the first 16 KB). Returns the dotted path and the string when one field is
381/// ≥ 80% of the serialized size.
382fn dominant_string(v: &serde_json::Value, total: usize) -> Option<(String, &str)> {
383    fn walk<'a>(v: &'a serde_json::Value, path: &str, best: &mut Option<(String, &'a str)>) {
384        match v {
385            serde_json::Value::String(s) => {
386                if best.as_ref().is_none_or(|(_, b)| s.len() > b.len()) {
387                    *best = Some((path.to_string(), s.as_str()));
388                }
389            }
390            serde_json::Value::Object(m) => {
391                for (k, x) in m {
392                    let p = if path.is_empty() {
393                        k.clone()
394                    } else {
395                        format!("{path}.{k}")
396                    };
397                    walk(x, &p, best);
398                }
399            }
400            serde_json::Value::Array(a) => {
401                for (i, x) in a.iter().enumerate() {
402                    walk(x, &format!("{path}[{i}]"), best);
403                }
404            }
405            _ => {}
406        }
407    }
408    let mut best = None;
409    walk(v, "", &mut best);
410    best.filter(|(_, s)| s.len() * 5 >= total * 4)
411}
412
413/// Replace the value at a `dominant_string` dotted path with `with`.
414fn replace_at(v: &mut serde_json::Value, path: &str, with: serde_json::Value) {
415    let mut cur = v;
416    let mut rest = path;
417    loop {
418        // Next segment: `key`, `key[i]`, or a bare `[i]`.
419        let (seg, tail) = match rest.find('.') {
420            Some(dot) => (&rest[..dot], &rest[dot + 1..]),
421            None => (rest, ""),
422        };
423        let (key, idx) = match seg.find('[') {
424            Some(b) => (&seg[..b], seg[b + 1..seg.len() - 1].parse::<usize>().ok()),
425            None => (seg, None),
426        };
427        if !key.is_empty() {
428            match cur.get_mut(key) {
429                Some(next) => cur = next,
430                None => return,
431            }
432        }
433        if let Some(i) = idx {
434            match cur.get_mut(i) {
435                Some(next) => cur = next,
436                None => return,
437            }
438        }
439        if tail.is_empty() {
440            *cur = with;
441            return;
442        }
443        rest = tail;
444    }
445}
446
447/// Persist an oversized result under `.harness/spill/` in the workspace and
448/// build the inline marker. `None` on any IO failure — the caller falls back
449/// to truncation, because a guard that can error a run to protect a context
450/// window has its priorities backwards.
451fn spill_oversized(
452    action: &Action,
453    content: &serde_json::Value,
454    serialized: &str,
455    root: &std::path::Path,
456) -> Option<serde_json::Value> {
457    let dir = root.join(".harness").join("spill");
458    std::fs::create_dir_all(&dir).ok()?;
459    let id: String = action
460        .call_id
461        .chars()
462        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
463        .take(48)
464        .collect();
465    let id = if id.is_empty() { "call".into() } else { id };
466
467    let (rel, preview, meta) = match dominant_string(content, serialized.len()) {
468        // One big string in a small envelope: spill the raw text, keep the
469        // envelope inline with the big field swapped for a pointer.
470        Some((field, text)) => {
471            let rel = format!(".harness/spill/{id}-{}.txt", action.tool);
472            std::fs::write(root.join(&rel), text).ok()?;
473            let mut meta = content.clone();
474            replace_at(
475                &mut meta,
476                &field,
477                serde_json::Value::String(format!("[{} bytes spilled to {rel}]", text.len())),
478            );
479            (
480                rel,
481                head_of(text, SPILL_PREVIEW_BYTES).to_string(),
482                Some(meta),
483            )
484        }
485        // Structured payload (e.g. a long match list): spill pretty-printed,
486        // one element per line, so line-oriented retrieval still works.
487        None => {
488            let rel = format!(".harness/spill/{id}-{}.json", action.tool);
489            let pretty =
490                serde_json::to_string_pretty(content).unwrap_or_else(|_| serialized.to_string());
491            std::fs::write(root.join(&rel), &pretty).ok()?;
492            (rel, head_of(&pretty, SPILL_PREVIEW_BYTES).to_string(), None)
493        }
494    };
495    tracing::warn!(
496        target: "harness.telemetry",
497        event = "tool.result.spilled",
498        "gen_ai.tool.name" = %action.tool,
499        bytes = serialized.len(),
500        path = %rel,
501    );
502    let mut marker = serde_json::json!({
503        "spilled": true,
504        "tool": action.tool,
505        "bytes_total": serialized.len(),
506        "path": rel,
507        "preview": preview,
508        "note": format!(
509            "This result was {} bytes — too large to inline, so the FULL content was \
510             saved to '{rel}' (workspace-relative). Nothing was lost. Retrieve exactly \
511             the part you need: grep(path=\"{rel}\", pattern=...) or \
512             read_file(path=\"{rel}\", offset=..., limit=...). Do not repeat the \
513             original call — it will spill again.",
514            serialized.len()
515        ),
516    });
517    // The envelope metadata (paths, flags) rides along when it is small; a
518    // pathological envelope that is itself oversized is dropped, not inlined.
519    if let Some(meta) = meta
520        && meta.to_string().len() <= SPILL_PREVIEW_BYTES
521    {
522        marker["meta"] = meta;
523    }
524    Some(marker)
525}
526
527/// A stable fingerprint of a round's tool calls (names + args, ignoring the
528/// volatile call id). Two rounds with the same fingerprint asked for the exact
529/// same actions — the signal the stuck-detector keys on.
530fn tool_call_fingerprint(calls: &[ToolCall]) -> String {
531    calls
532        .iter()
533        .map(|c| format!("{}({})", c.name, c.args))
534        .collect::<Vec<_>>()
535        .join("|")
536}
537
538/// The one tool a round asked for, when the whole round asked for exactly one
539/// *name*. `None` when the round mixed names — reaching for a second tool is,
540/// on its own, evidence the model is still moving, and resets
541/// [`MonotonyPolicy`]'s count.
542///
543/// Several parallel calls to the same tool count as one round of that tool:
544/// reading four files in one round is efficient work, not monotony, and the
545/// policy's threshold is in *rounds* precisely so that batching is never
546/// punished.
547fn sole_tool(calls: &[ToolCall]) -> Option<&str> {
548    let first = calls.first()?.name.as_str();
549    calls.iter().all(|c| c.name == first).then_some(first)
550}
551
552/// Cheap identity for one tool result, for the stuck detector's "did anything
553/// change" test. Not a checksum anyone depends on — only equality between two
554/// consecutive rounds of the same process matters.
555fn result_digest(tool: &str, content: &serde_json::Value) -> u64 {
556    use std::hash::{Hash, Hasher};
557    let mut h = std::collections::hash_map::DefaultHasher::new();
558    tool.hash(&mut h);
559    content.to_string().hash(&mut h);
560    h.finish()
561}
562
563/// Where a run finished. Each variant is `#[non_exhaustive]` so new *fields*
564/// don't break downstream matches — always include `..` when destructuring.
565#[derive(Debug, Clone)]
566pub enum Outcome {
567    /// Model returned text with no tool calls (natural end).
568    #[non_exhaustive]
569    Done {
570        text: Option<String>,
571        iters: u32,
572        tools_called: u32,
573        usage: harness_core::Usage,
574        /// What the acceptance checks said. `None` means nothing was asked —
575        /// so "the model stopped" is all this outcome claims.
576        verified: Option<Verdict>,
577        /// The sealed contract as it stood before the model's first turn.
578        ///
579        /// Carried out of the run because a receipt has to say *what* was
580        /// measured, not only that the measurement held. Empty when nothing
581        /// was sealed.
582        contract: crate::seal::SealSet,
583        /// Set when a sealed acceptance contract changed during the run.
584        ///
585        /// Distinct from a plain failed `verified` because the two mean
586        /// different things to a caller: a failed check is work not finished,
587        /// this is the measuring instrument having been moved. A host may want
588        /// to fail a build on the first and page someone on the second.
589        seal_breach: Option<String>,
590    },
591    /// Policy budget exhausted before the model stopped requesting tools.
592    /// Carries everything we know so the caller can recover partial work
593    /// (saved notes, files written by tools, the last assistant text, etc.)
594    /// instead of seeing a single bare "budget out" string.
595    #[non_exhaustive]
596    BudgetExhausted {
597        iters: u32,
598        last_text: Option<String>,
599        tools_called: u32,
600        usage: harness_core::Usage,
601        /// True when `Task::deadline` stopped the run rather than `max_iters`.
602        /// Both end the same way — a forced final answer — but "ran out of
603        /// time" and "ran out of steps" call for different responses from the
604        /// caller, and an unattended long run only ever hits the first.
605        deadline_reached: bool,
606    },
607    /// The agent got stuck and the loop terminated early to save the rest of
608    /// the budget. Carries partial work (last text, files already written by
609    /// tools) like `BudgetExhausted`.
610    ///
611    /// Two independent detectors end here, and `reason` says which: it repeated
612    /// the *same* tool call for `StuckPolicy::abort_after` rounds without
613    /// progress, or it worked a *single* tool for `MonotonyPolicy::abort_after`
614    /// rounds without touching anything else. Only the second forces a final
615    /// synthesis before returning — see the abort site for why.
616    #[non_exhaustive]
617    Stuck {
618        /// Human-readable reason, e.g. "repeated `read_file(...)` 6× without progress"
619        /// or "called `graph_find` for 16 consecutive rounds without using any
620        /// other tool".
621        reason: String,
622        /// How many consecutive rounds the detector counted before aborting.
623        repeated: u32,
624        iters: u32,
625        last_text: Option<String>,
626        tools_called: u32,
627        usage: harness_core::Usage,
628    },
629    /// The caller stopped the run through [`AgentLoop::with_cancellation`]
630    /// before the model reached a natural end. Carries partial work like
631    /// `Stuck` does, because the user who pressed Ctrl-C still wants what was
632    /// done. The loop makes **no** further model call after this — not even
633    /// the forced final synthesis the other early exits perform.
634    ///
635    /// A tool that was mid-flight when the token fired may still finish its
636    /// side effects — a file write on a blocking thread completes, a child
637    /// process keeps running unless its runner kills it on drop — but its
638    /// result is discarded before it reaches history. The dispatch is still
639    /// counted in `tools_called` — the telemetry `run.end` line reconciles
640    /// against that number.
641    #[non_exhaustive]
642    Cancelled {
643        /// Iterations completed before the cancel. `0` means the token was
644        /// already cancelled on entry.
645        iters: u32,
646        last_text: Option<String>,
647        tools_called: u32,
648        usage: harness_core::Usage,
649    },
650}
651
652/// The agent loop.
653pub struct AgentLoop<M: Model> {
654    pub model: M,
655    pub tools: ToolRegistry,
656    pub guides: Vec<Arc<dyn Guide>>,
657    pub sensors: Vec<Arc<dyn Sensor>>,
658    pub hooks: HookBus,
659    pub compactor: Arc<dyn Compactor>,
660    /// A deadline on each individual tool call. One hung call — a network tool
661    /// on a dead endpoint, a shell command waiting on stdin — otherwise takes
662    /// the whole run down with it, and the host's only recourse is a run-level
663    /// timeout that throws away every turn of finished work (measured on the
664    /// completion benchmark: a run that had already done the job was billed as
665    /// a 0-token timeout). A per-call deadline converts the hang into an error
666    /// *result* the model sees and can route around. `None` disables. The
667    /// default is generous — 120s covers a slow build — because a false
668    /// deadline on a legitimately long tool is worse than a late one.
669    pub tool_timeout: Option<Duration>,
670    /// Default response format applied to every run unless overridden by
671    /// `run_typed`. See [`ResponseFormat`].
672    pub response_format: ResponseFormat,
673    /// When `true`, the loop drives each model turn via `Model::stream()`
674    /// instead of `complete()`, firing `Event::ModelTokenDelta` for each
675    /// text fragment. Tool-call deltas are still assembled inside the loop;
676    /// only the terminal `ModelOutput` shape is observable downstream.
677    pub streaming: bool,
678    /// Stops the run from outside. Checked at the top of every iteration and
679    /// raced against the model step and every tool dispatch, so a cancel
680    /// lands within one await point rather than at the next iteration
681    /// boundary. Defaults to a token nobody holds, which never fires.
682    pub cancel: CancellationToken,
683    /// Optional cross-session recall store. When set, the loop captures every
684    /// turn and the `session_search` tool is registered. See `with_recall`.
685    pub recall: Option<Arc<dyn harness_core::RecallStore>>,
686    /// When true (and `recall` is set), a `RecallGuide` auto-injects top-k
687    /// past context at session start.
688    pub recall_auto_inject: bool,
689    pub learning: Option<LearningConfig>,
690    /// Loop-detection policy. Enabled by default — see [`StuckPolicy`].
691    pub stuck: StuckPolicy,
692    /// Second, independent loop-detection signal: one tool worked round after
693    /// round with nothing else touched. Off by default — see [`MonotonyPolicy`].
694    pub monotony: MonotonyPolicy,
695    /// Ceiling on context tokens, overriding the model's own window. `None`
696    /// (default) sizes the budget to `ModelInfo::context_window`.
697    pub max_input_tokens: Option<u32>,
698    /// Context-compaction hysteresis. See [`CompactPolicy`].
699    pub compaction: CompactPolicy,
700    /// Ceiling on a single tool result. See [`ToolResultPolicy`].
701    pub tool_results: ToolResultPolicy,
702    /// Conditions the run must satisfy before the loop reports success. The
703    /// model stopping is evidence it *believes* it is finished; these say
704    /// whether it is. See [`acceptance`].
705    pub acceptance: Vec<Arc<dyn Acceptance>>,
706    /// How many times a failed acceptance is handed back to the model before
707    /// the loop gives up and reports what there is. One is usually enough: a
708    /// model that ignores the first correction rarely takes the second.
709    pub acceptance_retries: u32,
710    /// System instruction injected into every run's `Context.system` (unless the
711    /// built context already carries its own). Set via [`with_system`](Self::with_system).
712    pub system: Vec<Block>,
713    /// Named auxiliary models for side tasks — compaction, memory synthesis,
714    /// judging, subagents — so the main conversation stays on one model (and
715    /// keeps its provider prompt-cache prefix intact) while cheap or specialist
716    /// work goes elsewhere. Populated via [`with_model_role`](Self::with_model_role),
717    /// read via [`model_for`](Self::model_for). An unregistered role means
718    /// "use the main model" — components fall back rather than fail.
719    pub model_roles: std::collections::HashMap<String, Arc<dyn Model>>,
720    /// True once the host installed its own compactor via
721    /// [`with_compactor`](Self::with_compactor). Guards the `"compactor"`
722    /// model-role convenience from overwriting an explicit choice.
723    pub compactor_custom: bool,
724}
725
726impl AgentLoop<harness_core::DynModel> {
727    /// Build a loop from a boxed model — what every model factory hands back
728    /// (`ApiKind::build`, a router, anything stored behind a trait object).
729    ///
730    /// `Arc<dyn Model>` deliberately does not implement `Model` (see
731    /// [`DynModel`](harness_core::DynModel) for why), so `AgentLoop::new` cannot
732    /// take one. Without this constructor every caller writes the wrapper
733    /// themselves, and the first thing a new user meets is a trait-bound error
734    /// naming a type they have never heard of.
735    ///
736    /// ```ignore
737    /// let model = ApiKind::OpenAI.build(base_url, model_id, key);
738    /// let agent = AgentLoop::boxed(model).with_tool(Arc::new(ReadFile));
739    /// ```
740    pub fn boxed(model: Arc<dyn Model>) -> Self {
741        Self::new(harness_core::DynModel(model))
742    }
743}
744
745impl<M: Model> AgentLoop<M> {
746    pub fn new(model: M) -> Self {
747        Self {
748            model,
749            tools: ToolRegistry::new(),
750            guides: Vec::new(),
751            sensors: Vec::new(),
752            hooks: HookBus::new(),
753            compactor: Arc::new(DefaultCompactor::new()),
754            tool_timeout: Some(Duration::from_secs(120)),
755            response_format: ResponseFormat::Free,
756            streaming: false,
757            cancel: CancellationToken::new(),
758            recall: None,
759            recall_auto_inject: false,
760            learning: None,
761            stuck: StuckPolicy::default(),
762            monotony: MonotonyPolicy::default(),
763            max_input_tokens: None,
764            compaction: CompactPolicy::default(),
765            // On by default, because the failure it catches is invisible: a
766            // turn that produced nothing is reported as a turn that finished.
767            tool_results: ToolResultPolicy::default(),
768            acceptance: vec![Arc::new(acceptance::NonEmptyAnswer)],
769            acceptance_retries: 1,
770            system: Vec::new(),
771            model_roles: std::collections::HashMap::new(),
772            compactor_custom: false,
773        }
774    }
775
776    /// Register an auxiliary model under a role name — the loop's seam for
777    /// "side tasks don't have to run on the main model".
778    ///
779    /// The main conversation stays pinned to one model, which keeps its
780    /// provider prompt-cache prefix byte-stable; compaction summaries, memory
781    /// synthesis, judging, and subagents can go to a cheaper or specialist
782    /// model instead. Components read roles via [`model_for`](Self::model_for)
783    /// and fall back to the main model when a role is unregistered.
784    ///
785    /// One role is wired automatically: registering `"compactor"` upgrades the
786    /// default structural compactor to a [`ModelBackedCompactor`] on that
787    /// model — unless the host already installed its own via
788    /// [`with_compactor`](Self::with_compactor), which always wins regardless
789    /// of call order.
790    ///
791    /// ```ignore
792    /// let agent = AgentLoop::boxed(main)
793    ///     .with_model_role("compactor", cheap.clone())
794    ///     .with_model_role("judge", strong);
795    /// ```
796    pub fn with_model_role(mut self, role: impl Into<String>, model: Arc<dyn Model>) -> Self {
797        let role = role.into();
798        if role == "compactor" && !self.compactor_custom {
799            self.compactor = Arc::new(crate::compactor::ModelBackedCompactor::new(model.clone()));
800        }
801        self.model_roles.insert(role, model);
802        self
803    }
804
805    /// Look up an auxiliary model by role. `None` means "no model registered
806    /// for this role — use the main model"; callers fall back rather than fail,
807    /// so wiring stays optional everywhere.
808    pub fn model_for(&self, role: &str) -> Option<Arc<dyn Model>> {
809        self.model_roles.get(role).cloned()
810    }
811
812    /// Set a system instruction applied to every run (into `Context.system`) —
813    /// e.g. "answer only via the governed tools; never claim you can't access
814    /// data; never invent numbers". This is the first-class seam for a system
815    /// prompt; small local models in particular need it to reliably call tools
816    /// instead of refusing or hallucinating.
817    pub fn with_system(mut self, text: impl Into<String>) -> Self {
818        self.system = vec![Block::Text(text.into())];
819        self
820    }
821
822    /// Cap context tokens below the model's own window.
823    ///
824    /// Compaction fires at a fraction of this, so it is also the only way to
825    /// exercise the compaction path without first paying for a hundred
826    /// thousand tokens of real conversation — which is how "does a long run
827    /// survive being compacted" stayed untested.
828    pub fn with_max_input_tokens(mut self, n: u32) -> Self {
829        self.max_input_tokens = Some(n);
830        self
831    }
832
833    /// Override the loop-detection policy (thresholds, or disable entirely).
834    pub fn with_stuck_policy(mut self, policy: StuckPolicy) -> Self {
835        self.stuck = policy;
836        self
837    }
838
839    /// Opt in to (or retune) the single-tool monotony signal. Independent of
840    /// [`with_stuck_policy`](Self::with_stuck_policy): both detectors run, with
841    /// their own thresholds and their own `Outcome::Stuck` reason.
842    ///
843    /// ```ignore
844    /// let agent = AgentLoop::boxed(model)
845    ///     .with_monotony_policy(MonotonyPolicy { enabled: true, ..Default::default() });
846    /// ```
847    pub fn with_monotony_policy(mut self, policy: MonotonyPolicy) -> Self {
848        self.monotony = policy;
849        self
850    }
851
852    /// Override the compaction hysteresis policy. See [`CompactPolicy`].
853    /// Set the ceiling on a single tool result. See [`ToolResultPolicy`].
854    pub fn with_tool_result_policy(mut self, policy: ToolResultPolicy) -> Self {
855        self.tool_results = policy;
856        self
857    }
858
859    pub fn with_compact_policy(mut self, policy: CompactPolicy) -> Self {
860        self.compaction = policy;
861        self
862    }
863
864    /// Opt in to streaming the model's terminal turn token-by-token via
865    /// `Model::stream()`. Hooks subscribed to `Event::ModelTokenDelta` see
866    /// each fragment as it arrives; the rest of the loop is unchanged.
867    pub fn with_streaming(mut self, enable: bool) -> Self {
868        self.streaming = enable;
869        self
870    }
871
872    /// Hand the run a token the caller can cancel from anywhere.
873    ///
874    /// The token belongs to the **loop, not to one run**, and cancellation is
875    /// **one-way**: once `cancel()` has been called, every later `run` (and
876    /// every later `Session::turn`) on this loop returns `Outcome::Cancelled`
877    /// immediately, with `iters: 0`. That is right for a loop built for one
878    /// job and wrong for one that serves many turns. For per-turn cancellation
879    /// give each turn its own token — either rebuild the loop, or keep a parent
880    /// and hand out `parent.child_token()`, dropping the child when the turn
881    /// ends so the parent stays live:
882    ///
883    /// ```ignore
884    /// let token = CancellationToken::new();
885    /// let agent = AgentLoop::new(model).with_cancellation(token.clone());
886    /// // … later, from anywhere — this loop is now finished with, permanently:
887    /// token.cancel();
888    /// ```
889    ///
890    /// The field is public, so the simplest per-turn form is to assign
891    /// `loop_.cancel = fresh_token` before each run, which is what
892    /// `harness code` does.
893    ///
894    /// Cloning a `CancellationToken` shares it, so keep one and pass a clone.
895    pub fn with_cancellation(mut self, token: CancellationToken) -> Self {
896        self.cancel = token;
897        self
898    }
899
900    /// Add a condition the run must satisfy before it can report success.
901    pub fn with_acceptance(mut self, a: Arc<dyn Acceptance>) -> Self {
902        self.acceptance.push(a);
903        self
904    }
905
906    /// Replace the acceptance set outright (including the default).
907    pub fn with_acceptance_set(mut self, set: Vec<Arc<dyn Acceptance>>) -> Self {
908        self.acceptance = set;
909        self
910    }
911
912    pub fn with_acceptance_retries(mut self, n: u32) -> Self {
913        self.acceptance_retries = n;
914        self
915    }
916
917    pub fn with_tool_timeout(mut self, t: Option<Duration>) -> Self {
918        self.tool_timeout = t;
919        self
920    }
921
922    pub fn with_compactor(mut self, c: Arc<dyn Compactor>) -> Self {
923        self.compactor = c;
924        // An explicit compactor always wins over the "compactor" model-role
925        // convenience, in either call order.
926        self.compactor_custom = true;
927        self
928    }
929
930    pub fn with_tool(mut self, t: Arc<dyn harness_core::Tool>) -> Self {
931        self.tools.insert(t);
932        self
933    }
934
935    pub fn with_guide(mut self, g: Arc<dyn Guide>) -> Self {
936        self.guides.push(g);
937        self
938    }
939
940    pub fn with_sensor(mut self, s: Arc<dyn Sensor>) -> Self {
941        self.sensors.push(s);
942        self
943    }
944
945    pub fn with_hook(mut self, h: Arc<dyn harness_core::Hook>) -> Self {
946        self.hooks.register(h);
947        self
948    }
949
950    /// Pull in every `#[hook]`-registered hook.
951    pub fn with_macro_hooks(mut self) -> Self {
952        self.hooks = self.hooks.with_macro_hooks_take();
953        self
954    }
955
956    /// Enable cross-session recall: capture every turn into `store` and
957    /// register the `session_search` tool. Owner + session id are read from
958    /// `world.profile.extra["recall_owner"|"recall_session"]` at run time.
959    pub fn with_recall(mut self, store: Arc<dyn harness_core::RecallStore>) -> Self {
960        self.tools
961            .insert(Arc::new(crate::SessionSearchTool::new(store.clone())));
962        self.recall = Some(store);
963        self
964    }
965
966    /// Capture every turn into `store` **without** registering a search tool.
967    ///
968    /// Ingest and retrieval are separate concerns that [`with_recall`] happens
969    /// to bundle, and the bundling is a trap: capture only ever happens when
970    /// `self.recall` is set, so a host that wants a different search tool — one
971    /// scoped per tenant, or one that copes with a language the backend's index
972    /// does not — has no way to get the writes without also getting
973    /// `session_search`, and ends up offering the model two overlapping tools
974    /// to choose between.
975    ///
976    /// Use this, then register whichever retrieval tool suits the deployment.
977    pub fn with_recall_ingest(mut self, store: Arc<dyn harness_core::RecallStore>) -> Self {
978        self.recall = Some(store);
979        self
980    }
981
982    /// After `with_recall`, also auto-inject top-k relevant past context at
983    /// session start (off by default — tool-only is prompt-cache friendly).
984    pub fn auto_inject(mut self) -> Self {
985        self.recall_auto_inject = true;
986        self
987    }
988
989    /// Enable the self-evolving learning loop: after a session that made
990    /// `>= cfg.nudge_interval` tool calls, fork a review subagent (white-listed to
991    /// `cfg.tools`) to update skills + memory from the transcript. Best-effort.
992    pub fn with_learning_loop(mut self, cfg: LearningConfig) -> Self {
993        self.learning = Some(cfg);
994        self
995    }
996
997    /// Set the default response format for all runs through this loop. See
998    /// [`ResponseFormat`]. For typed deserialisation, prefer `run_typed::<T>()`.
999    pub fn with_response_format(mut self, fmt: ResponseFormat) -> Self {
1000        self.response_format = fmt;
1001        self
1002    }
1003
1004    /// Shortcut for `with_response_format(ResponseFormat::JsonSchema { name, schema })`.
1005    /// Accepts a raw `serde_json::Value` so callers can hand-roll the schema or
1006    /// pull it from `schemars::schema_for!(T)`.
1007    pub fn with_response_schema(self, name: impl Into<String>, schema: serde_json::Value) -> Self {
1008        self.with_response_format(ResponseFormat::JsonSchema {
1009            name: name.into(),
1010            schema,
1011        })
1012    }
1013
1014    pub async fn run(&self, task: Task, world: &mut World) -> Result<Outcome, HarnessError> {
1015        let max = harness_core::Policy::default().max_iters;
1016        self.run_with_max_iters(task, world, max).await
1017    }
1018
1019    /// Run, and hand back the evidence alongside the result.
1020    ///
1021    /// The [`Receipt`] is built here rather than by the caller because the loop
1022    /// already knows the two things a caller would otherwise have to restate —
1023    /// the task and the model — and restating them is how a receipt ends up
1024    /// describing a different run than the one that happened. `now_ms` stays a
1025    /// parameter: this crate does not read the clock, so a receipt is
1026    /// reproducible in a test.
1027    pub async fn run_receipted(
1028        &self,
1029        task: Task,
1030        world: &mut World,
1031        now_ms: i64,
1032    ) -> Result<(Outcome, Receipt), HarnessError> {
1033        let description = task.description.clone();
1034        let handle = self.model.info().handle;
1035        let outcome = self.run(task, world).await?;
1036        let receipt = ReceiptBuilder::new(description, handle, now_ms).build(&outcome);
1037        Ok((outcome, receipt))
1038    }
1039
1040    /// Advance a [`Goal`] by one phase, recording the result durably.
1041    ///
1042    /// Returns `None` when every phase is done — so a resume loop is
1043    /// `while let Some(..) = loop_.run_goal(..).await?`.
1044    ///
1045    /// The phase is marked `Running` and **saved before the model starts**, so
1046    /// a process that dies mid-run leaves a goal that says where it was rather
1047    /// than one that looks untouched. It is saved again afterwards on both
1048    /// paths. That second save on the failure path is the whole reason this
1049    /// method exists: written out by hand at each call site it is four lines,
1050    /// and the failure branch is the one that gets forgotten — which loses
1051    /// exactly the run you most wanted a record of.
1052    pub async fn run_goal(
1053        &self,
1054        goal: &mut Goal,
1055        store: &GoalStore,
1056        world: &mut World,
1057        now_ms: i64,
1058    ) -> Result<Option<(Outcome, Receipt)>, HarnessError> {
1059        let Some(i) = goal.start_current(now_ms) else {
1060            return Ok(None);
1061        };
1062        let _ = store.save(goal);
1063
1064        let task = Task {
1065            description: goal.brief(),
1066            source: None,
1067            deadline: None,
1068        };
1069        let result = self.run_receipted(task, world, now_ms).await;
1070
1071        match &result {
1072            Ok((_, receipt)) => {
1073                if receipt.passed {
1074                    goal.finish(i, receipt.summary(), now_ms);
1075                } else {
1076                    goal.fail(i, receipt.summary(), now_ms);
1077                }
1078            }
1079            // A run that errored outright still happened, and the goal has to
1080            // say so or a resume will retry it as though it were untouched.
1081            Err(e) => goal.fail(i, format!("the run errored: {e}"), now_ms),
1082        }
1083        let _ = store.save(goal);
1084
1085        result.map(Some)
1086    }
1087
1088    pub async fn run_with_max_iters(
1089        &self,
1090        task: Task,
1091        world: &mut World,
1092        max_iters: u32,
1093    ) -> Result<Outcome, HarnessError> {
1094        self.run_with_seed_history(task, Vec::new(), world, max_iters)
1095            .await
1096    }
1097
1098    /// Run the agent and deserialise the terminal reply into `T`.
1099    ///
1100    /// The schema for `T` is derived via `schemars::schema_for!(T)` and
1101    /// installed as `ResponseFormat::JsonSchema` for this run only — any
1102    /// pre-existing `self.response_format` is ignored. On success the
1103    /// returned `T` is parsed from `Outcome::Done.text` (or, on budget
1104    /// exhaustion, from `Outcome::BudgetExhausted.last_text`).
1105    ///
1106    /// Errors:
1107    /// - `HarnessError::Other` if the model returns no text at all
1108    /// - `HarnessError::Other` if `serde_json::from_str::<T>(text)` fails —
1109    ///   the original text is included in the message for debugging.
1110    pub async fn run_typed<T>(&self, task: Task, world: &mut World) -> Result<T, HarnessError>
1111    where
1112        T: serde::de::DeserializeOwned + schemars::JsonSchema + 'static,
1113    {
1114        let max = harness_core::Policy::default().max_iters;
1115        self.run_typed_with_max_iters::<T>(task, world, max).await
1116    }
1117
1118    /// Like `run_typed` but with explicit `max_iters`.
1119    pub async fn run_typed_with_max_iters<T>(
1120        &self,
1121        task: Task,
1122        world: &mut World,
1123        max_iters: u32,
1124    ) -> Result<T, HarnessError>
1125    where
1126        T: serde::de::DeserializeOwned + schemars::JsonSchema + 'static,
1127    {
1128        let schema_root = schemars::schema_for!(T);
1129        let schema = serde_json::to_value(&schema_root)
1130            .map_err(|e| HarnessError::Other(format!("response schema: {e}")))?;
1131        let name = std::any::type_name::<T>()
1132            .rsplit("::")
1133            .next()
1134            .unwrap_or("response")
1135            .to_string();
1136        let fmt = ResponseFormat::JsonSchema { name, schema };
1137        let outcome = self
1138            .run_with_response_format(task, world, max_iters, fmt)
1139            .await?;
1140        let text = match outcome {
1141            Outcome::Done { text: Some(t), .. }
1142            | Outcome::BudgetExhausted {
1143                last_text: Some(t), ..
1144            }
1145            | Outcome::Stuck {
1146                last_text: Some(t), ..
1147            }
1148            | Outcome::Cancelled {
1149                last_text: Some(t), ..
1150            } => t,
1151            Outcome::Done { text: None, .. } => {
1152                return Err(HarnessError::Other(
1153                    "run_typed: model returned no text".into(),
1154                ));
1155            }
1156            Outcome::Stuck {
1157                last_text: None, ..
1158            } => {
1159                return Err(HarnessError::Other(
1160                    "run_typed: agent stuck with no text".into(),
1161                ));
1162            }
1163            Outcome::BudgetExhausted {
1164                last_text: None, ..
1165            } => {
1166                return Err(HarnessError::Other(
1167                    "run_typed: budget exhausted with no text".into(),
1168                ));
1169            }
1170            Outcome::Cancelled {
1171                last_text: None, ..
1172            } => {
1173                return Err(HarnessError::Other(
1174                    "run_typed: run cancelled with no text".into(),
1175                ));
1176            }
1177        };
1178        serde_json::from_str::<T>(&text).map_err(|e| {
1179            HarnessError::Other(format!(
1180                "run_typed: decode {} failed: {e} — raw text was: {text}",
1181                std::any::type_name::<T>()
1182            ))
1183        })
1184    }
1185
1186    /// Run with a one-off `ResponseFormat` override (doesn't touch `self`).
1187    pub async fn run_with_response_format(
1188        &self,
1189        task: Task,
1190        world: &mut World,
1191        max_iters: u32,
1192        fmt: ResponseFormat,
1193    ) -> Result<Outcome, HarnessError> {
1194        // Borrow checker won't let us swap `self.response_format` because
1195        // `self` is `&`. Easiest workaround: hand-roll the same setup that
1196        // `run_with_seed_history` does, but with our `fmt`. We do this by
1197        // calling through a private helper.
1198        self.run_with_seed_history_and_format(task, Vec::new(), world, max_iters, Some(fmt))
1199            .await
1200    }
1201
1202    async fn run_with_seed_history_and_format(
1203        &self,
1204        task: Task,
1205        seed: Vec<Turn>,
1206        world: &mut World,
1207        max_iters: u32,
1208        fmt_override: Option<ResponseFormat>,
1209    ) -> Result<Outcome, HarnessError> {
1210        let mut ctx = Context::new(task);
1211        ctx.policy.max_iters = max_iters;
1212        ctx.tools = self.tools.schemas();
1213        ctx.history = seed;
1214        ctx.response_format = fmt_override.unwrap_or_else(|| self.response_format.clone());
1215        self.run_built_context(ctx, world).await
1216    }
1217
1218    /// Like `run_with_max_iters` but seeds `ctx.history` with `seed` **before**
1219    /// the current user task is appended. Use this for multi-turn REPLs so
1220    /// prior conversation lives in `ctx.history` (where the Compactor can see
1221    /// it) instead of being concatenated into `task.description` (where it
1222    /// previously bypassed compaction entirely — see audit #2).
1223    pub async fn run_with_seed_history(
1224        &self,
1225        task: Task,
1226        seed: Vec<Turn>,
1227        world: &mut World,
1228        max_iters: u32,
1229    ) -> Result<Outcome, HarnessError> {
1230        self.run_with_seed_and_metadata(task, seed, Default::default(), world, max_iters)
1231            .await
1232    }
1233
1234    /// Like [`run_with_seed_history`](Self::run_with_seed_history) but also seeds
1235    /// `ctx.metadata` with per-request key/values. Hooks and a
1236    /// [`ModelRouter`](harness_models::ModelRouter) read this map — e.g.
1237    /// `audit.actor` / `audit.session` for the audit trail, or
1238    /// `router.keep_local` to pin a request to the local model. This is the
1239    /// entry point a serving layer uses to pass caller identity and routing
1240    /// flags into a single, shared, reused loop.
1241    pub async fn run_with_seed_and_metadata(
1242        &self,
1243        task: Task,
1244        seed: Vec<Turn>,
1245        metadata: std::collections::BTreeMap<String, serde_json::Value>,
1246        world: &mut World,
1247        max_iters: u32,
1248    ) -> Result<Outcome, HarnessError> {
1249        let mut ctx = Context::new(task);
1250        ctx.policy.max_iters = max_iters;
1251        ctx.tools = self.tools.schemas();
1252        ctx.history = seed;
1253        ctx.metadata = metadata;
1254        ctx.response_format = self.response_format.clone();
1255        self.run_built_context(ctx, world).await
1256    }
1257
1258    /// Start a persistent multi-turn [`Session`]. Each `turn` re-runs the loop
1259    /// against the accumulated history with a **stable prefix** (system +
1260    /// name-sorted tool schemas), so a provider's prefix cache (e.g. DeepSeek's,
1261    /// ~10% price on cache-hit tokens) hits across turns instead of paying full
1262    /// price to re-read the same bytes every round. For maximum hit rate, keep
1263    /// your guides' output stable (put per-turn volatile context in the message,
1264    /// not a recomputed system guide).
1265    pub fn session(&self) -> Session<'_, M> {
1266        Session {
1267            loop_: self,
1268            history: Vec::new(),
1269            max_iters: harness_core::Policy::default().max_iters,
1270        }
1271    }
1272
1273    /// Inner ReAct loop on an already-prepared `Context`. Use the public
1274    /// `run*` methods unless you need to inject a non-standard `Context`
1275    /// (e.g. `run_with_response_format` does to apply a one-off
1276    /// `ResponseFormat` without mutating `self`).
1277    ///
1278    /// The run executes inside an `agent_run` span, and every model call and
1279    /// tool call inside a child span of it (`chat`, `execute_tool`). The loop
1280    /// owns these rather than a hook, because only the loop knows when a call
1281    /// really starts and ends: read-only tools are dispatched in parallel
1282    /// *before* their `PreToolUse` fires, so a hook timing them would see a
1283    /// zero-length call. Spans cost nothing without a subscriber; with an OTLP
1284    /// layer (feature `otel`) they are the trace waterfall.
1285    async fn run_built_context(
1286        &self,
1287        ctx: Context,
1288        world: &mut World,
1289    ) -> Result<Outcome, HarnessError> {
1290        let info = self.model.info();
1291        let span = tracing::info_span!(
1292            target: "harness.telemetry",
1293            "agent_run",
1294            "gen_ai.operation.name" = "invoke_agent",
1295            "gen_ai.provider.name" = %info.provider,
1296            "gen_ai.request.model" = %info.model,
1297            outcome = Empty,
1298            "otel.status_code" = Empty,
1299            "otel.status_message" = Empty,
1300        );
1301        let started = std::time::Instant::now();
1302        let r = self.run_in_span(ctx, world).instrument(span.clone()).await;
1303        let outcome = match &r {
1304            Ok(Outcome::Done { .. }) => "done",
1305            Ok(Outcome::BudgetExhausted { .. }) => "budget_exhausted",
1306            Ok(Outcome::Stuck { .. }) => "stuck",
1307            Ok(Outcome::Cancelled { .. }) => "cancelled",
1308            Err(e) => {
1309                span.record("otel.status_code", "error")
1310                    .record("otel.status_message", e.to_string());
1311                "error"
1312            }
1313        };
1314        span.record("outcome", outcome);
1315        meters::run(outcome, started.elapsed());
1316        r
1317    }
1318
1319    async fn run_in_span(
1320        &self,
1321        mut ctx: Context,
1322        world: &mut World,
1323    ) -> Result<Outcome, HarnessError> {
1324        if ctx.system.is_empty() && !self.system.is_empty() {
1325            ctx.system = self.system.clone();
1326        }
1327
1328        // Size the context budget to the model actually in use.
1329        //
1330        // Compaction fires at a fraction of `max_input_tokens`, so a value
1331        // unrelated to the model is wrong in one of two directions: too high and
1332        // the provider rejects the request before the compactor ever runs (a 32k
1333        // model under the 150k default would need 112,500 tokens to trigger, and
1334        // it cannot hold that many); too low and the loop discards history it
1335        // could have kept. Nothing read `ModelInfo::context_window` before this —
1336        // the framework's own defaults disagreed, 150,000 against 128,000.
1337        //
1338        // Only when the caller left the default in place; an explicit policy is
1339        // a decision and stays untouched. The output allowance is reserved,
1340        // because the window is shared between the prompt and the reply.
1341        if let Some(n) = self.max_input_tokens {
1342            // An explicit cap wins over both the default and the model window.
1343            ctx.policy.max_input_tokens = n.max(1);
1344        } else if ctx.policy.max_input_tokens == harness_core::Policy::default().max_input_tokens {
1345            let window = self.model.info().context_window;
1346            if window > 0 {
1347                // Reserve room for the reply, but never let the reservation eat
1348                // the window: an 8k model with the default 8k output allowance
1349                // would leave 0 tokens for input, and every turn — a 26-token
1350                // one included — would run all five compaction stages against a
1351                // budget of 1. Cap the reservation at a quarter of the window.
1352                let reserve = ctx.policy.max_output_tokens.min(window / 4);
1353                ctx.policy.max_input_tokens = window.saturating_sub(reserve).max(1);
1354            }
1355        }
1356
1357        self.hooks.fire(
1358            &Event::SessionStart {
1359                source: SessionSource::Startup,
1360            },
1361            world,
1362        );
1363
1364        // ── recall: resolve owner/session, ensure the session row ──
1365        let (recall_owner, recall_session) = if self.recall.is_some() {
1366            use std::sync::atomic::Ordering;
1367            let owner = crate::recall_owner(world);
1368            let session = world
1369                .profile
1370                .extra
1371                .get("recall_session")
1372                .and_then(|v| v.as_str())
1373                .map(|s| s.to_string())
1374                .unwrap_or_else(|| {
1375                    format!(
1376                        "sess-{}-{}",
1377                        world.clock.now_ms(),
1378                        RECALL_SEQ.fetch_add(1, Ordering::SeqCst)
1379                    )
1380                });
1381            if let Some(store) = &self.recall {
1382                let meta = harness_core::SessionMeta::new(&session, world.clock.now_ms());
1383                if let Err(e) = store.ensure_session(&owner, &session, &meta).await {
1384                    tracing::warn!(error = %e, "recall ensure_session failed");
1385                }
1386            }
1387            (owner, session)
1388        } else {
1389            (String::new(), String::new())
1390        };
1391
1392        let recall_guide: Option<Arc<dyn Guide>> = if self.recall_auto_inject {
1393            if self.recall.is_none() {
1394                tracing::warn!(
1395                    "auto_inject() set but no recall store — call with_recall(store) first; skipping recall guide"
1396                );
1397                None
1398            } else {
1399                self.recall
1400                    .clone()
1401                    .map(|s| Arc::new(crate::RecallGuide::new(s)) as Arc<dyn Guide>)
1402            }
1403        } else {
1404            None
1405        };
1406        let all_guides: Vec<&Arc<dyn Guide>> =
1407            self.guides.iter().chain(recall_guide.iter()).collect();
1408        for g in &all_guides {
1409            if g.scope().matches(&ctx.task) {
1410                self.hooks.fire(&Event::PreGuide { guide: g.id() }, world);
1411                g.apply(&mut ctx, world).await?;
1412                self.hooks.fire(&Event::PostGuide { guide: g.id() }, world);
1413            }
1414        }
1415
1416        ctx.history.push(Turn {
1417            role: TurnRole::User,
1418            blocks: vec![Block::Text(ctx.task.description.clone())],
1419        });
1420
1421        if self.recall.is_some() {
1422            self.recall_append(
1423                &recall_owner,
1424                &recall_session,
1425                harness_core::RecallMessage::new(
1426                    "user",
1427                    ctx.task.description.clone(),
1428                    world.clock.now_ms(),
1429                ),
1430            )
1431            .await;
1432        }
1433
1434        // Running totals — surface to caller even on BudgetExhausted.
1435        let mut tools_called: u32 = 0;
1436        let mut total_usage = harness_core::Usage::default();
1437        let mut last_text: Option<String> = None;
1438
1439        // Stuck-detector state: the previous round's tool-call fingerprint and
1440        // how many consecutive rounds have repeated it.
1441        let mut last_fingerprint: Option<String> = None;
1442        let mut repeat_count: u32 = 0;
1443        // Monotony state: the tool that has been the round's only tool, and for
1444        // how many consecutive rounds. Separate counter from `repeat_count` on
1445        // purpose — the two detectors answer different questions.
1446        let mut monotone_tool: Option<String> = None;
1447        let mut monotone_rounds: u32 = 0;
1448        // Read-only calls already answered this run, cleared whenever anything
1449        // mutates the world. See `ToolResultPolicy::dedupe_repeats`.
1450        let mut answered: std::collections::HashSet<String> = std::collections::HashSet::new();
1451        // How many times the model has stopped mid-work with nothing to show.
1452        let mut acceptance_retries_left = self.acceptance_retries;
1453
1454        // The contract as it stood before the model touched anything. Taken
1455        // now, not at verdict time, because the whole point is to compare
1456        // against a state the model has not had the chance to influence.
1457        // Set once a sealed file is found to have moved; makes the failure
1458        // terminal and carries the reason out to the caller.
1459        let mut seal_breached: Option<String> = None;
1460        let sealed_before: crate::seal::SealSet = {
1461            let paths: Vec<std::path::PathBuf> =
1462                self.acceptance.iter().flat_map(|a| a.seals()).collect();
1463            if paths.is_empty() {
1464                crate::seal::SealSet::default()
1465            } else {
1466                crate::seal::SealSet::capture(&world.repo.root, paths)
1467            }
1468        };
1469
1470        // How far the loop actually got. Equal to `max_iters` on a normal
1471        // budget exhaustion, less when the wall clock stopped it first.
1472        let mut iters_done = ctx.policy.max_iters;
1473        let mut deadline_reached = false;
1474
1475        for iter in 0..ctx.policy.max_iters {
1476            if self.cancel.is_cancelled() {
1477                tracing::info!(iter, "run cancelled by caller");
1478                self.hooks.fire(&Event::Cancelled, world);
1479                self.hooks.fire(&Event::SessionEnd, world);
1480                return Ok(Outcome::Cancelled {
1481                    iters: iter,
1482                    last_text,
1483                    tools_called,
1484                    usage: total_usage,
1485                });
1486            }
1487
1488            // ── wall-clock budget ───────────────────────────────────────
1489            // `max_iters` bounds *steps*, which says nothing about elapsed
1490            // time: one iteration can be a 100ms read or a 20-minute build.
1491            // An unattended run is bounded in hours, not rounds, so a task
1492            // may carry a deadline — and reaching it goes through the same
1493            // forced-synthesis exit as a spent step budget, so the caller
1494            // gets the conclusion of the work rather than a dropped future.
1495            if let Some(at) = ctx.task.deadline
1496                && world.clock.now_ms() >= at
1497            {
1498                tracing::warn!(
1499                    iter,
1500                    deadline = at,
1501                    "task deadline reached — forcing a final answer"
1502                );
1503                iters_done = iter;
1504                deadline_reached = true;
1505                break;
1506            }
1507            self.hooks.fire(&Event::Heartbeat { iter }, world);
1508
1509            // Compaction with hysteresis: only once over the high-water mark,
1510            // then escalate stage-by-stage, re-estimating after each, and stop
1511            // the moment we're back under target. Avoids over-compacting to the
1512            // lossy AutoCompact stage and avoids rewriting history (→ prefix
1513            // cache miss) every turn. Token estimate is calibrated against the
1514            // last real `input_tokens` via `CALIBRATION_KEY`.
1515            let mut budget = self.compactor.budget(&ctx);
1516            if budget.ratio() > self.compaction.high_water {
1517                for stage in CompactionStage::ALL {
1518                    if budget.ratio() <= self.compaction.target {
1519                        break;
1520                    }
1521                    self.hooks.fire(&Event::PreCompact { stage }, world);
1522                    let before = budget.used;
1523                    let turns_before = ctx.history.len();
1524                    self.compactor.compact(stage, &mut ctx).await?;
1525                    budget = self.compactor.budget(&ctx);
1526                    // Compaction used to leave no trace anywhere: not in the
1527                    // log, not in the transcript. That is a bad property for
1528                    // the one mechanism that rewrites the conversation, and it
1529                    // is how a compaction bug that killed long runs stayed
1530                    // invisible — the only symptom was a provider error with
1531                    // no hint of what had touched the history.
1532                    tracing::info!(
1533                        stage = ?stage,
1534                        tokens_before = before,
1535                        tokens_after = budget.used,
1536                        turns_before,
1537                        turns_after = ctx.history.len(),
1538                        "compacted context"
1539                    );
1540                    meters::compaction(stage, before, budget.used);
1541                    self.hooks.fire(
1542                        &Event::PostCompact {
1543                            stage,
1544                            before,
1545                            after: budget.used,
1546                        },
1547                        world,
1548                    );
1549                }
1550            }
1551
1552            // Per-iteration guides — recall-style adapters that want to
1553            // refresh their injected context every turn (e.g. MemoryGuide
1554            // re-recalling against the latest user message). Default
1555            // `apply_before_iter` is a no-op, so this loop is cheap for
1556            // guides that don't override it.
1557            for g in &all_guides {
1558                if g.scope().matches(&ctx.task)
1559                    && let Err(e) = g.apply_before_iter(&mut ctx, world).await
1560                {
1561                    tracing::warn!(guide = %g.id(), error = %e, "apply_before_iter failed; continuing");
1562                }
1563            }
1564
1565            self.hooks.fire(&Event::PreModel { ctx: &ctx }, world);
1566            let mut partial = String::new();
1567            let Some(out) = self.model_step(&ctx, world, &mut partial).await? else {
1568                tracing::info!(iter, "run cancelled during model step");
1569                // What the stream delivered before the cancel is what the person
1570                // saw; it belongs to the outcome, not to the dropped future.
1571                if !partial.is_empty() {
1572                    last_text = Some(std::mem::take(&mut partial));
1573                }
1574                self.hooks.fire(&Event::Cancelled, world);
1575                self.hooks.fire(&Event::SessionEnd, world);
1576                return Ok(Outcome::Cancelled {
1577                    iters: iter + 1,
1578                    last_text,
1579                    tools_called,
1580                    usage: total_usage,
1581                });
1582            };
1583            self.hooks.fire(&Event::PostModel { out: &out }, world);
1584
1585            // Calibrate the compactor against ground truth: `ctx` still holds
1586            // exactly what we just sent, so `budget().used` is the estimate for
1587            // it. Nudge the stored correction so estimate·correction ≈ the
1588            // model's real `input_tokens` next time. Self-correcting (converges
1589            // even as the raw estimate drifts); clamped so one odd turn can't
1590            // blow it up. This is what makes compaction fire at the right moment
1591            // for *this* model + language instead of a blind char heuristic.
1592            if out.usage.input_tokens > 0 {
1593                let used = self.compactor.budget(&ctx).used;
1594                if used > 0 {
1595                    let prev = ctx
1596                        .metadata
1597                        .get(CALIBRATION_KEY)
1598                        .and_then(|v| v.as_f64())
1599                        .filter(|f| f.is_finite() && *f > 0.0)
1600                        .unwrap_or(1.0);
1601                    let next =
1602                        (prev * out.usage.input_tokens as f64 / used as f64).clamp(0.1, 10.0);
1603                    ctx.metadata
1604                        .insert(CALIBRATION_KEY.into(), serde_json::json!(next));
1605                }
1606            }
1607
1608            // Accumulate usage even if the run later exhausts budget.
1609            total_usage.input_tokens += out.usage.input_tokens;
1610            total_usage.output_tokens += out.usage.output_tokens;
1611            total_usage.cached_input_tokens += out.usage.cached_input_tokens;
1612            total_usage.cache_write_input_tokens += out.usage.cache_write_input_tokens;
1613            if let Some(t) = &out.text {
1614                last_text = Some(t.clone());
1615            }
1616            ctx.push_model_output(&out);
1617
1618            if self.recall.is_some() {
1619                let calls = if out.tool_calls.is_empty() {
1620                    None
1621                } else {
1622                    serde_json::to_string(&out.tool_calls).ok()
1623                };
1624                let mut m = harness_core::RecallMessage::new(
1625                    "assistant",
1626                    out.text.clone().unwrap_or_default(),
1627                    world.clock.now_ms(),
1628                );
1629                m.tool_calls = calls;
1630                self.recall_append(&recall_owner, &recall_session, m).await;
1631            }
1632
1633            if out.tool_calls.is_empty() {
1634                // The model stopping is its opinion that the work is done.
1635                // Before taking it as fact, run whatever the caller said
1636                // "done" actually means. A failure goes back as an instruction
1637                // and the loop carries on; the retry cap keeps a model that
1638                // ignores corrections from eating the budget.
1639                let mut verdict: Option<Verdict> = None;
1640                if !self.acceptance.is_empty() {
1641                    // Record this turn first — the checks read the transcript.
1642                    let mut probe = ctx.clone();
1643                    probe.history.push(Turn {
1644                        role: TurnRole::Assistant,
1645                        blocks: out
1646                            .text
1647                            .as_deref()
1648                            .filter(|t| !t.trim().is_empty())
1649                            .map(|t| vec![Block::Text(t.to_string())])
1650                            .unwrap_or_default(),
1651                    });
1652                    for check in &self.acceptance {
1653                        let v = check.check(&probe, world).await;
1654                        self.hooks.fire(
1655                            &Event::AcceptanceChecked {
1656                                name: check.name(),
1657                                passed: v.passed,
1658                                reason: &v.reason,
1659                            },
1660                            world,
1661                        );
1662                        if !v.passed {
1663                            tracing::info!(
1664                                check = check.name(),
1665                                reason = %v.reason,
1666                                "acceptance failed"
1667                            );
1668                            verdict = Some(v);
1669                            break;
1670                        }
1671                    }
1672                    // Everything passed. Say so explicitly: "checked, and it
1673                    // holds up" is a different claim from "nobody looked", and
1674                    // the host has to be able to tell them apart.
1675                    verdict = verdict.or_else(|| Some(Verdict::passed()));
1676                }
1677
1678                // A pass is only worth the contract it was measured against.
1679                // Re-read the sealed files and refuse if any moved.
1680                if !sealed_before.is_empty() && verdict.as_ref().is_some_and(|v| v.passed) {
1681                    let paths: Vec<std::path::PathBuf> =
1682                        self.acceptance.iter().flat_map(|a| a.seals()).collect();
1683                    let now = crate::seal::SealSet::capture(&world.repo.root, paths);
1684                    let breaches = sealed_before.breaches(&now);
1685                    if !breaches.is_empty() {
1686                        let what = breaches
1687                            .iter()
1688                            .map(|b| b.describe())
1689                            .collect::<Vec<_>>()
1690                            .join("; ");
1691                        tracing::error!(
1692                            breaches = %what,
1693                            "acceptance contract changed during the run — refusing the pass"
1694                        );
1695                        self.hooks
1696                            .fire(&Event::SealBreached { detail: &what }, world);
1697                        // Deliberately NOT a retry. Every other acceptance
1698                        // failure is handed back as an instruction because the
1699                        // model can act on it; this one would be handing back
1700                        // "you edited the gate", to the party that edited it,
1701                        // with the file still writable. The run is over.
1702                        seal_breached = Some(what);
1703                        verdict = Some(Verdict::failed(
1704                            "the acceptance contract was modified during this run",
1705                        ));
1706                    }
1707                }
1708
1709                if let Some(v) = verdict.clone().filter(|v| !v.passed)
1710                    && seal_breached.is_none()
1711                    && acceptance_retries_left > 0
1712                    && iter + 1 < ctx.policy.max_iters
1713                {
1714                    acceptance_retries_left -= 1;
1715                    ctx.history.push(Turn {
1716                        role: TurnRole::User,
1717                        blocks: vec![Block::Text(v.reason)],
1718                    });
1719                    continue;
1720                }
1721
1722                self.hooks.fire(&Event::TaskCompleted, world);
1723                self.hooks.fire(&Event::SessionEnd, world);
1724                self.run_learning_review(&ctx, world, tools_called).await;
1725                // Thinking models (e.g. Qwen3 via Ollama) sometimes emit the
1726                // whole answer into the reasoning channel and leave `text`
1727                // empty. Fall back to the reasoning so the turn isn't blank —
1728                // but `verified` says whether anyone agreed it was done.
1729                let text = out
1730                    .text
1731                    .filter(|t| !t.trim().is_empty())
1732                    .or_else(|| out.reasoning.filter(|r| !r.trim().is_empty()));
1733                return Ok(Outcome::Done {
1734                    text,
1735                    iters: iter + 1,
1736                    tools_called,
1737                    usage: total_usage,
1738                    verified: verdict,
1739                    contract: sealed_before.clone(),
1740                    seal_breach: seal_breached,
1741                });
1742            }
1743
1744            // Stuck detection runs *after* dispatch — see the block below the
1745            // tool loop, which needs this round's results to judge progress.
1746
1747            // Parallel-safe prefetch: dispatch the *leading run* of read-only
1748            // tool calls concurrently (a mutating tool is a serial barrier).
1749            // The sequential loop below still processes every call in order —
1750            // hooks, sensors, and history stay ordered — only the dispatch IO
1751            // overlaps. Reads before any write are safe; anything at/after the
1752            // first mutating call runs on the normal path.
1753            // Digest of what each tool handed back this round, for the stuck
1754            // check below. Digests rather than the payloads: results are
1755            // already capped, but a per-round copy of every one of them is
1756            // still a cost the detector does not need to pay.
1757            let mut round_results: Vec<u64> = Vec::new();
1758
1759            let mut prefetched: HashMap<String, Dispatched> = HashMap::new();
1760            {
1761                let lead: Vec<&_> = out
1762                    .tool_calls
1763                    .iter()
1764                    .take_while(|c| {
1765                        self.tools.risk(&c.name) == Some(harness_core::ToolRisk::ReadOnly)
1766                    })
1767                    .collect();
1768                if lead.len() > 1 {
1769                    let futs = lead.iter().map(|c| {
1770                        let mut w = world.clone();
1771                        let action = Action {
1772                            tool: c.name.clone(),
1773                            call_id: c.id.clone(),
1774                            args: c.args.clone(),
1775                        };
1776                        async move {
1777                            let r = self.dispatch_bounded(&action, &mut w).await;
1778                            (action.call_id, r)
1779                        }
1780                    });
1781                    let results = tokio::select! {
1782                        biased;
1783                        _ = self.cancel.cancelled() => Vec::new(),
1784                        rs = futures::future::join_all(futs) => rs,
1785                    };
1786                    for (id, r) in results {
1787                        prefetched.insert(id, r);
1788                    }
1789                }
1790            }
1791
1792            for call in &out.tool_calls {
1793                let action = Action {
1794                    tool: call.name.clone(),
1795                    call_id: call.id.clone(),
1796                    args: call.args.clone(),
1797                };
1798
1799                // PreToolUse hook can deny destructive actions
1800                if let HookOutcome::Deny { reason } = self
1801                    .hooks
1802                    .fire(&Event::PreToolUse { action: &action }, world)
1803                {
1804                    ctx.history.push(Turn {
1805                        role: TurnRole::Tool,
1806                        blocks: vec![Block::ToolResult {
1807                            call_id: action.call_id.clone(),
1808                            content: serde_json::json!({
1809                                "ok": false,
1810                                "denied_by_hook": reason,
1811                            }),
1812                        }],
1813                    });
1814                    if self.recall.is_some() {
1815                        self.recall_append(
1816                            &recall_owner,
1817                            &recall_session,
1818                            harness_core::RecallMessage::new(
1819                                "tool",
1820                                format!("[denied by hook] {reason}"),
1821                                world.clock.now_ms(),
1822                            )
1823                            .with_tool_name(action.tool.clone()),
1824                        )
1825                        .await;
1826                    }
1827                    continue;
1828                }
1829
1830                // Use the concurrently-prefetched result if we have one;
1831                // otherwise dispatch now.
1832                let Dispatched {
1833                    result,
1834                    started_ms,
1835                    finished_ms,
1836                } = if let Some(r) = prefetched.remove(&action.call_id) {
1837                    r
1838                } else {
1839                    self.dispatch_bounded(&action, world).await
1840                };
1841                tools_called += 1;
1842
1843                if self.cancel.is_cancelled() {
1844                    tracing::info!(iter, "run cancelled during tool dispatch");
1845                    self.hooks.fire(&Event::Cancelled, world);
1846                    self.hooks.fire(&Event::SessionEnd, world);
1847                    return Ok(Outcome::Cancelled {
1848                        iters: iter + 1,
1849                        last_text,
1850                        tools_called,
1851                        usage: total_usage,
1852                    });
1853                }
1854
1855                // Decide the final payload *before* announcing the result, so
1856                // hooks, telemetry and the context all describe the same thing:
1857                // an audit that logs a 200 KB blob the model never saw is not an
1858                // audit of what happened.
1859                let result = ToolResult {
1860                    content: self.shape_result(&action, &result, &mut answered, &world.repo.root),
1861                    ..result
1862                };
1863                self.hooks.fire(
1864                    &Event::ToolTimed {
1865                        action: &action,
1866                        started_ms,
1867                        finished_ms,
1868                    },
1869                    world,
1870                );
1871                self.hooks.fire(
1872                    &Event::PostToolUse {
1873                        action: &action,
1874                        result: &result,
1875                    },
1876                    world,
1877                );
1878
1879                round_results.push(result_digest(&action.tool, &result.content));
1880
1881                ctx.history.push(Turn {
1882                    role: TurnRole::Tool,
1883                    blocks: vec![Block::ToolResult {
1884                        call_id: action.call_id.clone(),
1885                        content: result.content.clone(),
1886                    }],
1887                });
1888
1889                if self.recall.is_some() {
1890                    let body = serde_json::to_string(&result.content).unwrap_or_default();
1891                    self.recall_append(
1892                        &recall_owner,
1893                        &recall_session,
1894                        harness_core::RecallMessage::new("tool", body, world.clock.now_ms())
1895                            .with_tool_name(action.tool.clone()),
1896                    )
1897                    .await;
1898                }
1899
1900                // run self-correct sensors
1901                let mut all_signals = Vec::new();
1902                for s in &self.sensors {
1903                    if s.stage() != Stage::SelfCorrect {
1904                        continue;
1905                    }
1906                    self.hooks.fire(&Event::PreSensor { sensor: s.id() }, world);
1907                    let sigs = s.observe(&action, world).await.unwrap_or_else(|e| {
1908                        tracing::warn!(?e, "sensor failed");
1909                        Vec::new()
1910                    });
1911                    self.hooks.fire(
1912                        &Event::PostSensor {
1913                            sensor: s.id(),
1914                            signals: &sigs,
1915                        },
1916                        world,
1917                    );
1918                    all_signals.extend(sigs);
1919                }
1920                if !all_signals.is_empty() {
1921                    let bundle = SignalSet::new(all_signals);
1922                    let (patches, remaining) = bundle.partition_auto_fix();
1923
1924                    // audit #7: each patch goes through PreAutoFix.
1925                    // Hooks can Deny (skip silently). Default safelist on
1926                    // RunCommand catches the obvious misuses with no hook.
1927                    let approved: Vec<harness_core::FixPatch> = patches.into_iter().filter(|p| {
1928                        if !is_default_safe_fix(p) {
1929                            tracing::warn!(?p, "auto-fix rejected by default safelist (use PreAutoFix hook to override)");
1930                            self.hooks.fire(&Event::PostAutoFix { patch: p, applied: false }, world);
1931                            return false;
1932                        }
1933                        match self.hooks.fire(&Event::PreAutoFix { patch: p }, world) {
1934                            HookOutcome::Deny { reason } => {
1935                                tracing::warn!(?p, %reason, "auto-fix denied by hook");
1936                                self.hooks.fire(&Event::PostAutoFix { patch: p, applied: false }, world);
1937                                false
1938                            }
1939                            _ => true,
1940                        }
1941                    }).collect();
1942
1943                    let applied = apply_patches(&approved, world).await;
1944                    // Emit PostAutoFix for each approved patch with the application result.
1945                    for (i, p) in approved.iter().enumerate() {
1946                        self.hooks.fire(
1947                            &Event::PostAutoFix {
1948                                patch: p,
1949                                applied: i < applied.len(),
1950                            },
1951                            world,
1952                        );
1953                    }
1954                    if !applied.is_empty() {
1955                        ctx.push_feedback(vec![harness_core::Signal {
1956                            severity: harness_core::Severity::Hint,
1957                            origin: "auto-fix".into(),
1958                            message: format!(
1959                                "applied {} auto-fix patch(es): {applied:?}",
1960                                applied.len()
1961                            ),
1962                            agent_hint: Some(
1963                                "re-check the affected files before continuing".into(),
1964                            ),
1965                            auto_fix: None,
1966                            location: None,
1967                        }]);
1968                    }
1969                    if remaining.has_blocking() {
1970                        ctx.push_feedback(remaining.signals);
1971                    }
1972                }
1973            }
1974
1975            // ── stuck detection ─────────────────────────────────────────
1976            // A round repeats when the request AND what came back were both
1977            // identical. The same call whose *result moved* is the model
1978            // watching something progress — polling a build, a background
1979            // job, a queue — not spinning, which is why this runs after
1980            // dispatch: before it, this round's results do not exist yet and
1981            // the check could only compare the request. Judging on the
1982            // request alone aborted runs that were making progress, and a
1983            // long unattended task is mostly made of such waits.
1984            //
1985            // A poll whose result never changes still counts, and still
1986            // aborts: burning model calls on a thing that is not moving is
1987            // exactly what this guard is for. What bounds a *legitimate*
1988            // long wait is `max_iters`, not this.
1989            if self.stuck.enabled {
1990                let fp = format!(
1991                    "{}#{}",
1992                    tool_call_fingerprint(&out.tool_calls),
1993                    round_results
1994                        .iter()
1995                        .map(u64::to_string)
1996                        .collect::<Vec<_>>()
1997                        .join(",")
1998                );
1999                if last_fingerprint.as_ref() == Some(&fp) {
2000                    repeat_count += 1;
2001                } else {
2002                    repeat_count = 1;
2003                    last_fingerprint = Some(fp);
2004                }
2005
2006                if repeat_count >= self.stuck.abort_after {
2007                    let reason = format!(
2008                        "repeated the same tool call {repeat_count}× with an unchanging result"
2009                    );
2010                    tracing::warn!(repeated = repeat_count, "stuck: aborting run");
2011                    self.hooks.fire(&Event::SessionEnd, world);
2012                    return Ok(Outcome::Stuck {
2013                        reason,
2014                        repeated: repeat_count,
2015                        iters: iter + 1,
2016                        last_text,
2017                        tools_called,
2018                        usage: total_usage,
2019                    });
2020                }
2021
2022                if repeat_count == self.stuck.nudge_after {
2023                    tracing::warn!(
2024                        repeated = repeat_count,
2025                        "stuck: nudging model to change approach"
2026                    );
2027                    ctx.push_feedback(vec![harness_core::Signal {
2028                        severity: harness_core::Severity::Warn,
2029                        origin: "stuck-detector".into(),
2030                        message: format!(
2031                            "You have issued the same tool call {repeat_count} rounds in a row \
2032                             and the result has not changed."
2033                        ),
2034                        agent_hint: Some(
2035                            "Stop repeating it. Inspect the actual tool result/error, try a \
2036                             different approach, or give your final answer with no tool call. \
2037                             If you are waiting on something, wait inside one call rather than \
2038                             polling in a tight loop."
2039                                .into(),
2040                        ),
2041                        auto_fix: None,
2042                        location: None,
2043                    }]);
2044                }
2045            }
2046
2047            // ── monotony detection ──────────────────────────────────────
2048            // The second signal, and deliberately not part of the block above:
2049            // that one asks "did this round repeat?", this one asks "has the
2050            // model been working a single tool and nothing else?". A guessing
2051            // spiral answers no to the first and yes to the second, which is
2052            // why the byte-identical policy stays exactly as strict as it is.
2053            //
2054            // Off unless the host asked for it — see `MonotonyPolicy` for why
2055            // no threshold is safe by default. Independent of `stuck.enabled`,
2056            // so a host can run either, both, or neither.
2057            if self.monotony.enabled {
2058                match sole_tool(&out.tool_calls) {
2059                    // Same single tool as last round: the run continues.
2060                    Some(name) if monotone_tool.as_deref() == Some(name) => monotone_rounds += 1,
2061                    // A different single tool: a new run of one.
2062                    Some(name) => {
2063                        monotone_tool = Some(name.to_string());
2064                        monotone_rounds = 1;
2065                    }
2066                    // A mixed round. Reaching for a second tool is movement,
2067                    // and movement is what this detector is looking for.
2068                    None => {
2069                        monotone_tool = None;
2070                        monotone_rounds = 0;
2071                    }
2072                }
2073
2074                if monotone_rounds >= self.monotony.abort_after {
2075                    let name = monotone_tool.clone().unwrap_or_default();
2076                    let reason = format!(
2077                        "called `{name}` for {monotone_rounds} consecutive rounds \
2078                         without using any other tool"
2079                    );
2080                    tracing::warn!(tool = %name, rounds = monotone_rounds, "monotony: aborting run");
2081
2082                    // Force the final answer before returning. A model caught
2083                    // here is by definition one that will not stop calling
2084                    // tools on its own, so terminating it without asking for
2085                    // text hands the caller the same empty partial answer the
2086                    // detector exists to prevent — earlier, and therefore
2087                    // worse. Stripping the tools and asking once is the exit
2088                    // the model could not find; it costs one model call and no
2089                    // prompt bytes at all. (The budget-exhausted path has done
2090                    // this since it existed; this is the same exit, reached
2091                    // sooner.)
2092                    match self
2093                        .force_final_synthesis(
2094                            &mut ctx,
2095                            world,
2096                            &mut total_usage,
2097                            MONOTONY_SYNTHESIS_PROMPT,
2098                        )
2099                        .await
2100                    {
2101                        Synthesis::Text(Some(t)) => last_text = Some(t),
2102                        Synthesis::Text(None) => {}
2103                        // Stop means stop: the synthesis is a model call like
2104                        // any other, and the run owes the caller a `Cancelled`
2105                        // rather than the `Stuck` it was on its way to.
2106                        Synthesis::Cancelled => {
2107                            tracing::info!(iter, "run cancelled during final synthesis");
2108                            self.hooks.fire(&Event::Cancelled, world);
2109                            self.hooks.fire(&Event::SessionEnd, world);
2110                            return Ok(Outcome::Cancelled {
2111                                iters: iter + 1,
2112                                last_text,
2113                                tools_called,
2114                                usage: total_usage,
2115                            });
2116                        }
2117                    }
2118
2119                    self.hooks.fire(&Event::SessionEnd, world);
2120                    return Ok(Outcome::Stuck {
2121                        reason,
2122                        repeated: monotone_rounds,
2123                        iters: iter + 1,
2124                        last_text,
2125                        tools_called,
2126                        usage: total_usage,
2127                    });
2128                }
2129
2130                if monotone_rounds == self.monotony.nudge_after {
2131                    let name = monotone_tool.clone().unwrap_or_default();
2132                    tracing::warn!(
2133                        tool = %name,
2134                        rounds = monotone_rounds,
2135                        "monotony: nudging model to change approach"
2136                    );
2137                    ctx.push_feedback(vec![harness_core::Signal {
2138                        severity: harness_core::Severity::Warn,
2139                        origin: "monotony-detector".into(),
2140                        message: format!(
2141                            "You have called `{name}` for {monotone_rounds} rounds in a row \
2142                             and used no other tool. A different argument each time is not \
2143                             the same thing as making progress."
2144                        ),
2145                        agent_hint: Some(
2146                            "If you are guessing at arguments to see which one lands, stop: \
2147                             report what you did find and say plainly what you could not \
2148                             determine. Otherwise reach for a different tool, or give your \
2149                             final answer with no tool call."
2150                                .into(),
2151                        ),
2152                        auto_fix: None,
2153                        location: None,
2154                    }]);
2155                }
2156            }
2157        }
2158        // ── Budget exhausted ─────────────────────────────────────────
2159        // Force a final synthesis pass with tools DISABLED. Otherwise the
2160        // model often spins on tool calls right up to the budget cap and
2161        // never emits a text conclusion, leaving the caller with nothing
2162        // but `last_text` from some earlier intermediate turn (or None).
2163        //
2164        // The synthesis call is "free" — it costs one extra model call
2165        // beyond max_iters but doesn't count toward `iters`. The result
2166        // lands in `last_text` so callers display it as the answer.
2167        //
2168        // Signal to any observer (LiveProgressHook, SessionRecorder, custom
2169        // hooks) that we've used 100% of the budget and are about to force
2170        // synthesis. Pre-existing `BudgetWarning` event was unused; this is
2171        // its natural home.
2172        self.hooks.fire(&Event::BudgetWarning { ratio: 1.0 }, world);
2173        match self
2174            .force_final_synthesis(&mut ctx, world, &mut total_usage, BUDGET_SYNTHESIS_PROMPT)
2175            .await
2176        {
2177            Synthesis::Text(Some(t)) => last_text = Some(t),
2178            Synthesis::Text(None) => {}
2179            // A cancel that lands here has to win: this is the last model call
2180            // of the run, and it is made after the loop's last cancel check.
2181            // No learning review either — it is one more model call, and the
2182            // other cancel exits all skip it.
2183            Synthesis::Cancelled => {
2184                tracing::info!(iter = iters_done, "run cancelled during final synthesis");
2185                self.hooks.fire(&Event::Cancelled, world);
2186                self.hooks.fire(&Event::SessionEnd, world);
2187                return Ok(Outcome::Cancelled {
2188                    iters: iters_done,
2189                    last_text,
2190                    tools_called,
2191                    usage: total_usage,
2192                });
2193            }
2194        }
2195
2196        self.hooks.fire(&Event::SessionEnd, world);
2197        self.run_learning_review(&ctx, world, tools_called).await;
2198        Ok(Outcome::BudgetExhausted {
2199            iters: iters_done,
2200            last_text,
2201            tools_called,
2202            usage: total_usage,
2203            deadline_reached,
2204        })
2205    }
2206
2207    /// One model call, racing the run's cancellation token.
2208    ///
2209    /// `None` means the token fired first. Dropping the un-awaited future is
2210    /// what cancels the underlying HTTP request (reqwest aborts on drop) or
2211    /// the SSE stream, so the model stops generating rather than finishing
2212    /// into a void. `biased` so a token already cancelled wins a tie.
2213    ///
2214    /// `partial` collects streamed text so a cancel can hand it to the outcome.
2215    async fn model_step(
2216        &self,
2217        ctx: &Context,
2218        world: &mut World,
2219        partial: &mut String,
2220    ) -> Result<Option<ModelOutput>, HarnessError> {
2221        let info = self.model.info();
2222        let span = chat_span(&info);
2223        let started = std::time::Instant::now();
2224        let r = async {
2225            if self.streaming {
2226                tokio::select! {
2227                    biased;
2228                    _ = self.cancel.cancelled() => Ok(None),
2229                    r = self.complete_via_stream(ctx, world, partial) => r.map(Some),
2230                }
2231            } else {
2232                tokio::select! {
2233                    biased;
2234                    _ = self.cancel.cancelled() => Ok(None),
2235                    r = self.model.complete(ctx) => r
2236                        .map(Some)
2237                        .map_err(harness_core::HarnessError::Model),
2238                }
2239            }
2240        }
2241        .instrument(span.clone())
2242        .await;
2243        let end = match &r {
2244            Ok(Some(out)) => Some(Ok(out)),
2245            Ok(None) => None,
2246            Err(e) => Some(Err(e.to_string())),
2247        };
2248        finish_chat(&span, &info, started, end);
2249        r
2250    }
2251
2252    /// Drive `Model::stream()` and assemble the result into a `ModelOutput`,
2253    /// firing `Event::ModelTokenDelta` for each text fragment along the way.
2254    ///
2255    /// Adapters that don't implement real streaming (e.g. `GeminiNative` /
2256    /// `AnthropicNative` today) fall back to the default trait impl, which
2257    /// runs `complete()` and emits the whole reply as a single delta. That
2258    /// works — the loop sees one big `ModelDelta::Text(...)` followed by
2259    /// `Stop`, fires one big `ModelTokenDelta`, and proceeds. So enabling
2260    /// `streaming` is safe regardless of which provider the user picked.
2261    ///
2262    /// `sink` is where the text accumulates, owned by the caller so that a
2263    /// cancel — which drops this future mid-stream — does not drop the chunks
2264    /// already delivered along with it. A completed stream leaves it empty.
2265    ///
2266    /// Tool-call deltas need no such rescue: they fire no hook, and no dispatch
2267    /// happens until after the output is pushed, so a cancel mid-tool-call
2268    /// loses nothing anyone observed.
2269    async fn complete_via_stream(
2270        &self,
2271        ctx: &Context,
2272        world: &mut World,
2273        sink: &mut String,
2274    ) -> Result<ModelOutput, HarnessError> {
2275        use futures::StreamExt;
2276        let mut stream = self
2277            .model
2278            .stream(ctx)
2279            .await
2280            .map_err(harness_core::HarnessError::Model)?;
2281        let mut reasoning = String::new();
2282        let mut usage = Usage::default();
2283        let mut stop_reason = StopReason::EndTurn;
2284        // Insertion-ordered map: index → (id, name, args). We can't use the
2285        // tool-call id as the primary key because the stream may emit args
2286        // chunks before the first chunk that carries the id; the OpenAI-compat
2287        // SSE parser already does its own buffering and surfaces `id` in
2288        // ToolCallStart, but be lenient with adapters that may interleave.
2289        let mut tool_starts: HashMap<String, (String, String)> = HashMap::new();
2290        let mut tool_order: Vec<String> = Vec::new();
2291        while let Some(item) = stream.next().await {
2292            let delta = item.map_err(harness_core::HarnessError::Model)?;
2293            match delta {
2294                ModelDelta::Text(t) => {
2295                    if !t.is_empty() {
2296                        self.hooks.fire(&Event::ModelTokenDelta { text: &t }, world);
2297                        sink.push_str(&t);
2298                    }
2299                }
2300                ModelDelta::ToolCallStart { id, name } => {
2301                    if !tool_starts.contains_key(&id) {
2302                        tool_order.push(id.clone());
2303                    }
2304                    tool_starts
2305                        .entry(id)
2306                        .or_insert_with(|| (name, String::new()));
2307                }
2308                ModelDelta::ToolCallArgs { id, partial_json } => {
2309                    let entry = tool_starts
2310                        .entry(id.clone())
2311                        .or_insert_with(|| (String::new(), String::new()));
2312                    if !tool_order.iter().any(|k| k == &id) {
2313                        tool_order.push(id);
2314                    }
2315                    entry.1.push_str(&partial_json);
2316                }
2317                ModelDelta::ToolCallEnd { .. } => {}
2318                ModelDelta::Usage(u) => usage = u,
2319                ModelDelta::Stop(r) => stop_reason = r,
2320                ModelDelta::Reasoning(s) => {
2321                    // Streamed reasoning arrives as token fragments, not lines —
2322                    // concatenate verbatim (same as `text`), don't insert newlines.
2323                    reasoning.push_str(&s);
2324                }
2325                // ModelDelta is `#[non_exhaustive]`; ignore future variants
2326                // we don't yet understand.
2327                _ => {}
2328            }
2329        }
2330        let tool_calls: Vec<ToolCall> = tool_order
2331            .into_iter()
2332            .filter_map(|id| {
2333                tool_starts.remove(&id).map(|(name, args)| {
2334                    let args_v = serde_json::from_str::<serde_json::Value>(&args)
2335                        .unwrap_or(serde_json::Value::String(args));
2336                    ToolCall {
2337                        id,
2338                        name,
2339                        args: args_v,
2340                    }
2341                })
2342            })
2343            .collect();
2344        // Reconcile stop_reason with what actually came out — adapters
2345        // sometimes emit `Stop(EndTurn)` even after tool_calls, which would
2346        // confuse downstream consumers that branch on stop_reason alone.
2347        let stop_reason = if !tool_calls.is_empty() {
2348            StopReason::ToolUse
2349        } else {
2350            stop_reason
2351        };
2352        let text = std::mem::take(sink);
2353        Ok(ModelOutput {
2354            text: if text.is_empty() { None } else { Some(text) },
2355            tool_calls,
2356            usage,
2357            stop_reason,
2358            reasoning: if reasoning.is_empty() {
2359                None
2360            } else {
2361                Some(reasoning)
2362            },
2363            // `ModelDelta` has no image variant: the verified image-output
2364            // path (Gemini image models over chat) answers non-streamed, so
2365            // there is nothing to accumulate here. A streaming provider that
2366            // emits images would need a `ModelDelta::Image` first.
2367            images: Vec::new(),
2368        })
2369    }
2370
2371    /// One tool call, under the per-call deadline and the run's cancellation
2372    /// token. A timeout becomes an error *result* — the model sees it and routes
2373    /// around it — never a hung run. A cancel drops the tool's future unpolled
2374    /// and returns a result the loop discards before it reaches history, so the
2375    /// model never sees that one at all. Errors are folded the same way: the
2376    /// loop's contract is that a tool call always produces a result turn.
2377    ///
2378    /// Dropping the future stops *this* side of the work. What it stops on the
2379    /// other side depends on the tool: an HTTP request aborts, a `spawn_blocking`
2380    /// file write runs to completion, and a child process is only killed if its
2381    /// runner asked for `kill_on_drop`.
2382    ///
2383    /// Runs in an `execute_tool` span, so parallel calls show up as overlapping
2384    /// bars in a trace and a failed one is marked as an error.
2385    async fn dispatch_bounded(&self, action: &Action, world: &mut World) -> Dispatched {
2386        let span = tracing::info_span!(
2387            target: "harness.telemetry",
2388            "execute_tool",
2389            "otel.name" = %format!("execute_tool {}", action.tool),
2390            "otel.status_code" = Empty,
2391            "otel.status_message" = Empty,
2392            "gen_ai.operation.name" = "execute_tool",
2393            "gen_ai.tool.name" = %action.tool,
2394            "gen_ai.tool.call.id" = %action.call_id,
2395            ok = Empty,
2396        );
2397        let clock = world.clock.clone();
2398        let started_ms = clock.now_ms();
2399        let started = std::time::Instant::now();
2400        let r = self
2401            .dispatch_bounded_in_span(action, world)
2402            .instrument(span.clone())
2403            .await;
2404        let finished_ms = clock.now_ms();
2405        meters::tool_call(&action.tool, r.ok, started.elapsed());
2406        span.record("ok", r.ok);
2407        if !r.ok {
2408            span.record("otel.status_code", "error");
2409            if let Some(msg) = r.content.get("error").and_then(|v| v.as_str()) {
2410                span.record("otel.status_message", msg);
2411            }
2412        }
2413        Dispatched {
2414            result: r,
2415            started_ms,
2416            finished_ms,
2417        }
2418    }
2419
2420    async fn dispatch_bounded_in_span(&self, action: &Action, world: &mut World) -> ToolResult {
2421        let fut = self.tools.dispatch(action, world);
2422        let bounded = async {
2423            match self.tool_timeout {
2424                Some(deadline) => match tokio::time::timeout(deadline, fut).await {
2425                    Ok(r) => r,
2426                    Err(_) => {
2427                        tracing::warn!(
2428                            target: "harness.telemetry",
2429                            event = "tool.deadline",
2430                            "gen_ai.tool.name" = %action.tool,
2431                            seconds = deadline.as_secs(),
2432                        );
2433                        Ok(ToolResult {
2434                            ok: false,
2435                            content: serde_json::json!({
2436                                "error": format!(
2437                                    "tool call exceeded its {}s deadline and was cancelled; \
2438                                     the operation may be too broad — narrow it or try a \
2439                                     different approach",
2440                                    deadline.as_secs()
2441                                ),
2442                                "timeout": true,
2443                            }),
2444                            trace: None,
2445                        })
2446                    }
2447                },
2448                None => fut.await,
2449            }
2450        };
2451        // `biased` so that a token already cancelled wins even when the tool
2452        // future is also ready — the caller said stop, and a result produced
2453        // after that would be work the run is about to throw away anyway.
2454        let dispatched = tokio::select! {
2455            biased;
2456            _ = self.cancel.cancelled() => {
2457                tracing::info!("gen_ai.tool.name" = %action.tool, "tool call dropped: run cancelled");
2458                return ToolResult {
2459                    ok: false,
2460                    content: serde_json::json!({"error": "run cancelled", "cancelled": true}),
2461                    trace: None,
2462                };
2463            }
2464            r = bounded => r,
2465        };
2466        dispatched.unwrap_or_else(|e| ToolResult {
2467            ok: false,
2468            content: serde_json::json!({"error": e.to_string()}),
2469            trace: None,
2470        })
2471    }
2472
2473    /// What a tool result contributes to the context: repeat suppression first,
2474    /// then the size ceiling. A repeat that is also oversized collapses to the
2475    /// pointer rather than to a truncated copy of what the model already holds.
2476    fn shape_result(
2477        &self,
2478        action: &Action,
2479        result: &ToolResult,
2480        answered: &mut std::collections::HashSet<String>,
2481        root: &std::path::Path,
2482    ) -> serde_json::Value {
2483        if !(self.tool_results.dedupe_repeats && result.ok) {
2484            return self.cap_result(action, &result.content, root);
2485        }
2486        match self.tools.risk(&action.tool) {
2487            Some(harness_core::ToolRisk::ReadOnly) => {
2488                let fp = format!("{}({})", action.tool, action.args);
2489                if answered.contains(&fp) {
2490                    tracing::info!(
2491                        target: "harness.telemetry",
2492                        event = "tool.result.repeat",
2493                        "gen_ai.tool.name" = %action.tool,
2494                    );
2495                    serde_json::json!({
2496                        "repeat_of_earlier_call": true,
2497                        "tool": action.tool,
2498                        "note": "You already made this exact call in this run and nothing has \
2499                                 changed the workspace since. The earlier result above still \
2500                                 stands — use it rather than asking again.",
2501                    })
2502                } else {
2503                    answered.insert(fp);
2504                    self.cap_result(action, &result.content, root)
2505                }
2506            }
2507            // A write invalidates every earlier read.
2508            _ => {
2509                answered.clear();
2510                self.cap_result(action, &result.content, root)
2511            }
2512        }
2513    }
2514
2515    /// Enforce [`ToolResultPolicy`] on one result before it reaches the context.
2516    ///
2517    /// Over the ceiling, the guard prefers to *spill*: full payload to a file
2518    /// inside the workspace, bounded preview plus the path inline — nothing is
2519    /// lost, and the model retrieves slices with the file tools it already has.
2520    /// Only when spilling is off (or the write fails) does it fall back to
2521    /// destructive truncation: a byte-level cut handed back as a marker object
2522    /// rather than mangled JSON, saying how much was dropped and what to do
2523    /// instead.
2524    fn cap_result(
2525        &self,
2526        action: &Action,
2527        content: &serde_json::Value,
2528        root: &std::path::Path,
2529    ) -> serde_json::Value {
2530        let Some(max) = self.tool_results.max_bytes else {
2531            return content.clone();
2532        };
2533        let serialized = content.to_string();
2534        if serialized.len() <= max {
2535            return content.clone();
2536        }
2537        if self.tool_results.spill
2538            && let Some(marker) = spill_oversized(action, content, &serialized, root)
2539        {
2540            return marker;
2541        }
2542        // Cut on a char boundary so the kept head is valid UTF-8.
2543        let mut end = max;
2544        while end > 0 && !serialized.is_char_boundary(end) {
2545            end -= 1;
2546        }
2547        tracing::warn!(
2548            target: "harness.telemetry",
2549            event = "tool.result.truncated",
2550            "gen_ai.tool.name" = %action.tool,
2551            bytes = serialized.len(),
2552            max_bytes = max,
2553        );
2554        serde_json::json!({
2555            "truncated": true,
2556            "tool": action.tool,
2557            "bytes_total": serialized.len(),
2558            "bytes_kept": end,
2559            "head": serialized[..end],
2560            "note": format!(
2561                "This result was {} bytes and was cut to {} to protect the context window. \
2562                 Do not ask for it again unchanged — narrow it: request a smaller range, \
2563                 a filter, or a specific field.",
2564                serialized.len(), end
2565            ),
2566        })
2567    }
2568
2569    async fn recall_append(&self, owner: &str, session: &str, msg: harness_core::RecallMessage) {
2570        if let Some(store) = &self.recall
2571            && let Err(e) = store.append(owner, session, &msg).await
2572        {
2573            tracing::warn!(error = %e, "recall append failed");
2574        }
2575    }
2576
2577    /// Best-effort post-session review. Never affects the finished run.
2578    async fn run_learning_review(&self, ctx: &Context, world: &mut World, tools_called: u32) {
2579        let Some(cfg) = &self.learning else { return };
2580        if tools_called < cfg.nudge_interval {
2581            return;
2582        }
2583        let transcript = crate::render_transcript(&ctx.history, 12_000);
2584        let task = harness_core::Task {
2585            description: format!(
2586                "{}\n\n## Conversation transcript\n{}",
2587                cfg.review_prompt, transcript
2588            ),
2589            source: None,
2590            deadline: None,
2591        };
2592        let mut spec =
2593            crate::SubagentSpec::new("learning-review", task).with_max_iters(cfg.max_iters);
2594        for t in &cfg.tools {
2595            spec = spec.with_tool(t.clone());
2596        }
2597        let sub = crate::Subagent::new(harness_core::DynModel(cfg.review_model.clone()), spec);
2598        // Box::pin breaks the recursive async-future cycle: AgentLoop<M> →
2599        // run_learning_review → Subagent<DynModel>::run →
2600        // AgentLoop<Arc<dyn Model>>::run_built_context. Without pinning the
2601        // compiler rejects the infinite-sized future.
2602        if let Err(e) = Box::pin(sub.run(world)).await {
2603            tracing::warn!(error = %e, "learning review failed");
2604        }
2605    }
2606
2607    /// One final model call with tools removed, asking it to write the
2608    /// best-effort conclusion from whatever it has already gathered.
2609    ///
2610    /// Errors from the model are swallowed — observability is best-effort
2611    /// here, and a transport blip during synthesis should not turn a
2612    /// near-complete run into a hard failure.
2613    ///
2614    /// The call is raced against the run's cancellation token like every
2615    /// other model call: a cancel before or during it produces no text,
2616    /// leaves the context as it was, and is reported as
2617    /// [`Synthesis::Cancelled`] so the caller can return `Outcome::Cancelled`
2618    /// instead of pretending the run ended on its own terms.
2619    ///
2620    /// `prompt` says *why* the loop stopped granting tool calls. Budget
2621    /// exhaustion is not the only way a run can end with the model still
2622    /// reaching for tools — a detected loop is another — and the model writes a
2623    /// better final answer when it is told which one happened.
2624    async fn force_final_synthesis(
2625        &self,
2626        ctx: &mut Context,
2627        world: &mut World,
2628        total_usage: &mut harness_core::Usage,
2629        prompt: &str,
2630    ) -> Synthesis {
2631        // Snapshot + clear tool schemas so the model has no choice but text.
2632        let saved_tools = std::mem::take(&mut ctx.tools);
2633        ctx.history.push(Turn {
2634            role: TurnRole::User,
2635            blocks: vec![Block::Text(prompt.into())],
2636        });
2637
2638        self.hooks.fire(&Event::PreModel { ctx }, world);
2639        // `biased` with the token first means an already-cancelled token wins
2640        // the race outright, so no separate `is_cancelled()` pre-check is
2641        // needed here — the select is the check.
2642        let info = self.model.info();
2643        let span = chat_span(&info);
2644        let started = std::time::Instant::now();
2645        let result = tokio::select! {
2646            biased;
2647            _ = self.cancel.cancelled() => None,
2648            r = self.model.complete(ctx).instrument(span.clone()) => Some(r),
2649        };
2650        finish_chat(
2651            &span,
2652            &info,
2653            started,
2654            result
2655                .as_ref()
2656                .map(|r| r.as_ref().map_err(|e| e.to_string())),
2657        );
2658        ctx.tools = saved_tools;
2659
2660        let Some(result) = result else {
2661            // Drop the synthesis prompt pushed above. Nothing answered it, and
2662            // leaving it would hand the next reader of this context a dangling
2663            // user turn.
2664            ctx.history.pop();
2665            return Synthesis::Cancelled;
2666        };
2667
2668        match result {
2669            Ok(out) => {
2670                self.hooks.fire(&Event::PostModel { out: &out }, world);
2671                total_usage.input_tokens += out.usage.input_tokens;
2672                total_usage.output_tokens += out.usage.output_tokens;
2673                total_usage.cached_input_tokens += out.usage.cached_input_tokens;
2674                total_usage.cache_write_input_tokens += out.usage.cache_write_input_tokens;
2675                ctx.push_model_output(&out);
2676                Synthesis::Text(out.text)
2677            }
2678            Err(_) => Synthesis::Text(None),
2679        }
2680    }
2681}
2682
2683/// What the forced final synthesis produced.
2684enum Synthesis {
2685    /// The model answered (or errored — errors are swallowed, see the fn doc).
2686    Text(Option<String>),
2687    /// The run's token fired before or during the call; no text was produced
2688    /// and nothing was pushed to the context.
2689    Cancelled,
2690}
2691
2692/// A persistent multi-turn conversation over one [`AgentLoop`].
2693///
2694/// Holds the append-only history and, on each [`turn`](Session::turn), re-runs
2695/// the loop against a **stable prefix** (system + name-sorted tool schemas).
2696/// That byte-stable prefix is what lets a provider's prefix cache hit across
2697/// turns — the difference between paying full price to re-read the same context
2698/// every round and paying ~10% for the cached bytes (DeepSeek).
2699pub struct Session<'a, M: Model> {
2700    loop_: &'a AgentLoop<M>,
2701    history: Vec<Turn>,
2702    max_iters: u32,
2703}
2704
2705impl<'a, M: Model> Session<'a, M> {
2706    pub fn with_max_iters(mut self, n: u32) -> Self {
2707        self.max_iters = n;
2708        self
2709    }
2710    /// Preload prior turns (e.g. resumed from disk).
2711    pub fn with_seed(mut self, seed: Vec<Turn>) -> Self {
2712        self.history = seed;
2713        self
2714    }
2715    /// The accumulated conversation so far.
2716    pub fn history(&self) -> &[Turn] {
2717        &self.history
2718    }
2719    /// Start over (branch): drop the accumulated turns.
2720    pub fn reset(&mut self) {
2721        self.history.clear();
2722    }
2723
2724    /// Send one user message. Runs the ReAct loop against the accumulated
2725    /// history, then appends this user turn + the assistant reply so the next
2726    /// turn extends the same cached prefix.
2727    pub async fn turn(
2728        &mut self,
2729        message: impl Into<String>,
2730        world: &mut World,
2731    ) -> Result<Outcome, HarnessError> {
2732        let message = message.into();
2733        let task = Task {
2734            description: message.clone(),
2735            source: None,
2736            deadline: None,
2737        };
2738        let outcome = self
2739            .loop_
2740            .run_with_seed_history(task, self.history.clone(), world, self.max_iters)
2741            .await?;
2742        let reply = match &outcome {
2743            Outcome::Done { text, .. } => text.clone().unwrap_or_default(),
2744            Outcome::BudgetExhausted { last_text, .. }
2745            | Outcome::Stuck { last_text, .. }
2746            | Outcome::Cancelled { last_text, .. } => last_text.clone().unwrap_or_default(),
2747        };
2748        self.history.push(Turn {
2749            role: TurnRole::User,
2750            blocks: vec![Block::Text(message)],
2751        });
2752        self.history.push(Turn {
2753            role: TurnRole::Assistant,
2754            blocks: vec![Block::Text(reply)],
2755        });
2756        Ok(outcome)
2757    }
2758}
2759
2760/// Audit #7: default safelist for `FixPatch::RunCommand`.
2761///
2762/// Sensors emitting `RunCommand` patches would otherwise be a silent
2763/// arbitrary-code-execution channel. We restrict the *program* by name to a
2764/// short list of well-known, side-effect-bounded formatters/fixers. Anything
2765/// else returns false and the patch is rejected (write your own `PreAutoFix`
2766/// hook returning `HookOutcome::Allow` to widen the policy).
2767///
2768/// `ReplaceFile` and `UnifiedDiff` are not restricted here — they only touch
2769/// files inside the workspace and are covered by the symlink-safe path
2770/// resolution in `harness-tools-fs`.
2771pub fn is_default_safe_fix(patch: &harness_core::FixPatch) -> bool {
2772    use harness_core::FixPatch;
2773    match patch {
2774        FixPatch::ReplaceFile { .. } | FixPatch::UnifiedDiff { .. } => true,
2775        FixPatch::RunCommand { program, args, .. } => match program.as_str() {
2776            // Cargo subcommands proven side-effect-bounded.
2777            "cargo" => matches!(
2778                args.first().map(String::as_str),
2779                Some("fmt" | "clippy" | "fix"),
2780            ),
2781            "rustfmt" | "gofmt" | "prettier" | "ruff" | "black" => true,
2782            _ => false,
2783        },
2784        // Future FixPatch variants: deny by default — review and add to the list above.
2785        _ => false,
2786    }
2787}
2788
2789/// Monotonic counter for `.harness-patch-*.diff` temp filenames — millisecond
2790/// resolution alone collides under parallel agent runs.
2791static PATCH_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2792
2793/// Monotonic counter for fallback recall session ids (no `uuid` dep).
2794static RECALL_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2795
2796/// Apply auto-fix patches; return short descriptions of those that succeeded.
2797///
2798/// Made `pub` (was `pub(crate)`) so integration tests can call it directly.
2799pub async fn apply_patches(patches: &[harness_core::FixPatch], world: &mut World) -> Vec<String> {
2800    use harness_core::FixPatch;
2801    let mut applied = Vec::new();
2802    for p in patches {
2803        match p {
2804            FixPatch::ReplaceFile { path, content } => {
2805                let abs = world.repo.root.join(path);
2806                if let Some(parent) = abs.parent() {
2807                    let _ = tokio::fs::create_dir_all(parent).await;
2808                }
2809                if tokio::fs::write(&abs, content).await.is_ok() {
2810                    applied.push(format!("replaced {}", path.display()));
2811                }
2812            }
2813            FixPatch::UnifiedDiff { diff } => {
2814                if try_apply_diff(world, diff).await {
2815                    applied.push("unified diff applied".into());
2816                }
2817            }
2818            FixPatch::RunCommand { program, args, cwd } => {
2819                let cwd_ref = cwd.as_deref().unwrap_or(world.repo.root.as_path());
2820                let args_ref: Vec<&str> = args.iter().map(String::as_str).collect();
2821                if let Ok(out) = world.runner.exec(program, &args_ref, Some(cwd_ref)).await
2822                    && out.status == 0
2823                {
2824                    applied.push(format!("ran `{program} {}`", args.join(" ")));
2825                }
2826            }
2827            // FixPatch is `#[non_exhaustive]`; unknown variants are skipped.
2828            _ => tracing::warn!("apply_patches: unknown FixPatch variant — skipped"),
2829        }
2830    }
2831    applied
2832}
2833
2834/// Write `diff` to a unique temp file and try `patch -p1` first, then `-p0`.
2835/// Returns whether either succeeded. The `-p1`-then-`-p0` order matches the
2836/// reality that most agent-emitted diffs are git-style (need `-p1`) but some
2837/// hand-rolled diffs use repo-relative paths (need `-p0`).
2838async fn try_apply_diff(world: &mut World, diff: &str) -> bool {
2839    use std::sync::atomic::Ordering;
2840    use tokio::io::AsyncWriteExt;
2841
2842    let seq = PATCH_SEQ.fetch_add(1, Ordering::SeqCst);
2843    let pid = std::process::id();
2844    let now = world.clock.now_ms();
2845    let tmp = world
2846        .repo
2847        .root
2848        .join(format!(".harness-patch-{pid}-{now}-{seq}.diff"));
2849
2850    let mut f = match tokio::fs::File::create(&tmp).await {
2851        Ok(f) => f,
2852        Err(e) => {
2853            tracing::warn!(error=%e, path=%tmp.display(), "could not create patch tempfile");
2854            return false;
2855        }
2856    };
2857    if let Err(e) = f.write_all(diff.as_bytes()).await {
2858        tracing::warn!(error=%e, "could not write patch tempfile");
2859        let _ = tokio::fs::remove_file(&tmp).await;
2860        return false;
2861    }
2862    drop(f);
2863
2864    let tmp_str = tmp.to_string_lossy().to_string();
2865    let mut applied = false;
2866    for strip in ["-p1", "-p0"] {
2867        match world
2868            .runner
2869            .exec(
2870                "patch",
2871                &[strip, "--silent", "-i", tmp_str.as_str()],
2872                Some(world.repo.root.as_path()),
2873            )
2874            .await
2875        {
2876            Ok(out) if out.status == 0 => {
2877                tracing::info!(strip, "patch applied");
2878                applied = true;
2879                break;
2880            }
2881            Ok(out) => {
2882                tracing::debug!(strip, stderr=%out.stderr, "patch failed; trying next strip level");
2883            }
2884            Err(e) => {
2885                tracing::warn!(error=%e, "patch command not available");
2886                break; // patch tool missing — no point trying other strip
2887            }
2888        }
2889    }
2890    let _ = tokio::fs::remove_file(&tmp).await;
2891    applied
2892}