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, or when `policy.max_iters` is hit.
10
11pub mod acceptance;
12pub mod goal;
13pub mod learning;
14pub mod memory_layer;
15#[cfg(feature = "otel")]
16pub mod otel;
17pub mod profile_guide;
18pub mod recall_layer;
19pub mod receipt;
20pub mod registry;
21pub mod seal;
22pub use acceptance::{Acceptance, FilesExist, NonEmptyAnswer, Verdict};
23pub use goal::{Goal, GoalStore, Phase, PhaseStatus};
24pub use receipt::{Receipt, ReceiptBuilder};
25pub use seal::{SealBreach, SealSet};
26pub mod replay;
27pub mod subagent;
28pub mod telemetry;
29
30pub use learning::*;
31pub use memory_layer::*;
32pub mod boundary_guide;
33pub use boundary_guide::*;
34pub use profile_guide::*;
35pub use recall_layer::*;
36pub use registry::*;
37pub use replay::*;
38pub use subagent::*;
39pub use telemetry::*;
40
41use harness_compactor::{CALIBRATION_KEY, DefaultCompactor};
42use harness_core::{
43 Action, Block, CompactionStage, Compactor, Context, Event, Guide, HarnessError, HookOutcome,
44 Model, ModelDelta, ModelOutput, ResponseFormat, Sensor, SessionSource, SignalSet, Stage,
45 StopReason, Task, ToolCall, ToolResult, Turn, TurnRole, Usage, World,
46};
47use harness_hooks::HookBus;
48use std::collections::HashMap;
49use std::sync::Arc;
50use std::time::Duration;
51
52/// Governs the loop's stuck-detector. When the model repeats the *same* tool
53/// call (name + args) round after round without making progress, the loop first
54/// nudges it to change approach, then terminates cleanly with [`Outcome::Stuck`]
55/// rather than burning the rest of the budget spinning on a loop.
56///
57/// Enabled by default with conservative thresholds — the calls must be
58/// *byte-identical*, so genuine "read the same file twice" work never trips it.
59#[derive(Debug, Clone)]
60pub struct StuckPolicy {
61 pub enabled: bool,
62 /// Consecutive identical tool-call rounds before injecting a "you are
63 /// repeating yourself, change your approach" feedback signal.
64 pub nudge_after: u32,
65 /// Consecutive identical rounds before terminating with [`Outcome::Stuck`].
66 pub abort_after: u32,
67}
68
69impl Default for StuckPolicy {
70 fn default() -> Self {
71 Self {
72 enabled: true,
73 nudge_after: 3,
74 abort_after: 6,
75 }
76 }
77}
78
79/// A ceiling on how much of one tool result reaches the context.
80///
81/// A single call can return more than the whole conversation: a lock file, a
82/// `SELECT *`, an MCP tool the framework does not control. Measured on a real
83/// run, "search these files for a word" cost 53,487 input tokens because one
84/// `read_file` returned a lock file — the model then paid for it on every
85/// subsequent turn, and compaction started throwing away real history to make
86/// room. A per-result ceiling is the only place to stop that: the tools cannot
87/// all be trusted (third-party MCP), and the compactor only runs after the
88/// damage is in the context.
89#[derive(Debug, Clone)]
90pub struct ToolResultPolicy {
91 /// Max serialized bytes of a single tool result. `None` disables the guard.
92 /// Default ~24 KiB — roughly 6k tokens of English, generous for a file page
93 /// or a query result, far below what blows a window.
94 pub max_bytes: Option<usize>,
95 /// Replace the payload of a read-only call that exactly repeats an earlier
96 /// one in the same run, when nothing has modified the world in between.
97 ///
98 /// [`StuckPolicy`] only sees *consecutive* identical rounds. Reading a file
99 /// at iteration 1 and again at iteration 5 is not that, and looks like
100 /// progress — but the same bytes land in the context twice and the model
101 /// learns nothing the second time. Measured on a real run, model wait was
102 /// 36.7s against 3ms of tool execution: a repeat costs context, not time,
103 /// so what is suppressed is the payload, not the call.
104 ///
105 /// Only `ToolRisk::ReadOnly` qualifies (`Network` is a separate risk, and an
106 /// external endpoint may answer differently), and any non-read-only call
107 /// clears the record — after a write, re-reading is the correct move.
108 ///
109 /// **Off by default, on the evidence.** Measured on the completion
110 /// benchmark: ceilings alone solved 6/6 tasks for 160k effective tokens;
111 /// adding repeat-suppression cut that to 32k — and lost a task. An agent
112 /// working through a file larger than one page re-reads it because it cannot
113 /// hold it, gets told it already has the answer, and does not: the content
114 /// was paged away. Five times cheaper is not worth a task a framework could
115 /// otherwise do, so this is opt-in for callers who would rather have the
116 /// tokens. (Suppressing from the *third* identical call rather than the
117 /// second would likely keep most of the saving without the failure — it
118 /// needs measuring before it becomes the default.)
119 pub dedupe_repeats: bool,
120 /// When a result exceeds `max_bytes`, save the *full* payload to a file
121 /// under `.harness/spill/` in the workspace and inline a bounded preview
122 /// plus the path, instead of cutting the tail off and throwing it away.
123 ///
124 /// Truncation destroys information: the model is told "narrow your
125 /// request", but the bytes it needed may be exactly the ones dropped, and
126 /// the only recovery is re-running the call to be truncated again.
127 /// Measured on the completion benchmark, that loop is visible as a single
128 /// task paying 184k input tokens. Spilling keeps the ceiling — the context
129 /// gets a preview, never the flood — while the whole result stays
130 /// retrievable through the file tools the agent already has (`read_file`
131 /// with offset/limit, `grep` on the spill path), because the spill lives
132 /// inside the workspace jail. Borrowed from DeepSeek Harness's `spill`
133 /// family (preview + retrieval locator), which is the same judgement.
134 ///
135 /// Costs nothing until it fires: the write happens only on the oversized
136 /// path, which the default ceiling makes rare. When the write fails (e.g.
137 /// read-only workspace) the guard falls back to plain truncation.
138 pub spill: bool,
139}
140
141impl Default for ToolResultPolicy {
142 fn default() -> Self {
143 Self {
144 max_bytes: Some(24 * 1024),
145 dedupe_repeats: false,
146 spill: true,
147 }
148 }
149}
150
151/// Governs *when* and *how far* the loop compacts context. Hysteresis: only
152/// start compacting once usage crosses `high_water`, and stop as soon as it's
153/// back under `target` — instead of running every stage above a threshold on
154/// every turn. This avoids over-compacting (needlessly reaching the lossy,
155/// main-model `AutoCompact` stage) and, because compaction rewrites history and
156/// invalidates the provider prefix cache, avoids nibbling the context every
157/// single turn.
158#[derive(Debug, Clone)]
159pub struct CompactPolicy {
160 /// Start compacting when `used/window` exceeds this. Default 0.75.
161 pub high_water: f32,
162 /// Stop as soon as `used/window` is back at/under this. Default 0.55.
163 pub target: f32,
164}
165
166impl Default for CompactPolicy {
167 fn default() -> Self {
168 Self {
169 high_water: 0.75,
170 target: 0.55,
171 }
172 }
173}
174
175/// Inline preview size for a spilled result. Deliberately smaller than the
176/// ceiling: the point of spilling is that the context gets a *glimpse* and a
177/// path, not four-fifths of the flood.
178const SPILL_PREVIEW_BYTES: usize = 4 * 1024;
179
180/// First `n` bytes of `s`, cut on a char boundary.
181fn head_of(s: &str, n: usize) -> &str {
182 let mut end = n.min(s.len());
183 while end > 0 && !s.is_char_boundary(end) {
184 end -= 1;
185 }
186 &s[..end]
187}
188
189/// The string field that dominates an oversized result, if one does.
190///
191/// Most oversized results are one big string in a small envelope — a file
192/// body, a command's stdout — and the right spill for those is the *raw text*:
193/// multi-line, so `read_file`'s line paging and `grep`'s line matching work on
194/// it. Spilling the serialized JSON instead would fold the whole payload onto
195/// one escaped line that line-oriented tools can neither page nor match
196/// (`read_file` pages by line; a 68 KB single-line file is unreachable past
197/// the first 16 KB). Returns the dotted path and the string when one field is
198/// ≥ 80% of the serialized size.
199fn dominant_string(v: &serde_json::Value, total: usize) -> Option<(String, &str)> {
200 fn walk<'a>(v: &'a serde_json::Value, path: &str, best: &mut Option<(String, &'a str)>) {
201 match v {
202 serde_json::Value::String(s) => {
203 if best.as_ref().is_none_or(|(_, b)| s.len() > b.len()) {
204 *best = Some((path.to_string(), s.as_str()));
205 }
206 }
207 serde_json::Value::Object(m) => {
208 for (k, x) in m {
209 let p = if path.is_empty() {
210 k.clone()
211 } else {
212 format!("{path}.{k}")
213 };
214 walk(x, &p, best);
215 }
216 }
217 serde_json::Value::Array(a) => {
218 for (i, x) in a.iter().enumerate() {
219 walk(x, &format!("{path}[{i}]"), best);
220 }
221 }
222 _ => {}
223 }
224 }
225 let mut best = None;
226 walk(v, "", &mut best);
227 best.filter(|(_, s)| s.len() * 5 >= total * 4)
228}
229
230/// Replace the value at a `dominant_string` dotted path with `with`.
231fn replace_at(v: &mut serde_json::Value, path: &str, with: serde_json::Value) {
232 let mut cur = v;
233 let mut rest = path;
234 loop {
235 // Next segment: `key`, `key[i]`, or a bare `[i]`.
236 let (seg, tail) = match rest.find('.') {
237 Some(dot) => (&rest[..dot], &rest[dot + 1..]),
238 None => (rest, ""),
239 };
240 let (key, idx) = match seg.find('[') {
241 Some(b) => (&seg[..b], seg[b + 1..seg.len() - 1].parse::<usize>().ok()),
242 None => (seg, None),
243 };
244 if !key.is_empty() {
245 match cur.get_mut(key) {
246 Some(next) => cur = next,
247 None => return,
248 }
249 }
250 if let Some(i) = idx {
251 match cur.get_mut(i) {
252 Some(next) => cur = next,
253 None => return,
254 }
255 }
256 if tail.is_empty() {
257 *cur = with;
258 return;
259 }
260 rest = tail;
261 }
262}
263
264/// Persist an oversized result under `.harness/spill/` in the workspace and
265/// build the inline marker. `None` on any IO failure — the caller falls back
266/// to truncation, because a guard that can error a run to protect a context
267/// window has its priorities backwards.
268fn spill_oversized(
269 action: &Action,
270 content: &serde_json::Value,
271 serialized: &str,
272 root: &std::path::Path,
273) -> Option<serde_json::Value> {
274 let dir = root.join(".harness").join("spill");
275 std::fs::create_dir_all(&dir).ok()?;
276 let id: String = action
277 .call_id
278 .chars()
279 .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
280 .take(48)
281 .collect();
282 let id = if id.is_empty() { "call".into() } else { id };
283
284 let (rel, preview, meta) = match dominant_string(content, serialized.len()) {
285 // One big string in a small envelope: spill the raw text, keep the
286 // envelope inline with the big field swapped for a pointer.
287 Some((field, text)) => {
288 let rel = format!(".harness/spill/{id}-{}.txt", action.tool);
289 std::fs::write(root.join(&rel), text).ok()?;
290 let mut meta = content.clone();
291 replace_at(
292 &mut meta,
293 &field,
294 serde_json::Value::String(format!("[{} bytes spilled to {rel}]", text.len())),
295 );
296 (
297 rel,
298 head_of(text, SPILL_PREVIEW_BYTES).to_string(),
299 Some(meta),
300 )
301 }
302 // Structured payload (e.g. a long match list): spill pretty-printed,
303 // one element per line, so line-oriented retrieval still works.
304 None => {
305 let rel = format!(".harness/spill/{id}-{}.json", action.tool);
306 let pretty =
307 serde_json::to_string_pretty(content).unwrap_or_else(|_| serialized.to_string());
308 std::fs::write(root.join(&rel), &pretty).ok()?;
309 (rel, head_of(&pretty, SPILL_PREVIEW_BYTES).to_string(), None)
310 }
311 };
312 tracing::warn!(
313 target: "harness.telemetry",
314 event = "tool.result.spilled",
315 "gen_ai.tool.name" = %action.tool,
316 bytes = serialized.len(),
317 path = %rel,
318 );
319 let mut marker = serde_json::json!({
320 "spilled": true,
321 "tool": action.tool,
322 "bytes_total": serialized.len(),
323 "path": rel,
324 "preview": preview,
325 "note": format!(
326 "This result was {} bytes — too large to inline, so the FULL content was \
327 saved to '{rel}' (workspace-relative). Nothing was lost. Retrieve exactly \
328 the part you need: grep(path=\"{rel}\", pattern=...) or \
329 read_file(path=\"{rel}\", offset=..., limit=...). Do not repeat the \
330 original call — it will spill again.",
331 serialized.len()
332 ),
333 });
334 // The envelope metadata (paths, flags) rides along when it is small; a
335 // pathological envelope that is itself oversized is dropped, not inlined.
336 if let Some(meta) = meta
337 && meta.to_string().len() <= SPILL_PREVIEW_BYTES
338 {
339 marker["meta"] = meta;
340 }
341 Some(marker)
342}
343
344/// A stable fingerprint of a round's tool calls (names + args, ignoring the
345/// volatile call id). Two rounds with the same fingerprint asked for the exact
346/// same actions — the signal the stuck-detector keys on.
347fn tool_call_fingerprint(calls: &[ToolCall]) -> String {
348 calls
349 .iter()
350 .map(|c| format!("{}({})", c.name, c.args))
351 .collect::<Vec<_>>()
352 .join("|")
353}
354
355/// Where a run finished. Each variant is `#[non_exhaustive]` so new *fields*
356/// don't break downstream matches — always include `..` when destructuring.
357#[derive(Debug, Clone)]
358pub enum Outcome {
359 /// Model returned text with no tool calls (natural end).
360 #[non_exhaustive]
361 Done {
362 text: Option<String>,
363 iters: u32,
364 tools_called: u32,
365 usage: harness_core::Usage,
366 /// What the acceptance checks said. `None` means nothing was asked —
367 /// so "the model stopped" is all this outcome claims.
368 verified: Option<Verdict>,
369 /// The sealed contract as it stood before the model's first turn.
370 ///
371 /// Carried out of the run because a receipt has to say *what* was
372 /// measured, not only that the measurement held. Empty when nothing
373 /// was sealed.
374 contract: crate::seal::SealSet,
375 /// Set when a sealed acceptance contract changed during the run.
376 ///
377 /// Distinct from a plain failed `verified` because the two mean
378 /// different things to a caller: a failed check is work not finished,
379 /// this is the measuring instrument having been moved. A host may want
380 /// to fail a build on the first and page someone on the second.
381 seal_breach: Option<String>,
382 },
383 /// Policy budget exhausted before the model stopped requesting tools.
384 /// Carries everything we know so the caller can recover partial work
385 /// (saved notes, files written by tools, the last assistant text, etc.)
386 /// instead of seeing a single bare "budget out" string.
387 #[non_exhaustive]
388 BudgetExhausted {
389 iters: u32,
390 last_text: Option<String>,
391 tools_called: u32,
392 usage: harness_core::Usage,
393 },
394 /// The agent got stuck: it repeated the *same* tool call for
395 /// `StuckPolicy::abort_after` consecutive rounds without progress, so the
396 /// loop terminated early to save the rest of the budget. Carries partial
397 /// work (last text, files already written by tools) like `BudgetExhausted`.
398 #[non_exhaustive]
399 Stuck {
400 /// Human-readable reason, e.g. "repeated `read_file(...)` 6× without progress".
401 reason: String,
402 /// How many consecutive identical rounds were observed.
403 repeated: u32,
404 iters: u32,
405 last_text: Option<String>,
406 tools_called: u32,
407 usage: harness_core::Usage,
408 },
409}
410
411/// The agent loop.
412pub struct AgentLoop<M: Model> {
413 pub model: M,
414 pub tools: ToolRegistry,
415 pub guides: Vec<Arc<dyn Guide>>,
416 pub sensors: Vec<Arc<dyn Sensor>>,
417 pub hooks: HookBus,
418 pub compactor: Arc<dyn Compactor>,
419 /// A deadline on each individual tool call. One hung call — a network tool
420 /// on a dead endpoint, a shell command waiting on stdin — otherwise takes
421 /// the whole run down with it, and the host's only recourse is a run-level
422 /// timeout that throws away every turn of finished work (measured on the
423 /// completion benchmark: a run that had already done the job was billed as
424 /// a 0-token timeout). A per-call deadline converts the hang into an error
425 /// *result* the model sees and can route around. `None` disables. The
426 /// default is generous — 120s covers a slow build — because a false
427 /// deadline on a legitimately long tool is worse than a late one.
428 pub tool_timeout: Option<Duration>,
429 /// Default response format applied to every run unless overridden by
430 /// `run_typed`. See [`ResponseFormat`].
431 pub response_format: ResponseFormat,
432 /// When `true`, the loop drives each model turn via `Model::stream()`
433 /// instead of `complete()`, firing `Event::ModelTokenDelta` for each
434 /// text fragment. Tool-call deltas are still assembled inside the loop;
435 /// only the terminal `ModelOutput` shape is observable downstream.
436 pub streaming: bool,
437 /// Optional cross-session recall store. When set, the loop captures every
438 /// turn and the `session_search` tool is registered. See `with_recall`.
439 pub recall: Option<Arc<dyn harness_core::RecallStore>>,
440 /// When true (and `recall` is set), a `RecallGuide` auto-injects top-k
441 /// past context at session start.
442 pub recall_auto_inject: bool,
443 pub learning: Option<LearningConfig>,
444 /// Loop-detection policy. Enabled by default — see [`StuckPolicy`].
445 pub stuck: StuckPolicy,
446 /// Context-compaction hysteresis. See [`CompactPolicy`].
447 pub compaction: CompactPolicy,
448 /// Ceiling on a single tool result. See [`ToolResultPolicy`].
449 pub tool_results: ToolResultPolicy,
450 /// Conditions the run must satisfy before the loop reports success. The
451 /// model stopping is evidence it *believes* it is finished; these say
452 /// whether it is. See [`acceptance`].
453 pub acceptance: Vec<Arc<dyn Acceptance>>,
454 /// How many times a failed acceptance is handed back to the model before
455 /// the loop gives up and reports what there is. One is usually enough: a
456 /// model that ignores the first correction rarely takes the second.
457 pub acceptance_retries: u32,
458 /// System instruction injected into every run's `Context.system` (unless the
459 /// built context already carries its own). Set via [`with_system`](Self::with_system).
460 pub system: Vec<Block>,
461 /// Named auxiliary models for side tasks — compaction, memory synthesis,
462 /// judging, subagents — so the main conversation stays on one model (and
463 /// keeps its provider prompt-cache prefix intact) while cheap or specialist
464 /// work goes elsewhere. Populated via [`with_model_role`](Self::with_model_role),
465 /// read via [`model_for`](Self::model_for). An unregistered role means
466 /// "use the main model" — components fall back rather than fail.
467 pub model_roles: std::collections::HashMap<String, Arc<dyn Model>>,
468 /// True once the host installed its own compactor via
469 /// [`with_compactor`](Self::with_compactor). Guards the `"compactor"`
470 /// model-role convenience from overwriting an explicit choice.
471 pub compactor_custom: bool,
472}
473
474impl AgentLoop<harness_core::DynModel> {
475 /// Build a loop from a boxed model — what every model factory hands back
476 /// (`ApiKind::build`, a router, anything stored behind a trait object).
477 ///
478 /// `Arc<dyn Model>` deliberately does not implement `Model` (see
479 /// [`DynModel`](harness_core::DynModel) for why), so `AgentLoop::new` cannot
480 /// take one. Without this constructor every caller writes the wrapper
481 /// themselves, and the first thing a new user meets is a trait-bound error
482 /// naming a type they have never heard of.
483 ///
484 /// ```ignore
485 /// let model = ApiKind::OpenAI.build(base_url, model_id, key);
486 /// let agent = AgentLoop::boxed(model).with_tool(Arc::new(ReadFile));
487 /// ```
488 pub fn boxed(model: Arc<dyn Model>) -> Self {
489 Self::new(harness_core::DynModel(model))
490 }
491}
492
493impl<M: Model> AgentLoop<M> {
494 pub fn new(model: M) -> Self {
495 Self {
496 model,
497 tools: ToolRegistry::new(),
498 guides: Vec::new(),
499 sensors: Vec::new(),
500 hooks: HookBus::new(),
501 compactor: Arc::new(DefaultCompactor::new()),
502 tool_timeout: Some(Duration::from_secs(120)),
503 response_format: ResponseFormat::Free,
504 streaming: false,
505 recall: None,
506 recall_auto_inject: false,
507 learning: None,
508 stuck: StuckPolicy::default(),
509 compaction: CompactPolicy::default(),
510 // On by default, because the failure it catches is invisible: a
511 // turn that produced nothing is reported as a turn that finished.
512 tool_results: ToolResultPolicy::default(),
513 acceptance: vec![Arc::new(acceptance::NonEmptyAnswer)],
514 acceptance_retries: 1,
515 system: Vec::new(),
516 model_roles: std::collections::HashMap::new(),
517 compactor_custom: false,
518 }
519 }
520
521 /// Register an auxiliary model under a role name — the loop's seam for
522 /// "side tasks don't have to run on the main model".
523 ///
524 /// The main conversation stays pinned to one model, which keeps its
525 /// provider prompt-cache prefix byte-stable; compaction summaries, memory
526 /// synthesis, judging, and subagents can go to a cheaper or specialist
527 /// model instead. Components read roles via [`model_for`](Self::model_for)
528 /// and fall back to the main model when a role is unregistered.
529 ///
530 /// One role is wired automatically: registering `"compactor"` upgrades the
531 /// default structural compactor to a [`ModelBackedCompactor`] on that
532 /// model — unless the host already installed its own via
533 /// [`with_compactor`](Self::with_compactor), which always wins regardless
534 /// of call order.
535 ///
536 /// ```ignore
537 /// let agent = AgentLoop::boxed(main)
538 /// .with_model_role("compactor", cheap.clone())
539 /// .with_model_role("judge", strong);
540 /// ```
541 pub fn with_model_role(mut self, role: impl Into<String>, model: Arc<dyn Model>) -> Self {
542 let role = role.into();
543 if role == "compactor" && !self.compactor_custom {
544 self.compactor = Arc::new(harness_compactor::ModelBackedCompactor::new(model.clone()));
545 }
546 self.model_roles.insert(role, model);
547 self
548 }
549
550 /// Look up an auxiliary model by role. `None` means "no model registered
551 /// for this role — use the main model"; callers fall back rather than fail,
552 /// so wiring stays optional everywhere.
553 pub fn model_for(&self, role: &str) -> Option<Arc<dyn Model>> {
554 self.model_roles.get(role).cloned()
555 }
556
557 /// Set a system instruction applied to every run (into `Context.system`) —
558 /// e.g. "answer only via the governed tools; never claim you can't access
559 /// data; never invent numbers". This is the first-class seam for a system
560 /// prompt; small local models in particular need it to reliably call tools
561 /// instead of refusing or hallucinating.
562 pub fn with_system(mut self, text: impl Into<String>) -> Self {
563 self.system = vec![Block::Text(text.into())];
564 self
565 }
566
567 /// Override the loop-detection policy (thresholds, or disable entirely).
568 pub fn with_stuck_policy(mut self, policy: StuckPolicy) -> Self {
569 self.stuck = policy;
570 self
571 }
572
573 /// Override the compaction hysteresis policy. See [`CompactPolicy`].
574 /// Set the ceiling on a single tool result. See [`ToolResultPolicy`].
575 pub fn with_tool_result_policy(mut self, policy: ToolResultPolicy) -> Self {
576 self.tool_results = policy;
577 self
578 }
579
580 pub fn with_compact_policy(mut self, policy: CompactPolicy) -> Self {
581 self.compaction = policy;
582 self
583 }
584
585 /// Opt in to streaming the model's terminal turn token-by-token via
586 /// `Model::stream()`. Hooks subscribed to `Event::ModelTokenDelta` see
587 /// each fragment as it arrives; the rest of the loop is unchanged.
588 pub fn with_streaming(mut self, enable: bool) -> Self {
589 self.streaming = enable;
590 self
591 }
592
593 /// Add a condition the run must satisfy before it can report success.
594 pub fn with_acceptance(mut self, a: Arc<dyn Acceptance>) -> Self {
595 self.acceptance.push(a);
596 self
597 }
598
599 /// Replace the acceptance set outright (including the default).
600 pub fn with_acceptance_set(mut self, set: Vec<Arc<dyn Acceptance>>) -> Self {
601 self.acceptance = set;
602 self
603 }
604
605 pub fn with_acceptance_retries(mut self, n: u32) -> Self {
606 self.acceptance_retries = n;
607 self
608 }
609
610 pub fn with_tool_timeout(mut self, t: Option<Duration>) -> Self {
611 self.tool_timeout = t;
612 self
613 }
614
615 pub fn with_compactor(mut self, c: Arc<dyn Compactor>) -> Self {
616 self.compactor = c;
617 // An explicit compactor always wins over the "compactor" model-role
618 // convenience, in either call order.
619 self.compactor_custom = true;
620 self
621 }
622
623 pub fn with_tool(mut self, t: Arc<dyn harness_core::Tool>) -> Self {
624 self.tools.insert(t);
625 self
626 }
627
628 pub fn with_guide(mut self, g: Arc<dyn Guide>) -> Self {
629 self.guides.push(g);
630 self
631 }
632
633 pub fn with_sensor(mut self, s: Arc<dyn Sensor>) -> Self {
634 self.sensors.push(s);
635 self
636 }
637
638 pub fn with_hook(mut self, h: Arc<dyn harness_core::Hook>) -> Self {
639 self.hooks.register(h);
640 self
641 }
642
643 /// Pull in every `#[hook]`-registered hook.
644 pub fn with_macro_hooks(mut self) -> Self {
645 self.hooks = self.hooks.with_macro_hooks_take();
646 self
647 }
648
649 /// Enable cross-session recall: capture every turn into `store` and
650 /// register the `session_search` tool. Owner + session id are read from
651 /// `world.profile.extra["recall_owner"|"recall_session"]` at run time.
652 pub fn with_recall(mut self, store: Arc<dyn harness_core::RecallStore>) -> Self {
653 self.tools
654 .insert(Arc::new(crate::SessionSearchTool::new(store.clone())));
655 self.recall = Some(store);
656 self
657 }
658
659 /// Capture every turn into `store` **without** registering a search tool.
660 ///
661 /// Ingest and retrieval are separate concerns that [`with_recall`] happens
662 /// to bundle, and the bundling is a trap: capture only ever happens when
663 /// `self.recall` is set, so a host that wants a different search tool — one
664 /// scoped per tenant, or one that copes with a language the backend's index
665 /// does not — has no way to get the writes without also getting
666 /// `session_search`, and ends up offering the model two overlapping tools
667 /// to choose between.
668 ///
669 /// Use this, then register whichever retrieval tool suits the deployment.
670 pub fn with_recall_ingest(mut self, store: Arc<dyn harness_core::RecallStore>) -> Self {
671 self.recall = Some(store);
672 self
673 }
674
675 /// After `with_recall`, also auto-inject top-k relevant past context at
676 /// session start (off by default — tool-only is prompt-cache friendly).
677 pub fn auto_inject(mut self) -> Self {
678 self.recall_auto_inject = true;
679 self
680 }
681
682 /// Enable the self-evolving learning loop: after a session that made
683 /// `>= cfg.nudge_interval` tool calls, fork a review subagent (white-listed to
684 /// `cfg.tools`) to update skills + memory from the transcript. Best-effort.
685 pub fn with_learning_loop(mut self, cfg: LearningConfig) -> Self {
686 self.learning = Some(cfg);
687 self
688 }
689
690 /// Set the default response format for all runs through this loop. See
691 /// [`ResponseFormat`]. For typed deserialisation, prefer `run_typed::<T>()`.
692 pub fn with_response_format(mut self, fmt: ResponseFormat) -> Self {
693 self.response_format = fmt;
694 self
695 }
696
697 /// Shortcut for `with_response_format(ResponseFormat::JsonSchema { name, schema })`.
698 /// Accepts a raw `serde_json::Value` so callers can hand-roll the schema or
699 /// pull it from `schemars::schema_for!(T)`.
700 pub fn with_response_schema(self, name: impl Into<String>, schema: serde_json::Value) -> Self {
701 self.with_response_format(ResponseFormat::JsonSchema {
702 name: name.into(),
703 schema,
704 })
705 }
706
707 pub async fn run(&self, task: Task, world: &mut World) -> Result<Outcome, HarnessError> {
708 let max = harness_core::Policy::default().max_iters;
709 self.run_with_max_iters(task, world, max).await
710 }
711
712 /// Run, and hand back the evidence alongside the result.
713 ///
714 /// The [`Receipt`] is built here rather than by the caller because the loop
715 /// already knows the two things a caller would otherwise have to restate —
716 /// the task and the model — and restating them is how a receipt ends up
717 /// describing a different run than the one that happened. `now_ms` stays a
718 /// parameter: this crate does not read the clock, so a receipt is
719 /// reproducible in a test.
720 pub async fn run_receipted(
721 &self,
722 task: Task,
723 world: &mut World,
724 now_ms: i64,
725 ) -> Result<(Outcome, Receipt), HarnessError> {
726 let description = task.description.clone();
727 let handle = self.model.info().handle;
728 let outcome = self.run(task, world).await?;
729 let receipt = ReceiptBuilder::new(description, handle, now_ms).build(&outcome);
730 Ok((outcome, receipt))
731 }
732
733 /// Advance a [`Goal`] by one phase, recording the result durably.
734 ///
735 /// Returns `None` when every phase is done — so a resume loop is
736 /// `while let Some(..) = loop_.run_goal(..).await?`.
737 ///
738 /// The phase is marked `Running` and **saved before the model starts**, so
739 /// a process that dies mid-run leaves a goal that says where it was rather
740 /// than one that looks untouched. It is saved again afterwards on both
741 /// paths. That second save on the failure path is the whole reason this
742 /// method exists: written out by hand at each call site it is four lines,
743 /// and the failure branch is the one that gets forgotten — which loses
744 /// exactly the run you most wanted a record of.
745 pub async fn run_goal(
746 &self,
747 goal: &mut Goal,
748 store: &GoalStore,
749 world: &mut World,
750 now_ms: i64,
751 ) -> Result<Option<(Outcome, Receipt)>, HarnessError> {
752 let Some(i) = goal.start_current(now_ms) else {
753 return Ok(None);
754 };
755 let _ = store.save(goal);
756
757 let task = Task {
758 description: goal.brief(),
759 source: None,
760 deadline: None,
761 };
762 let result = self.run_receipted(task, world, now_ms).await;
763
764 match &result {
765 Ok((_, receipt)) => {
766 if receipt.passed {
767 goal.finish(i, receipt.summary(), now_ms);
768 } else {
769 goal.fail(i, receipt.summary(), now_ms);
770 }
771 }
772 // A run that errored outright still happened, and the goal has to
773 // say so or a resume will retry it as though it were untouched.
774 Err(e) => goal.fail(i, format!("the run errored: {e}"), now_ms),
775 }
776 let _ = store.save(goal);
777
778 result.map(Some)
779 }
780
781 pub async fn run_with_max_iters(
782 &self,
783 task: Task,
784 world: &mut World,
785 max_iters: u32,
786 ) -> Result<Outcome, HarnessError> {
787 self.run_with_seed_history(task, Vec::new(), world, max_iters)
788 .await
789 }
790
791 /// Run the agent and deserialise the terminal reply into `T`.
792 ///
793 /// The schema for `T` is derived via `schemars::schema_for!(T)` and
794 /// installed as `ResponseFormat::JsonSchema` for this run only — any
795 /// pre-existing `self.response_format` is ignored. On success the
796 /// returned `T` is parsed from `Outcome::Done.text` (or, on budget
797 /// exhaustion, from `Outcome::BudgetExhausted.last_text`).
798 ///
799 /// Errors:
800 /// - `HarnessError::Other` if the model returns no text at all
801 /// - `HarnessError::Other` if `serde_json::from_str::<T>(text)` fails —
802 /// the original text is included in the message for debugging.
803 pub async fn run_typed<T>(&self, task: Task, world: &mut World) -> Result<T, HarnessError>
804 where
805 T: serde::de::DeserializeOwned + schemars::JsonSchema + 'static,
806 {
807 let max = harness_core::Policy::default().max_iters;
808 self.run_typed_with_max_iters::<T>(task, world, max).await
809 }
810
811 /// Like `run_typed` but with explicit `max_iters`.
812 pub async fn run_typed_with_max_iters<T>(
813 &self,
814 task: Task,
815 world: &mut World,
816 max_iters: u32,
817 ) -> Result<T, HarnessError>
818 where
819 T: serde::de::DeserializeOwned + schemars::JsonSchema + 'static,
820 {
821 let schema_root = schemars::schema_for!(T);
822 let schema = serde_json::to_value(&schema_root)
823 .map_err(|e| HarnessError::Other(format!("response schema: {e}")))?;
824 let name = std::any::type_name::<T>()
825 .rsplit("::")
826 .next()
827 .unwrap_or("response")
828 .to_string();
829 let fmt = ResponseFormat::JsonSchema { name, schema };
830 let outcome = self
831 .run_with_response_format(task, world, max_iters, fmt)
832 .await?;
833 let text = match outcome {
834 Outcome::Done { text: Some(t), .. }
835 | Outcome::BudgetExhausted {
836 last_text: Some(t), ..
837 }
838 | Outcome::Stuck {
839 last_text: Some(t), ..
840 } => t,
841 Outcome::Done { text: None, .. } => {
842 return Err(HarnessError::Other(
843 "run_typed: model returned no text".into(),
844 ));
845 }
846 Outcome::Stuck {
847 last_text: None, ..
848 } => {
849 return Err(HarnessError::Other(
850 "run_typed: agent stuck with no text".into(),
851 ));
852 }
853 Outcome::BudgetExhausted {
854 last_text: None, ..
855 } => {
856 return Err(HarnessError::Other(
857 "run_typed: budget exhausted with no text".into(),
858 ));
859 }
860 };
861 serde_json::from_str::<T>(&text).map_err(|e| {
862 HarnessError::Other(format!(
863 "run_typed: decode {} failed: {e} — raw text was: {text}",
864 std::any::type_name::<T>()
865 ))
866 })
867 }
868
869 /// Run with a one-off `ResponseFormat` override (doesn't touch `self`).
870 pub async fn run_with_response_format(
871 &self,
872 task: Task,
873 world: &mut World,
874 max_iters: u32,
875 fmt: ResponseFormat,
876 ) -> Result<Outcome, HarnessError> {
877 // Borrow checker won't let us swap `self.response_format` because
878 // `self` is `&`. Easiest workaround: hand-roll the same setup that
879 // `run_with_seed_history` does, but with our `fmt`. We do this by
880 // calling through a private helper.
881 self.run_with_seed_history_and_format(task, Vec::new(), world, max_iters, Some(fmt))
882 .await
883 }
884
885 async fn run_with_seed_history_and_format(
886 &self,
887 task: Task,
888 seed: Vec<Turn>,
889 world: &mut World,
890 max_iters: u32,
891 fmt_override: Option<ResponseFormat>,
892 ) -> Result<Outcome, HarnessError> {
893 let mut ctx = Context::new(task);
894 ctx.policy.max_iters = max_iters;
895 ctx.tools = self.tools.schemas();
896 ctx.history = seed;
897 ctx.response_format = fmt_override.unwrap_or_else(|| self.response_format.clone());
898 self.run_built_context(ctx, world).await
899 }
900
901 /// Like `run_with_max_iters` but seeds `ctx.history` with `seed` **before**
902 /// the current user task is appended. Use this for multi-turn REPLs so
903 /// prior conversation lives in `ctx.history` (where the Compactor can see
904 /// it) instead of being concatenated into `task.description` (where it
905 /// previously bypassed compaction entirely — see audit #2).
906 pub async fn run_with_seed_history(
907 &self,
908 task: Task,
909 seed: Vec<Turn>,
910 world: &mut World,
911 max_iters: u32,
912 ) -> Result<Outcome, HarnessError> {
913 self.run_with_seed_and_metadata(task, seed, Default::default(), world, max_iters)
914 .await
915 }
916
917 /// Like [`run_with_seed_history`](Self::run_with_seed_history) but also seeds
918 /// `ctx.metadata` with per-request key/values. Hooks and a
919 /// [`ModelRouter`](harness_models::ModelRouter) read this map — e.g.
920 /// `audit.actor` / `audit.session` for the audit trail, or
921 /// `router.keep_local` to pin a request to the local model. This is the
922 /// entry point a serving layer uses to pass caller identity and routing
923 /// flags into a single, shared, reused loop.
924 pub async fn run_with_seed_and_metadata(
925 &self,
926 task: Task,
927 seed: Vec<Turn>,
928 metadata: std::collections::BTreeMap<String, serde_json::Value>,
929 world: &mut World,
930 max_iters: u32,
931 ) -> Result<Outcome, HarnessError> {
932 let mut ctx = Context::new(task);
933 ctx.policy.max_iters = max_iters;
934 ctx.tools = self.tools.schemas();
935 ctx.history = seed;
936 ctx.metadata = metadata;
937 ctx.response_format = self.response_format.clone();
938 self.run_built_context(ctx, world).await
939 }
940
941 /// Start a persistent multi-turn [`Session`]. Each `turn` re-runs the loop
942 /// against the accumulated history with a **stable prefix** (system +
943 /// name-sorted tool schemas), so a provider's prefix cache (e.g. DeepSeek's,
944 /// ~10% price on cache-hit tokens) hits across turns instead of paying full
945 /// price to re-read the same bytes every round. For maximum hit rate, keep
946 /// your guides' output stable (put per-turn volatile context in the message,
947 /// not a recomputed system guide).
948 pub fn session(&self) -> Session<'_, M> {
949 Session {
950 loop_: self,
951 history: Vec::new(),
952 max_iters: harness_core::Policy::default().max_iters,
953 }
954 }
955
956 /// Inner ReAct loop on an already-prepared `Context`. Use the public
957 /// `run*` methods unless you need to inject a non-standard `Context`
958 /// (e.g. `run_with_response_format` does to apply a one-off
959 /// `ResponseFormat` without mutating `self`).
960 async fn run_built_context(
961 &self,
962 mut ctx: Context,
963 world: &mut World,
964 ) -> Result<Outcome, HarnessError> {
965 if ctx.system.is_empty() && !self.system.is_empty() {
966 ctx.system = self.system.clone();
967 }
968
969 // Size the context budget to the model actually in use.
970 //
971 // Compaction fires at a fraction of `max_input_tokens`, so a value
972 // unrelated to the model is wrong in one of two directions: too high and
973 // the provider rejects the request before the compactor ever runs (a 32k
974 // model under the 150k default would need 112,500 tokens to trigger, and
975 // it cannot hold that many); too low and the loop discards history it
976 // could have kept. Nothing read `ModelInfo::context_window` before this —
977 // the framework's own defaults disagreed, 150,000 against 128,000.
978 //
979 // Only when the caller left the default in place; an explicit policy is
980 // a decision and stays untouched. The output allowance is reserved,
981 // because the window is shared between the prompt and the reply.
982 if ctx.policy.max_input_tokens == harness_core::Policy::default().max_input_tokens {
983 let window = self.model.info().context_window;
984 if window > 0 {
985 // Reserve room for the reply, but never let the reservation eat
986 // the window: an 8k model with the default 8k output allowance
987 // would leave 0 tokens for input, and every turn — a 26-token
988 // one included — would run all five compaction stages against a
989 // budget of 1. Cap the reservation at a quarter of the window.
990 let reserve = ctx.policy.max_output_tokens.min(window / 4);
991 ctx.policy.max_input_tokens = window.saturating_sub(reserve).max(1);
992 }
993 }
994
995 self.hooks.fire(
996 &Event::SessionStart {
997 source: SessionSource::Startup,
998 },
999 world,
1000 );
1001
1002 // ── recall: resolve owner/session, ensure the session row ──
1003 let (recall_owner, recall_session) = if self.recall.is_some() {
1004 use std::sync::atomic::Ordering;
1005 let owner = crate::recall_owner(world);
1006 let session = world
1007 .profile
1008 .extra
1009 .get("recall_session")
1010 .and_then(|v| v.as_str())
1011 .map(|s| s.to_string())
1012 .unwrap_or_else(|| {
1013 format!(
1014 "sess-{}-{}",
1015 world.clock.now_ms(),
1016 RECALL_SEQ.fetch_add(1, Ordering::SeqCst)
1017 )
1018 });
1019 if let Some(store) = &self.recall {
1020 let meta = harness_core::SessionMeta::new(&session, world.clock.now_ms());
1021 if let Err(e) = store.ensure_session(&owner, &session, &meta).await {
1022 tracing::warn!(error = %e, "recall ensure_session failed");
1023 }
1024 }
1025 (owner, session)
1026 } else {
1027 (String::new(), String::new())
1028 };
1029
1030 let recall_guide: Option<Arc<dyn Guide>> = if self.recall_auto_inject {
1031 if self.recall.is_none() {
1032 tracing::warn!(
1033 "auto_inject() set but no recall store — call with_recall(store) first; skipping recall guide"
1034 );
1035 None
1036 } else {
1037 self.recall
1038 .clone()
1039 .map(|s| Arc::new(crate::RecallGuide::new(s)) as Arc<dyn Guide>)
1040 }
1041 } else {
1042 None
1043 };
1044 let all_guides: Vec<&Arc<dyn Guide>> =
1045 self.guides.iter().chain(recall_guide.iter()).collect();
1046 for g in &all_guides {
1047 if g.scope().matches(&ctx.task) {
1048 self.hooks.fire(&Event::PreGuide { guide: g.id() }, world);
1049 g.apply(&mut ctx, world).await?;
1050 self.hooks.fire(&Event::PostGuide { guide: g.id() }, world);
1051 }
1052 }
1053
1054 ctx.history.push(Turn {
1055 role: TurnRole::User,
1056 blocks: vec![Block::Text(ctx.task.description.clone())],
1057 });
1058
1059 if self.recall.is_some() {
1060 self.recall_append(
1061 &recall_owner,
1062 &recall_session,
1063 harness_core::RecallMessage::new(
1064 "user",
1065 ctx.task.description.clone(),
1066 world.clock.now_ms(),
1067 ),
1068 )
1069 .await;
1070 }
1071
1072 // Running totals — surface to caller even on BudgetExhausted.
1073 let mut tools_called: u32 = 0;
1074 let mut total_usage = harness_core::Usage::default();
1075 let mut last_text: Option<String> = None;
1076
1077 // Stuck-detector state: the previous round's tool-call fingerprint and
1078 // how many consecutive rounds have repeated it.
1079 let mut last_fingerprint: Option<String> = None;
1080 let mut repeat_count: u32 = 0;
1081 // Read-only calls already answered this run, cleared whenever anything
1082 // mutates the world. See `ToolResultPolicy::dedupe_repeats`.
1083 let mut answered: std::collections::HashSet<String> = std::collections::HashSet::new();
1084 // How many times the model has stopped mid-work with nothing to show.
1085 let mut acceptance_retries_left = self.acceptance_retries;
1086
1087 // The contract as it stood before the model touched anything. Taken
1088 // now, not at verdict time, because the whole point is to compare
1089 // against a state the model has not had the chance to influence.
1090 // Set once a sealed file is found to have moved; makes the failure
1091 // terminal and carries the reason out to the caller.
1092 let mut seal_breached: Option<String> = None;
1093 let sealed_before: crate::seal::SealSet = {
1094 let paths: Vec<std::path::PathBuf> =
1095 self.acceptance.iter().flat_map(|a| a.seals()).collect();
1096 if paths.is_empty() {
1097 crate::seal::SealSet::default()
1098 } else {
1099 crate::seal::SealSet::capture(&world.repo.root, paths)
1100 }
1101 };
1102
1103 for iter in 0..ctx.policy.max_iters {
1104 self.hooks.fire(&Event::Heartbeat { iter }, world);
1105
1106 // Compaction with hysteresis: only once over the high-water mark,
1107 // then escalate stage-by-stage, re-estimating after each, and stop
1108 // the moment we're back under target. Avoids over-compacting to the
1109 // lossy AutoCompact stage and avoids rewriting history (→ prefix
1110 // cache miss) every turn. Token estimate is calibrated against the
1111 // last real `input_tokens` via `CALIBRATION_KEY`.
1112 let mut budget = self.compactor.budget(&ctx);
1113 if budget.ratio() > self.compaction.high_water {
1114 for stage in CompactionStage::ALL {
1115 if budget.ratio() <= self.compaction.target {
1116 break;
1117 }
1118 self.hooks.fire(&Event::PreCompact { stage }, world);
1119 let before = budget.used;
1120 self.compactor.compact(stage, &mut ctx).await?;
1121 budget = self.compactor.budget(&ctx);
1122 self.hooks.fire(
1123 &Event::PostCompact {
1124 stage,
1125 before,
1126 after: budget.used,
1127 },
1128 world,
1129 );
1130 }
1131 }
1132
1133 // Per-iteration guides — recall-style adapters that want to
1134 // refresh their injected context every turn (e.g. MemoryGuide
1135 // re-recalling against the latest user message). Default
1136 // `apply_before_iter` is a no-op, so this loop is cheap for
1137 // guides that don't override it.
1138 for g in &all_guides {
1139 if g.scope().matches(&ctx.task)
1140 && let Err(e) = g.apply_before_iter(&mut ctx, world).await
1141 {
1142 tracing::warn!(guide = %g.id(), error = %e, "apply_before_iter failed; continuing");
1143 }
1144 }
1145
1146 self.hooks.fire(&Event::PreModel { ctx: &ctx }, world);
1147 let out = if self.streaming {
1148 self.complete_via_stream(&ctx, world).await?
1149 } else {
1150 self.model.complete(&ctx).await?
1151 };
1152 self.hooks.fire(&Event::PostModel { out: &out }, world);
1153
1154 // Calibrate the compactor against ground truth: `ctx` still holds
1155 // exactly what we just sent, so `budget().used` is the estimate for
1156 // it. Nudge the stored correction so estimate·correction ≈ the
1157 // model's real `input_tokens` next time. Self-correcting (converges
1158 // even as the raw estimate drifts); clamped so one odd turn can't
1159 // blow it up. This is what makes compaction fire at the right moment
1160 // for *this* model + language instead of a blind char heuristic.
1161 if out.usage.input_tokens > 0 {
1162 let used = self.compactor.budget(&ctx).used;
1163 if used > 0 {
1164 let prev = ctx
1165 .metadata
1166 .get(CALIBRATION_KEY)
1167 .and_then(|v| v.as_f64())
1168 .filter(|f| f.is_finite() && *f > 0.0)
1169 .unwrap_or(1.0);
1170 let next =
1171 (prev * out.usage.input_tokens as f64 / used as f64).clamp(0.1, 10.0);
1172 ctx.metadata
1173 .insert(CALIBRATION_KEY.into(), serde_json::json!(next));
1174 }
1175 }
1176
1177 // Accumulate usage even if the run later exhausts budget.
1178 total_usage.input_tokens += out.usage.input_tokens;
1179 total_usage.output_tokens += out.usage.output_tokens;
1180 total_usage.cached_input_tokens += out.usage.cached_input_tokens;
1181 total_usage.cache_write_input_tokens += out.usage.cache_write_input_tokens;
1182 if let Some(t) = &out.text {
1183 last_text = Some(t.clone());
1184 }
1185 ctx.push_model_output(&out);
1186
1187 if self.recall.is_some() {
1188 let calls = if out.tool_calls.is_empty() {
1189 None
1190 } else {
1191 serde_json::to_string(&out.tool_calls).ok()
1192 };
1193 let mut m = harness_core::RecallMessage::new(
1194 "assistant",
1195 out.text.clone().unwrap_or_default(),
1196 world.clock.now_ms(),
1197 );
1198 m.tool_calls = calls;
1199 self.recall_append(&recall_owner, &recall_session, m).await;
1200 }
1201
1202 if out.tool_calls.is_empty() {
1203 // The model stopping is its opinion that the work is done.
1204 // Before taking it as fact, run whatever the caller said
1205 // "done" actually means. A failure goes back as an instruction
1206 // and the loop carries on; the retry cap keeps a model that
1207 // ignores corrections from eating the budget.
1208 let mut verdict: Option<Verdict> = None;
1209 if !self.acceptance.is_empty() {
1210 // Record this turn first — the checks read the transcript.
1211 let mut probe = ctx.clone();
1212 probe.history.push(Turn {
1213 role: TurnRole::Assistant,
1214 blocks: out
1215 .text
1216 .as_deref()
1217 .filter(|t| !t.trim().is_empty())
1218 .map(|t| vec![Block::Text(t.to_string())])
1219 .unwrap_or_default(),
1220 });
1221 for check in &self.acceptance {
1222 let v = check.check(&probe, world).await;
1223 self.hooks.fire(
1224 &Event::AcceptanceChecked {
1225 name: check.name(),
1226 passed: v.passed,
1227 reason: &v.reason,
1228 },
1229 world,
1230 );
1231 if !v.passed {
1232 tracing::info!(
1233 check = check.name(),
1234 reason = %v.reason,
1235 "acceptance failed"
1236 );
1237 verdict = Some(v);
1238 break;
1239 }
1240 }
1241 // Everything passed. Say so explicitly: "checked, and it
1242 // holds up" is a different claim from "nobody looked", and
1243 // the host has to be able to tell them apart.
1244 verdict = verdict.or_else(|| Some(Verdict::passed()));
1245 }
1246
1247 // A pass is only worth the contract it was measured against.
1248 // Re-read the sealed files and refuse if any moved.
1249 if !sealed_before.is_empty() && verdict.as_ref().is_some_and(|v| v.passed) {
1250 let paths: Vec<std::path::PathBuf> =
1251 self.acceptance.iter().flat_map(|a| a.seals()).collect();
1252 let now = crate::seal::SealSet::capture(&world.repo.root, paths);
1253 let breaches = sealed_before.breaches(&now);
1254 if !breaches.is_empty() {
1255 let what = breaches
1256 .iter()
1257 .map(|b| b.describe())
1258 .collect::<Vec<_>>()
1259 .join("; ");
1260 tracing::error!(
1261 breaches = %what,
1262 "acceptance contract changed during the run — refusing the pass"
1263 );
1264 self.hooks
1265 .fire(&Event::SealBreached { detail: &what }, world);
1266 // Deliberately NOT a retry. Every other acceptance
1267 // failure is handed back as an instruction because the
1268 // model can act on it; this one would be handing back
1269 // "you edited the gate", to the party that edited it,
1270 // with the file still writable. The run is over.
1271 seal_breached = Some(what);
1272 verdict = Some(Verdict::failed(
1273 "the acceptance contract was modified during this run",
1274 ));
1275 }
1276 }
1277
1278 if let Some(v) = verdict.clone().filter(|v| !v.passed)
1279 && seal_breached.is_none()
1280 && acceptance_retries_left > 0
1281 && iter + 1 < ctx.policy.max_iters
1282 {
1283 acceptance_retries_left -= 1;
1284 ctx.history.push(Turn {
1285 role: TurnRole::User,
1286 blocks: vec![Block::Text(v.reason)],
1287 });
1288 continue;
1289 }
1290
1291 self.hooks.fire(&Event::TaskCompleted, world);
1292 self.hooks.fire(&Event::SessionEnd, world);
1293 self.run_learning_review(&ctx, world, tools_called).await;
1294 // Thinking models (e.g. Qwen3 via Ollama) sometimes emit the
1295 // whole answer into the reasoning channel and leave `text`
1296 // empty. Fall back to the reasoning so the turn isn't blank —
1297 // but `verified` says whether anyone agreed it was done.
1298 let text = out
1299 .text
1300 .filter(|t| !t.trim().is_empty())
1301 .or_else(|| out.reasoning.filter(|r| !r.trim().is_empty()));
1302 return Ok(Outcome::Done {
1303 text,
1304 iters: iter + 1,
1305 tools_called,
1306 usage: total_usage,
1307 verified: verdict,
1308 contract: sealed_before.clone(),
1309 seal_breach: seal_breached,
1310 });
1311 }
1312
1313 // ── stuck detection ─────────────────────────────────────────
1314 // The model asked for tools again. If it's the *same* request as
1315 // last round, it's spinning: nudge it to change tack, then abort
1316 // cleanly rather than burn the rest of the budget on the loop.
1317 if self.stuck.enabled {
1318 let fp = tool_call_fingerprint(&out.tool_calls);
1319 if last_fingerprint.as_ref() == Some(&fp) {
1320 repeat_count += 1;
1321 } else {
1322 repeat_count = 1;
1323 last_fingerprint = Some(fp);
1324 }
1325
1326 if repeat_count >= self.stuck.abort_after {
1327 let reason =
1328 format!("repeated the same tool call {repeat_count}× without progress");
1329 tracing::warn!(repeated = repeat_count, "stuck: aborting run");
1330 self.hooks.fire(&Event::SessionEnd, world);
1331 return Ok(Outcome::Stuck {
1332 reason,
1333 repeated: repeat_count,
1334 iters: iter + 1,
1335 last_text,
1336 tools_called,
1337 usage: total_usage,
1338 });
1339 }
1340
1341 if repeat_count == self.stuck.nudge_after {
1342 tracing::warn!(
1343 repeated = repeat_count,
1344 "stuck: nudging model to change approach"
1345 );
1346 ctx.push_feedback(vec![harness_core::Signal {
1347 severity: harness_core::Severity::Warn,
1348 origin: "stuck-detector".into(),
1349 message: format!(
1350 "You have issued the same tool call {repeat_count} rounds in a row \
1351 without making progress."
1352 ),
1353 agent_hint: Some(
1354 "Stop repeating it. Inspect the actual tool result/error, try a \
1355 different approach, or give your final answer with no tool call."
1356 .into(),
1357 ),
1358 auto_fix: None,
1359 location: None,
1360 }]);
1361 }
1362 }
1363
1364 // Parallel-safe prefetch: dispatch the *leading run* of read-only
1365 // tool calls concurrently (a mutating tool is a serial barrier).
1366 // The sequential loop below still processes every call in order —
1367 // hooks, sensors, and history stay ordered — only the dispatch IO
1368 // overlaps. Reads before any write are safe; anything at/after the
1369 // first mutating call runs on the normal path.
1370 let mut prefetched: HashMap<String, ToolResult> = HashMap::new();
1371 {
1372 let lead: Vec<&_> = out
1373 .tool_calls
1374 .iter()
1375 .take_while(|c| {
1376 self.tools.risk(&c.name) == Some(harness_core::ToolRisk::ReadOnly)
1377 })
1378 .collect();
1379 if lead.len() > 1 {
1380 let futs = lead.iter().map(|c| {
1381 let mut w = world.clone();
1382 let action = Action {
1383 tool: c.name.clone(),
1384 call_id: c.id.clone(),
1385 args: c.args.clone(),
1386 };
1387 async move {
1388 let r = self.dispatch_bounded(&action, &mut w).await;
1389 (action.call_id, r)
1390 }
1391 });
1392 for (id, r) in futures::future::join_all(futs).await {
1393 prefetched.insert(id, r);
1394 }
1395 }
1396 }
1397
1398 for call in &out.tool_calls {
1399 let action = Action {
1400 tool: call.name.clone(),
1401 call_id: call.id.clone(),
1402 args: call.args.clone(),
1403 };
1404
1405 // PreToolUse hook can deny destructive actions
1406 if let HookOutcome::Deny { reason } = self
1407 .hooks
1408 .fire(&Event::PreToolUse { action: &action }, world)
1409 {
1410 ctx.history.push(Turn {
1411 role: TurnRole::Tool,
1412 blocks: vec![Block::ToolResult {
1413 call_id: action.call_id.clone(),
1414 content: serde_json::json!({
1415 "ok": false,
1416 "denied_by_hook": reason,
1417 }),
1418 }],
1419 });
1420 if self.recall.is_some() {
1421 self.recall_append(
1422 &recall_owner,
1423 &recall_session,
1424 harness_core::RecallMessage::new(
1425 "tool",
1426 format!("[denied by hook] {reason}"),
1427 world.clock.now_ms(),
1428 )
1429 .with_tool_name(action.tool.clone()),
1430 )
1431 .await;
1432 }
1433 continue;
1434 }
1435
1436 // Use the concurrently-prefetched result if we have one;
1437 // otherwise dispatch now.
1438 let result = if let Some(r) = prefetched.remove(&action.call_id) {
1439 r
1440 } else {
1441 self.dispatch_bounded(&action, world).await
1442 };
1443 tools_called += 1;
1444
1445 // Decide the final payload *before* announcing the result, so
1446 // hooks, telemetry and the context all describe the same thing:
1447 // an audit that logs a 200 KB blob the model never saw is not an
1448 // audit of what happened.
1449 let result = ToolResult {
1450 content: self.shape_result(&action, &result, &mut answered, &world.repo.root),
1451 ..result
1452 };
1453 self.hooks.fire(
1454 &Event::PostToolUse {
1455 action: &action,
1456 result: &result,
1457 },
1458 world,
1459 );
1460
1461 ctx.history.push(Turn {
1462 role: TurnRole::Tool,
1463 blocks: vec![Block::ToolResult {
1464 call_id: action.call_id.clone(),
1465 content: result.content.clone(),
1466 }],
1467 });
1468
1469 if self.recall.is_some() {
1470 let body = serde_json::to_string(&result.content).unwrap_or_default();
1471 self.recall_append(
1472 &recall_owner,
1473 &recall_session,
1474 harness_core::RecallMessage::new("tool", body, world.clock.now_ms())
1475 .with_tool_name(action.tool.clone()),
1476 )
1477 .await;
1478 }
1479
1480 // run self-correct sensors
1481 let mut all_signals = Vec::new();
1482 for s in &self.sensors {
1483 if s.stage() != Stage::SelfCorrect {
1484 continue;
1485 }
1486 self.hooks.fire(&Event::PreSensor { sensor: s.id() }, world);
1487 let sigs = s.observe(&action, world).await.unwrap_or_else(|e| {
1488 tracing::warn!(?e, "sensor failed");
1489 Vec::new()
1490 });
1491 self.hooks.fire(
1492 &Event::PostSensor {
1493 sensor: s.id(),
1494 signals: &sigs,
1495 },
1496 world,
1497 );
1498 all_signals.extend(sigs);
1499 }
1500 if !all_signals.is_empty() {
1501 let bundle = SignalSet::new(all_signals);
1502 let (patches, remaining) = bundle.partition_auto_fix();
1503
1504 // audit #7: each patch goes through PreAutoFix.
1505 // Hooks can Deny (skip silently). Default safelist on
1506 // RunCommand catches the obvious misuses with no hook.
1507 let approved: Vec<harness_core::FixPatch> = patches.into_iter().filter(|p| {
1508 if !is_default_safe_fix(p) {
1509 tracing::warn!(?p, "auto-fix rejected by default safelist (use PreAutoFix hook to override)");
1510 self.hooks.fire(&Event::PostAutoFix { patch: p, applied: false }, world);
1511 return false;
1512 }
1513 match self.hooks.fire(&Event::PreAutoFix { patch: p }, world) {
1514 HookOutcome::Deny { reason } => {
1515 tracing::warn!(?p, %reason, "auto-fix denied by hook");
1516 self.hooks.fire(&Event::PostAutoFix { patch: p, applied: false }, world);
1517 false
1518 }
1519 _ => true,
1520 }
1521 }).collect();
1522
1523 let applied = apply_patches(&approved, world).await;
1524 // Emit PostAutoFix for each approved patch with the application result.
1525 for (i, p) in approved.iter().enumerate() {
1526 self.hooks.fire(
1527 &Event::PostAutoFix {
1528 patch: p,
1529 applied: i < applied.len(),
1530 },
1531 world,
1532 );
1533 }
1534 if !applied.is_empty() {
1535 ctx.push_feedback(vec![harness_core::Signal {
1536 severity: harness_core::Severity::Hint,
1537 origin: "auto-fix".into(),
1538 message: format!(
1539 "applied {} auto-fix patch(es): {applied:?}",
1540 applied.len()
1541 ),
1542 agent_hint: Some(
1543 "re-check the affected files before continuing".into(),
1544 ),
1545 auto_fix: None,
1546 location: None,
1547 }]);
1548 }
1549 if remaining.has_blocking() {
1550 ctx.push_feedback(remaining.signals);
1551 }
1552 }
1553 }
1554 }
1555 // ── Budget exhausted ─────────────────────────────────────────
1556 // Force a final synthesis pass with tools DISABLED. Otherwise the
1557 // model often spins on tool calls right up to the budget cap and
1558 // never emits a text conclusion, leaving the caller with nothing
1559 // but `last_text` from some earlier intermediate turn (or None).
1560 //
1561 // The synthesis call is "free" — it costs one extra model call
1562 // beyond max_iters but doesn't count toward `iters`. The result
1563 // lands in `last_text` so callers display it as the answer.
1564 let synthesised = self
1565 .force_final_synthesis(&mut ctx, world, &mut total_usage)
1566 .await;
1567 if let Some(t) = synthesised {
1568 last_text = Some(t);
1569 }
1570
1571 self.hooks.fire(&Event::SessionEnd, world);
1572 self.run_learning_review(&ctx, world, tools_called).await;
1573 Ok(Outcome::BudgetExhausted {
1574 iters: ctx.policy.max_iters,
1575 last_text,
1576 tools_called,
1577 usage: total_usage,
1578 })
1579 }
1580
1581 /// Drive `Model::stream()` and assemble the result into a `ModelOutput`,
1582 /// firing `Event::ModelTokenDelta` for each text fragment along the way.
1583 ///
1584 /// Adapters that don't implement real streaming (e.g. `GeminiNative` /
1585 /// `AnthropicNative` today) fall back to the default trait impl, which
1586 /// runs `complete()` and emits the whole reply as a single delta. That
1587 /// works — the loop sees one big `ModelDelta::Text(...)` followed by
1588 /// `Stop`, fires one big `ModelTokenDelta`, and proceeds. So enabling
1589 /// `streaming` is safe regardless of which provider the user picked.
1590 async fn complete_via_stream(
1591 &self,
1592 ctx: &Context,
1593 world: &mut World,
1594 ) -> Result<ModelOutput, HarnessError> {
1595 use futures::StreamExt;
1596 let mut stream = self
1597 .model
1598 .stream(ctx)
1599 .await
1600 .map_err(harness_core::HarnessError::Model)?;
1601 let mut text = String::new();
1602 let mut reasoning = String::new();
1603 let mut usage = Usage::default();
1604 let mut stop_reason = StopReason::EndTurn;
1605 // Insertion-ordered map: index → (id, name, args). We can't use the
1606 // tool-call id as the primary key because the stream may emit args
1607 // chunks before the first chunk that carries the id; the OpenAI-compat
1608 // SSE parser already does its own buffering and surfaces `id` in
1609 // ToolCallStart, but be lenient with adapters that may interleave.
1610 let mut tool_starts: HashMap<String, (String, String)> = HashMap::new();
1611 let mut tool_order: Vec<String> = Vec::new();
1612 while let Some(item) = stream.next().await {
1613 let delta = item.map_err(harness_core::HarnessError::Model)?;
1614 match delta {
1615 ModelDelta::Text(t) => {
1616 if !t.is_empty() {
1617 self.hooks.fire(&Event::ModelTokenDelta { text: &t }, world);
1618 text.push_str(&t);
1619 }
1620 }
1621 ModelDelta::ToolCallStart { id, name } => {
1622 if !tool_starts.contains_key(&id) {
1623 tool_order.push(id.clone());
1624 }
1625 tool_starts
1626 .entry(id)
1627 .or_insert_with(|| (name, String::new()));
1628 }
1629 ModelDelta::ToolCallArgs { id, partial_json } => {
1630 let entry = tool_starts
1631 .entry(id.clone())
1632 .or_insert_with(|| (String::new(), String::new()));
1633 if !tool_order.iter().any(|k| k == &id) {
1634 tool_order.push(id);
1635 }
1636 entry.1.push_str(&partial_json);
1637 }
1638 ModelDelta::ToolCallEnd { .. } => {}
1639 ModelDelta::Usage(u) => usage = u,
1640 ModelDelta::Stop(r) => stop_reason = r,
1641 ModelDelta::Reasoning(s) => {
1642 // Streamed reasoning arrives as token fragments, not lines —
1643 // concatenate verbatim (same as `text`), don't insert newlines.
1644 reasoning.push_str(&s);
1645 }
1646 // ModelDelta is `#[non_exhaustive]`; ignore future variants
1647 // we don't yet understand.
1648 _ => {}
1649 }
1650 }
1651 let tool_calls: Vec<ToolCall> = tool_order
1652 .into_iter()
1653 .filter_map(|id| {
1654 tool_starts.remove(&id).map(|(name, args)| {
1655 let args_v = serde_json::from_str::<serde_json::Value>(&args)
1656 .unwrap_or(serde_json::Value::String(args));
1657 ToolCall {
1658 id,
1659 name,
1660 args: args_v,
1661 }
1662 })
1663 })
1664 .collect();
1665 // Reconcile stop_reason with what actually came out — adapters
1666 // sometimes emit `Stop(EndTurn)` even after tool_calls, which would
1667 // confuse downstream consumers that branch on stop_reason alone.
1668 let stop_reason = if !tool_calls.is_empty() {
1669 StopReason::ToolUse
1670 } else {
1671 stop_reason
1672 };
1673 Ok(ModelOutput {
1674 text: if text.is_empty() { None } else { Some(text) },
1675 tool_calls,
1676 usage,
1677 stop_reason,
1678 reasoning: if reasoning.is_empty() {
1679 None
1680 } else {
1681 Some(reasoning)
1682 },
1683 // `ModelDelta` has no image variant: the verified image-output
1684 // path (Gemini image models over chat) answers non-streamed, so
1685 // there is nothing to accumulate here. A streaming provider that
1686 // emits images would need a `ModelDelta::Image` first.
1687 images: Vec::new(),
1688 })
1689 }
1690
1691 /// Best-effort append to the recall store. Never fails the turn.
1692 /// One tool call, under the per-call deadline. A timeout becomes an error
1693 /// *result* — the model sees it and routes around it — never a hung run.
1694 /// Errors are folded the same way: the loop's contract is that a tool call
1695 /// always produces a result turn.
1696 async fn dispatch_bounded(&self, action: &Action, world: &mut World) -> ToolResult {
1697 let fut = self.tools.dispatch(action, world);
1698 let dispatched = match self.tool_timeout {
1699 Some(deadline) => match tokio::time::timeout(deadline, fut).await {
1700 Ok(r) => r,
1701 Err(_) => {
1702 tracing::warn!(
1703 target: "harness.telemetry",
1704 event = "tool.deadline",
1705 "gen_ai.tool.name" = %action.tool,
1706 seconds = deadline.as_secs(),
1707 );
1708 return ToolResult {
1709 ok: false,
1710 content: serde_json::json!({
1711 "error": format!(
1712 "tool call exceeded its {}s deadline and was cancelled; \
1713 the operation may be too broad — narrow it or try a \
1714 different approach",
1715 deadline.as_secs()
1716 ),
1717 "timeout": true,
1718 }),
1719 trace: None,
1720 };
1721 }
1722 },
1723 None => fut.await,
1724 };
1725 dispatched.unwrap_or_else(|e| ToolResult {
1726 ok: false,
1727 content: serde_json::json!({"error": e.to_string()}),
1728 trace: None,
1729 })
1730 }
1731
1732 /// What a tool result contributes to the context: repeat suppression first,
1733 /// then the size ceiling. A repeat that is also oversized collapses to the
1734 /// pointer rather than to a truncated copy of what the model already holds.
1735 fn shape_result(
1736 &self,
1737 action: &Action,
1738 result: &ToolResult,
1739 answered: &mut std::collections::HashSet<String>,
1740 root: &std::path::Path,
1741 ) -> serde_json::Value {
1742 if !(self.tool_results.dedupe_repeats && result.ok) {
1743 return self.cap_result(action, &result.content, root);
1744 }
1745 match self.tools.risk(&action.tool) {
1746 Some(harness_core::ToolRisk::ReadOnly) => {
1747 let fp = format!("{}({})", action.tool, action.args);
1748 if answered.contains(&fp) {
1749 tracing::info!(
1750 target: "harness.telemetry",
1751 event = "tool.result.repeat",
1752 "gen_ai.tool.name" = %action.tool,
1753 );
1754 serde_json::json!({
1755 "repeat_of_earlier_call": true,
1756 "tool": action.tool,
1757 "note": "You already made this exact call in this run and nothing has \
1758 changed the workspace since. The earlier result above still \
1759 stands — use it rather than asking again.",
1760 })
1761 } else {
1762 answered.insert(fp);
1763 self.cap_result(action, &result.content, root)
1764 }
1765 }
1766 // A write invalidates every earlier read.
1767 _ => {
1768 answered.clear();
1769 self.cap_result(action, &result.content, root)
1770 }
1771 }
1772 }
1773
1774 /// Enforce [`ToolResultPolicy`] on one result before it reaches the context.
1775 ///
1776 /// Over the ceiling, the guard prefers to *spill*: full payload to a file
1777 /// inside the workspace, bounded preview plus the path inline — nothing is
1778 /// lost, and the model retrieves slices with the file tools it already has.
1779 /// Only when spilling is off (or the write fails) does it fall back to
1780 /// destructive truncation: a byte-level cut handed back as a marker object
1781 /// rather than mangled JSON, saying how much was dropped and what to do
1782 /// instead.
1783 fn cap_result(
1784 &self,
1785 action: &Action,
1786 content: &serde_json::Value,
1787 root: &std::path::Path,
1788 ) -> serde_json::Value {
1789 let Some(max) = self.tool_results.max_bytes else {
1790 return content.clone();
1791 };
1792 let serialized = content.to_string();
1793 if serialized.len() <= max {
1794 return content.clone();
1795 }
1796 if self.tool_results.spill
1797 && let Some(marker) = spill_oversized(action, content, &serialized, root)
1798 {
1799 return marker;
1800 }
1801 // Cut on a char boundary so the kept head is valid UTF-8.
1802 let mut end = max;
1803 while end > 0 && !serialized.is_char_boundary(end) {
1804 end -= 1;
1805 }
1806 tracing::warn!(
1807 target: "harness.telemetry",
1808 event = "tool.result.truncated",
1809 "gen_ai.tool.name" = %action.tool,
1810 bytes = serialized.len(),
1811 max_bytes = max,
1812 );
1813 serde_json::json!({
1814 "truncated": true,
1815 "tool": action.tool,
1816 "bytes_total": serialized.len(),
1817 "bytes_kept": end,
1818 "head": serialized[..end],
1819 "note": format!(
1820 "This result was {} bytes and was cut to {} to protect the context window. \
1821 Do not ask for it again unchanged — narrow it: request a smaller range, \
1822 a filter, or a specific field.",
1823 serialized.len(), end
1824 ),
1825 })
1826 }
1827
1828 async fn recall_append(&self, owner: &str, session: &str, msg: harness_core::RecallMessage) {
1829 if let Some(store) = &self.recall
1830 && let Err(e) = store.append(owner, session, &msg).await
1831 {
1832 tracing::warn!(error = %e, "recall append failed");
1833 }
1834 }
1835
1836 /// Best-effort post-session review. Never affects the finished run.
1837 async fn run_learning_review(&self, ctx: &Context, world: &mut World, tools_called: u32) {
1838 let Some(cfg) = &self.learning else { return };
1839 if tools_called < cfg.nudge_interval {
1840 return;
1841 }
1842 let transcript = crate::render_transcript(&ctx.history, 12_000);
1843 let task = harness_core::Task {
1844 description: format!(
1845 "{}\n\n## Conversation transcript\n{}",
1846 cfg.review_prompt, transcript
1847 ),
1848 source: None,
1849 deadline: None,
1850 };
1851 let mut spec =
1852 crate::SubagentSpec::new("learning-review", task).with_max_iters(cfg.max_iters);
1853 for t in &cfg.tools {
1854 spec = spec.with_tool(t.clone());
1855 }
1856 let sub = crate::Subagent::new(harness_core::DynModel(cfg.review_model.clone()), spec);
1857 // Box::pin breaks the recursive async-future cycle: AgentLoop<M> →
1858 // run_learning_review → Subagent<DynModel>::run →
1859 // AgentLoop<Arc<dyn Model>>::run_built_context. Without pinning the
1860 // compiler rejects the infinite-sized future.
1861 if let Err(e) = Box::pin(sub.run(world)).await {
1862 tracing::warn!(error = %e, "learning review failed");
1863 }
1864 }
1865
1866 /// One final model call with tools removed, asking it to write the
1867 /// best-effort conclusion from whatever it has already gathered.
1868 ///
1869 /// Errors from the model are swallowed — observability is best-effort
1870 /// here, and a transport blip during synthesis should not turn a
1871 /// near-complete run into a hard failure.
1872 async fn force_final_synthesis(
1873 &self,
1874 ctx: &mut Context,
1875 world: &mut World,
1876 total_usage: &mut harness_core::Usage,
1877 ) -> Option<String> {
1878 const SYNTHESIS_PROMPT: &str = "[system: iteration budget exhausted] \
1879 You have run out of tool-calling iterations. Write your final answer \
1880 NOW using only the tool results already in this conversation. Do not \
1881 request more tools. Mark facts you could not verify as UNKNOWN. \
1882 Include source URLs for every claim that is not UNKNOWN.";
1883
1884 // Signal to any observer (LiveProgressHook, SessionRecorder, custom
1885 // hooks) that we've used 100% of the budget and are about to force
1886 // synthesis. Pre-existing `BudgetWarning` event was unused; this is
1887 // its natural home.
1888 self.hooks.fire(&Event::BudgetWarning { ratio: 1.0 }, world);
1889
1890 // Snapshot + clear tool schemas so the model has no choice but text.
1891 let saved_tools = std::mem::take(&mut ctx.tools);
1892 ctx.history.push(Turn {
1893 role: TurnRole::User,
1894 blocks: vec![Block::Text(SYNTHESIS_PROMPT.into())],
1895 });
1896
1897 self.hooks.fire(&Event::PreModel { ctx }, world);
1898 let result = self.model.complete(ctx).await;
1899 ctx.tools = saved_tools;
1900
1901 match result {
1902 Ok(out) => {
1903 self.hooks.fire(&Event::PostModel { out: &out }, world);
1904 total_usage.input_tokens += out.usage.input_tokens;
1905 total_usage.output_tokens += out.usage.output_tokens;
1906 total_usage.cached_input_tokens += out.usage.cached_input_tokens;
1907 total_usage.cache_write_input_tokens += out.usage.cache_write_input_tokens;
1908 ctx.push_model_output(&out);
1909 out.text
1910 }
1911 Err(_) => None,
1912 }
1913 }
1914}
1915
1916/// A persistent multi-turn conversation over one [`AgentLoop`].
1917///
1918/// Holds the append-only history and, on each [`turn`](Session::turn), re-runs
1919/// the loop against a **stable prefix** (system + name-sorted tool schemas).
1920/// That byte-stable prefix is what lets a provider's prefix cache hit across
1921/// turns — the difference between paying full price to re-read the same context
1922/// every round and paying ~10% for the cached bytes (DeepSeek).
1923pub struct Session<'a, M: Model> {
1924 loop_: &'a AgentLoop<M>,
1925 history: Vec<Turn>,
1926 max_iters: u32,
1927}
1928
1929impl<'a, M: Model> Session<'a, M> {
1930 pub fn with_max_iters(mut self, n: u32) -> Self {
1931 self.max_iters = n;
1932 self
1933 }
1934 /// Preload prior turns (e.g. resumed from disk).
1935 pub fn with_seed(mut self, seed: Vec<Turn>) -> Self {
1936 self.history = seed;
1937 self
1938 }
1939 /// The accumulated conversation so far.
1940 pub fn history(&self) -> &[Turn] {
1941 &self.history
1942 }
1943 /// Start over (branch): drop the accumulated turns.
1944 pub fn reset(&mut self) {
1945 self.history.clear();
1946 }
1947
1948 /// Send one user message. Runs the ReAct loop against the accumulated
1949 /// history, then appends this user turn + the assistant reply so the next
1950 /// turn extends the same cached prefix.
1951 pub async fn turn(
1952 &mut self,
1953 message: impl Into<String>,
1954 world: &mut World,
1955 ) -> Result<Outcome, HarnessError> {
1956 let message = message.into();
1957 let task = Task {
1958 description: message.clone(),
1959 source: None,
1960 deadline: None,
1961 };
1962 let outcome = self
1963 .loop_
1964 .run_with_seed_history(task, self.history.clone(), world, self.max_iters)
1965 .await?;
1966 let reply = match &outcome {
1967 Outcome::Done { text, .. } => text.clone().unwrap_or_default(),
1968 Outcome::BudgetExhausted { last_text, .. } | Outcome::Stuck { last_text, .. } => {
1969 last_text.clone().unwrap_or_default()
1970 }
1971 };
1972 self.history.push(Turn {
1973 role: TurnRole::User,
1974 blocks: vec![Block::Text(message)],
1975 });
1976 self.history.push(Turn {
1977 role: TurnRole::Assistant,
1978 blocks: vec![Block::Text(reply)],
1979 });
1980 Ok(outcome)
1981 }
1982}
1983
1984/// Audit #7: default safelist for `FixPatch::RunCommand`.
1985///
1986/// Sensors emitting `RunCommand` patches would otherwise be a silent
1987/// arbitrary-code-execution channel. We restrict the *program* by name to a
1988/// short list of well-known, side-effect-bounded formatters/fixers. Anything
1989/// else returns false and the patch is rejected (write your own `PreAutoFix`
1990/// hook returning `HookOutcome::Allow` to widen the policy).
1991///
1992/// `ReplaceFile` and `UnifiedDiff` are not restricted here — they only touch
1993/// files inside the workspace and are covered by the symlink-safe path
1994/// resolution in `harness-tools-fs`.
1995pub fn is_default_safe_fix(patch: &harness_core::FixPatch) -> bool {
1996 use harness_core::FixPatch;
1997 match patch {
1998 FixPatch::ReplaceFile { .. } | FixPatch::UnifiedDiff { .. } => true,
1999 FixPatch::RunCommand { program, args, .. } => match program.as_str() {
2000 // Cargo subcommands proven side-effect-bounded.
2001 "cargo" => matches!(
2002 args.first().map(String::as_str),
2003 Some("fmt" | "clippy" | "fix"),
2004 ),
2005 "rustfmt" | "gofmt" | "prettier" | "ruff" | "black" => true,
2006 _ => false,
2007 },
2008 // Future FixPatch variants: deny by default — review and add to the list above.
2009 _ => false,
2010 }
2011}
2012
2013/// Monotonic counter for `.harness-patch-*.diff` temp filenames — millisecond
2014/// resolution alone collides under parallel agent runs.
2015static PATCH_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2016
2017/// Monotonic counter for fallback recall session ids (no `uuid` dep).
2018static RECALL_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2019
2020/// Apply auto-fix patches; return short descriptions of those that succeeded.
2021///
2022/// Made `pub` (was `pub(crate)`) so integration tests can call it directly.
2023pub async fn apply_patches(patches: &[harness_core::FixPatch], world: &mut World) -> Vec<String> {
2024 use harness_core::FixPatch;
2025 let mut applied = Vec::new();
2026 for p in patches {
2027 match p {
2028 FixPatch::ReplaceFile { path, content } => {
2029 let abs = world.repo.root.join(path);
2030 if let Some(parent) = abs.parent() {
2031 let _ = tokio::fs::create_dir_all(parent).await;
2032 }
2033 if tokio::fs::write(&abs, content).await.is_ok() {
2034 applied.push(format!("replaced {}", path.display()));
2035 }
2036 }
2037 FixPatch::UnifiedDiff { diff } => {
2038 if try_apply_diff(world, diff).await {
2039 applied.push("unified diff applied".into());
2040 }
2041 }
2042 FixPatch::RunCommand { program, args, cwd } => {
2043 let cwd_ref = cwd.as_deref().unwrap_or(world.repo.root.as_path());
2044 let args_ref: Vec<&str> = args.iter().map(String::as_str).collect();
2045 if let Ok(out) = world.runner.exec(program, &args_ref, Some(cwd_ref)).await
2046 && out.status == 0
2047 {
2048 applied.push(format!("ran `{program} {}`", args.join(" ")));
2049 }
2050 }
2051 // FixPatch is `#[non_exhaustive]`; unknown variants are skipped.
2052 _ => tracing::warn!("apply_patches: unknown FixPatch variant — skipped"),
2053 }
2054 }
2055 applied
2056}
2057
2058/// Write `diff` to a unique temp file and try `patch -p1` first, then `-p0`.
2059/// Returns whether either succeeded. The `-p1`-then-`-p0` order matches the
2060/// reality that most agent-emitted diffs are git-style (need `-p1`) but some
2061/// hand-rolled diffs use repo-relative paths (need `-p0`).
2062async fn try_apply_diff(world: &mut World, diff: &str) -> bool {
2063 use std::sync::atomic::Ordering;
2064 use tokio::io::AsyncWriteExt;
2065
2066 let seq = PATCH_SEQ.fetch_add(1, Ordering::SeqCst);
2067 let pid = std::process::id();
2068 let now = world.clock.now_ms();
2069 let tmp = world
2070 .repo
2071 .root
2072 .join(format!(".harness-patch-{pid}-{now}-{seq}.diff"));
2073
2074 let mut f = match tokio::fs::File::create(&tmp).await {
2075 Ok(f) => f,
2076 Err(e) => {
2077 tracing::warn!(error=%e, path=%tmp.display(), "could not create patch tempfile");
2078 return false;
2079 }
2080 };
2081 if let Err(e) = f.write_all(diff.as_bytes()).await {
2082 tracing::warn!(error=%e, "could not write patch tempfile");
2083 let _ = tokio::fs::remove_file(&tmp).await;
2084 return false;
2085 }
2086 drop(f);
2087
2088 let tmp_str = tmp.to_string_lossy().to_string();
2089 let mut applied = false;
2090 for strip in ["-p1", "-p0"] {
2091 match world
2092 .runner
2093 .exec(
2094 "patch",
2095 &[strip, "--silent", "-i", tmp_str.as_str()],
2096 Some(world.repo.root.as_path()),
2097 )
2098 .await
2099 {
2100 Ok(out) if out.status == 0 => {
2101 tracing::info!(strip, "patch applied");
2102 applied = true;
2103 break;
2104 }
2105 Ok(out) => {
2106 tracing::debug!(strip, stderr=%out.stderr, "patch failed; trying next strip level");
2107 }
2108 Err(e) => {
2109 tracing::warn!(error=%e, "patch command not available");
2110 break; // patch tool missing — no point trying other strip
2111 }
2112 }
2113 }
2114 let _ = tokio::fs::remove_file(&tmp).await;
2115 applied
2116}