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