---
title: "Learn What an AI Harness Is by Building One in Rust"
description: "A model writes the patch. The harness decides what it can touch, runs the tests and logs every step. Build one in Rust from an empty folder."
author: "Jordan Hudgens"
author_handle: "@jordan"
canonical_url: "https://www.devguides.com/jordan/learn-what-an-ai-harness-is-by-building-one-in-rust"
published_at: "2026-11-22T12:35:48.195476+00:00"
updated_at: "2026-11-22T15:24:10.893567+00:00"
reading_minutes: 46
topics: ["rust", "ai", "agents", "cli", "llm", "security"]
---

# Learn What an AI Harness Is by Building One in Rust

> A model writes the patch. The harness decides what it can touch, runs the tests and logs every step. Build one in Rust from an empty folder.

In July 2025, SaaStr founder Jason Lemkin was nine days into a public experiment building an app with Replit's AI agent when the agent deleted his production database. He'd put the project under a code freeze, and afterward the agent said it "panicked and ran database commands without permission," as [Business Insider reported](https://www.businessinsider.com/replit-ceo-apologizes-ai-coding-tool-delete-company-database-2025-7). Lemkin put the real problem in one line, according to [The Register](https://www.theregister.com/2025/07/21/replit_saastr_vibe_coding_incident/): "There is no way to enforce a code freeze in vibe coding apps like Replit. There just isn't."

Replit's CEO called the deletion "unacceptable" and said it "should never be possible." Most of the fixes the company announced didn't change what the model was told. They changed what the agent could reach and how easily a mistake could be undone: automatic separation of development and production databases, better rollback and a planning-only mode, according to [Fortune](https://fortune.com/2025/07/23/ai-coding-tool-replit-wiped-database-called-it-a-catastrophic-failure/).

The same gap shows up on a smaller scale every time you ask a model to fix a bug. Send a source file to a language model over HTTP, and it will hand back plausible Rust and stop there. A model checkpoint can't read your workspace, run `cargo test`, prevent a hallucinated path from reading `/etc/hosts`, truncate a 50 KB compiler backtrace before your context window overflows or notice that its own patch left a second test broken.

Everything that does those jobs is the **AI harness**: the deterministic software wrapped around the model. The model proposes each action. The harness decides which actions actually run, what the model sees next and when the work counts as done.

The harness also changes how capable the same model looks. In February 2026, Can Bölük ran 16 models through the same 180 coding tasks and changed only the tool they used to edit files. As he reports in [The harness problem](https://blog.can.ac/2026/02/12/the-harness-problem/), Grok Code Fast 1 went from 6.7% to 68.3%. In other words, a good share of what looks like model quality is harness quality.

> **Short answer:** An AI harness owns the six things a raw LLM can't do for itself: the **turn loop & circuit breakers**, **workspace path & command sandboxing**, **UTF-8 observation bounding & history compaction**, **recoverable tool dispatch**, **provider wire translation**, and a **verification gate + JSONL trajectory log**. Every snippet below is complete, so you can follow Steps 1 to 9 from an empty folder, compile `harness` and run all four lab experiments locally.

## What you'll build

In this guide we'll build a security-hardened coding harness in Rust, starting from an empty folder. The crate is `agent-harness`, and the binary is `harness`. Every module compiles cleanly on stable Rust with zero Clippy warnings. It runs offline out of the box through a deterministic scripted replay backend, and it connects to OpenAI, Google Gemini, Anthropic Claude or a local Ollama server when you're ready for a real model.

By the end you'll have:

- A turn loop with circuit breakers that hands the model four tools: read a file, write a file, edit a file and run a command.
- A sandbox policy that keeps the harness's file tools inside the project folder, only starts programs on an allowlist and gives them a minimal environment. Step 2 also covers what it can't contain.
- Output limits that keep one noisy test run from flooding the context window.
- A provider layer that sends the same conversation to OpenAI, Gemini or Claude.
- A verification gate that won't accept "done" until `cargo test` passes.
- A `trace.jsonl` log of every turn that you can query with `jq`.

You'll need stable Rust, Cargo and some comfort reading Rust. You won't need an API key until Experiment 4 of the lab, and even there a local Ollama server works without one. The finished crate is on GitHub at [dev-guides-platform/agent-harness](https://github.com/dev-guides-platform/agent-harness) if you'd like to compare as you go.

Here's the payoff. In this verified run against a deliberately broken Rust crate, Turn 3 tries to stop after fixing only one of two bugs. The harness's `--verify "cargo test --quiet"` gate rejects the early stop, feeds the failing assertion back into Turn 4 and holds the loop open until all four unit tests pass on Turn 5.

[Guide animation](https://www.devguides.com/api/media?path=devguides%2F8f6b6a61-d3c6-4277-8bf5-0cd4e1a800cd%2Fc6f96258-df0f-4f34-a595-95e46c666a2e.mp4)

## Model vs. AI harness: drawing the boundary

Before writing a line of Rust, draw a strict boundary of responsibility. Treat the language model as an untrusted, stateless function `(Vec<Message>, Vec<ToolSpec>) -> ModelResponse`. Everything stateful or side-effecting belongs to the harness:

| Responsibility | Raw LLM API | Your Rust AI Harness (`agent-harness`) |
| --- | --- | --- |
| Conversation state | Stateless per HTTP call | Owns canonical `Vec<Message>` across turns and providers |
| Filesystem safety | Can propose `"../../etc/hosts"` | Canonicalizes ancestors & symlinks; confines paths to `workspace_root` |
| Command execution | Can propose `"rm -rf /"` or hang | Spawns allowlisted binaries directly (never `sh -c`) with a kill timer and a cleared environment |
| Output explosions | Fails when prompts exceed context | Bounds each tool output (60% head + 40% tail on UTF-8 boundaries) & compacts old turns |
| Premature "Done!" | Stops as soon as it *thinks* a fix works | Runs `--verify "cargo test --quiet"` before accepting completion |
| Post-mortem debugging | Ephemeral HTTP responses | Flushes structured JSON Lines events to `trace.jsonl` on every step |

Lemkin's code freeze sat on the wrong side of this table. It was a message to the model, and nothing on the harness side enforced it.

## How the crate is organized

We'll build `agent-harness` as a library crate (`src/lib.rs`) with a thin CLI binary (`src/main.rs`) on top so integration tests can exercise both the internal Rust types and the compiled `harness` binary.

![Module map of agent-harness 0.1.0 showing main.rs calling runner.rs, which calls provider.rs, tools.rs, sandbox.rs, and bounding.rs, with trace.rs and types.rs shared underneath.](https://www.devguides.com/api/media?path=devguides%2F8f6b6a61-d3c6-4277-8bf5-0cd4e1a800cd%2F740581bc-9d63-4e9c-b9eb-760c46dda740.png)

Before diving into the code, watch how a single turn travels through the four internal safety gates inside `sandbox.rs`, `bounding.rs`, and `trace.rs`:

[Guide animation](https://www.devguides.com/api/media?path=devguides%2F8f6b6a61-d3c6-4277-8bf5-0cd4e1a800cd%2F95eca968-79d1-4444-9339-1143fd2231a9.mp4)

Create a fresh Cargo project layout:

```bash
mkdir agent-harness && cd agent-harness
mkdir -p src tests
```

Save `Cargo.toml` first. Because an agent turn loop (`prompt -> tool -> verify -> prompt`) executes sequentially per workspace, blocking HTTP via `ureq` keeps compile times fast and avoids async trait boilerplate:

```toml
[package]
name = "agent-harness"
version = "0.1.0"
edition = "2021"

[[bin]]
name = "harness"
path = "src/main.rs"

[dependencies]
clap = { version = "4.5", features = ["derive", "env"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
thiserror = "2.0"
ureq = { version = "2.10", features = ["json"] }

[dev-dependencies]
tempfile = "3.14"
```

Expose all seven modules in `src/lib.rs`:

```rust
pub mod bounding;
pub mod provider;
pub mod runner;
pub mod sandbox;
pub mod tools;
pub mod trace;
pub mod types;
```

## Step 1: Define a provider-agnostic internal protocol (`src/types.rs`)

Coupling your core loop directly to one vendor's HTTP JSON schema makes multi-model support painful later: OpenAI puts stringified JSON tool arguments inside `choices[0].message.tool_calls`, whereas Anthropic embeds `tool_use` blocks inside `content` arrays and requires consecutive tool outputs to be merged into a single `user` turn.

Defining canonical `Message`, `ToolSpec`, `ToolCall`, `StopReason`, and `RunReport` types in `src/types.rs` isolates `runner.rs` from wire quirks. Save this as `src/types.rs`:

```rust
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::PathBuf;
use thiserror::Error;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    System,
    User,
    Assistant,
    Tool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
    pub id: String,
    pub name: String,
    pub arguments: Value,
    /// Provider data that must go back unchanged with this call, such as
    /// Gemini's `extra_content.google.thought_signature`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extra_content: Option<Value>,
}

impl ToolCall {
    pub fn new(id: impl Into<String>, name: impl Into<String>, arguments: Value) -> Self {
        Self { id: id.into(), name: name.into(), arguments, extra_content: None }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    pub role: Role,
    pub content: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tool_calls: Vec<ToolCall>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
    #[serde(default)]
    pub is_error: bool,
}

impl Message {
    pub fn system(content: impl Into<String>) -> Self {
        Self { role: Role::System, content: content.into(), tool_calls: vec![], tool_call_id: None, is_error: false }
    }
    pub fn user(content: impl Into<String>) -> Self {
        Self { role: Role::User, content: content.into(), tool_calls: vec![], tool_call_id: None, is_error: false }
    }
    pub fn assistant(content: impl Into<String>, tool_calls: Vec<ToolCall>) -> Self {
        Self { role: Role::Assistant, content: content.into(), tool_calls, tool_call_id: None, is_error: false }
    }
    pub fn tool_result(id: impl Into<String>, content: impl Into<String>, is_error: bool) -> Self {
        Self { role: Role::Tool, content: content.into(), tool_calls: vec![], tool_call_id: Some(id.into()), is_error }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolSpec {
    pub name: String,
    pub description: String,
    pub parameters: Value,
}

#[derive(Debug, Clone, Default, Copy, Serialize, Deserialize)]
pub struct TokenUsage {
    pub input_tokens: u64,
    pub output_tokens: u64,
}

impl TokenUsage {
    pub fn total(self) -> u64 {
        self.input_tokens.saturating_add(self.output_tokens)
    }
    pub fn accumulate(&mut self, other: TokenUsage) {
        self.input_tokens = self.input_tokens.saturating_add(other.input_tokens);
        self.output_tokens = self.output_tokens.saturating_add(other.output_tokens);
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelResponse {
    pub content: String,
    #[serde(default)]
    pub tool_calls: Vec<ToolCall>,
    #[serde(default)]
    pub usage: TokenUsage,
}

impl ModelResponse {
    pub fn new(content: impl Into<String>, tool_calls: Vec<ToolCall>, input_tokens: u64, output_tokens: u64) -> Self {
        Self { content: content.into(), tool_calls, usage: TokenUsage { input_tokens, output_tokens } }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
    Completed,
    MaxTurnsReached,
    TokenBudgetExceeded,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunReport {
    pub stop_reason: StopReason,
    pub final_answer: String,
    pub turns_used: usize,
    pub tool_calls_made: usize,
    pub policy_denials: usize,
    pub verification_runs: usize,
    pub compactions: usize,
    pub total_usage: TokenUsage,
    pub trace_path: PathBuf,
}

#[derive(Debug, Error)]
pub enum HarnessError {
    #[error("sandbox policy violation: {0}")]
    PolicyViolation(String),
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
    #[error("provider error: {0}")]
    Provider(String),
    #[error("configuration error: {0}")]
    Config(String),
}
```

Notice two deliberate design choices here:

- **`Message` carries `is_error: bool`**: Tool failures and sandbox denials never crash the Rust process. They become structured `is_error: true` observations, so the model can self-correct on the next turn.
- **Explicit `StopReason` variants**: Callers and CI scripts can distinguish `Completed` from `MaxTurnsReached` and `TokenBudgetExceeded`.

## Step 2: Enforce workspace confinement and command timeouts (`src/sandbox.rs`)

In plain terms, the harness's own file tools only touch files inside the project folder, and the model can only start programs on a short list. Giving a model `write_file` and `run_command` without a boundary turns a hallucinated path or prompt injection into arbitrary host execution. `SandboxPolicy` enforces three invariants before any tool touches the OS:

1. **Ancestor-aware symlink canonicalization (`resolve_path`)**: Checking `!raw_path.contains("..")` misses both absolute paths (`/etc/hosts`) and symlinks inside the workspace that point outside it. Meanwhile, calling `fs::canonicalize` directly on `src/new_helper.rs` fails with `NotFound` when creating a new file. `resolve_path` normalizes lexical `.`/`..` segments, walks upward to the deepest existing ancestor directory, canonicalizes that ancestor to resolve symlinks, re-attaches the new path tail, and verifies `canonical.starts_with(&self.workspace_root)`.
2. **Direct binary execution with threaded pipe draining (`run_command`)**: Passing strings to `sh -c` invites `; curl ... | sh` injection. `run_command` checks that `program` is a bare allowlisted executable name (`cargo`, `rustc`, `rustfmt`, `git`, `ls`), spawns it directly with `current_dir(&self.workspace_root)`, drains `stdout` and `stderr` on background threads so a chatty test suite never deadlocks a full OS pipe buffer, and kills the child if it exceeds `command_timeout`.
3. **A minimal environment for every child (`env_clear`)**: By default, a spawned process inherits the harness's whole environment, including the API key `main.rs` reads at startup. A failing test that prints its environment would send that key back to the model with its output. `run_command` clears the environment and passes through only `PATH`, `HOME`, `TMPDIR`, `LANG` and the Cargo and rustup variables.

> **What this policy doesn't contain:** `SandboxPolicy` controls what the harness itself reads, writes and starts. It can't see what an allowed program does next. `cargo test` compiles and runs code the model can write, including tests and `build.rs`, with your account's permissions. Cargo and Git also read config files inside the workspace that can name other programs to run ([Cargo configuration](https://doc.rust-lang.org/cargo/reference/config.html), [git-config](https://git-scm.com/docs/git-config)). So a test that reads `/etc/hostname` or runs `sh -c` passes, even though `read_file` on the same path is denied. The cleared environment doesn't stop that code either. On Linux, it can still read the harness's original environment from `/proc`. Containing it takes an operating-system sandbox around the commands, such as bubblewrap on Linux or Seatbelt on macOS. Codex and Claude Code both use those for the commands they run ([Inside the Codex sandbox](https://openai.com/index/inside-the-codex-sandbox), [Claude Code sandboxing](https://code.claude.com/docs/en/sandboxing)). Until you add one, only point a live model at a workspace and machine you'd let it run code on.

Save this as `src/sandbox.rs`:

```rust
use crate::types::HarnessError;
use std::collections::BTreeSet;
use std::fs;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};

/// The only variables a spawned command inherits. Everything else in the
/// harness's environment, including the API key it read at startup, is dropped.
const INHERITED_ENV: &[&str] = &["PATH", "HOME", "TMPDIR", "LANG", "CARGO_HOME", "RUSTUP_HOME", "RUSTUP_TOOLCHAIN"];

#[derive(Debug, Clone)]
pub struct CommandOutput {
    pub exit_code: Option<i32>,
    pub stdout: String,
    pub stderr: String,
    pub timed_out: bool,
    pub duration_ms: u64,
}

#[derive(Debug, Clone)]
pub struct SandboxPolicy {
    workspace_root: PathBuf,
    allowed_commands: BTreeSet<String>,
    command_timeout: Duration,
}

impl SandboxPolicy {
    pub fn new(
        workspace_root: impl AsRef<Path>,
        allowed_commands: impl IntoIterator<Item = impl Into<String>>,
        command_timeout: Duration,
    ) -> Result<Self, HarnessError> {
        let canonical_root = fs::canonicalize(workspace_root.as_ref()).map_err(|e| {
            HarnessError::Config(format!("failed to canonicalize workspace '{}': {e}", workspace_root.as_ref().display()))
        })?;
        Ok(Self {
            workspace_root: canonical_root,
            allowed_commands: allowed_commands.into_iter().map(Into::into).collect(),
            command_timeout,
        })
    }

    pub fn default_for_workspace(root: impl AsRef<Path>) -> Result<Self, HarnessError> {
        Self::new(root, ["cargo", "rustc", "rustfmt", "git", "ls"], Duration::from_secs(30))
    }

    pub fn workspace_root(&self) -> &Path {
        &self.workspace_root
    }

    pub fn allowed_commands(&self) -> &BTreeSet<String> {
        &self.allowed_commands
    }

    /// Resolves candidate paths (including files not yet on disk) and rejects
    /// lexical traversals or symlinks escaping `workspace_root`.
    pub fn resolve_path(&self, raw_path: &str) -> Result<PathBuf, HarnessError> {
        let trimmed = raw_path.trim();
        if trimmed.is_empty() || trimmed.contains('\0') {
            return Err(HarnessError::PolicyViolation("invalid empty or NUL path".into()));
        }
        let input = Path::new(trimmed);
        let joined = if input.is_absolute() { input.to_path_buf() } else { self.workspace_root.join(input) };

        let mut normalized = PathBuf::new();
        for comp in joined.components() {
            match comp {
                Component::Prefix(p) => normalized.push(p.as_os_str()),
                Component::RootDir => normalized.push(comp.as_os_str()),
                Component::CurDir => {}
                Component::Normal(part) => normalized.push(part),
                Component::ParentDir => {
                    if !normalized.pop() {
                        return Err(HarnessError::PolicyViolation(format!("path '{raw_path}' escapes root")));
                    }
                }
            }
        }

        let mut existing = normalized.as_path();
        let mut tail_parts: Vec<&std::ffi::OsStr> = Vec::new();
        while !existing.exists() {
            let Some(name) = existing.file_name() else {
                return Err(HarnessError::PolicyViolation(format!("cannot resolve ancestor for '{raw_path}'")));
            };
            tail_parts.push(name);
            existing = existing.parent().ok_or_else(|| {
                HarnessError::PolicyViolation(format!("cannot resolve parent for '{raw_path}'"))
            })?;
        }

        let mut canonical = fs::canonicalize(existing).map_err(|e| {
            HarnessError::PolicyViolation(format!("canonicalize failed for '{}': {e}", existing.display()))
        })?;
        for part in tail_parts.into_iter().rev() {
            canonical.push(part);
        }

        if !canonical.starts_with(&self.workspace_root) {
            return Err(HarnessError::PolicyViolation(format!(
                "path '{raw_path}' resolves to '{}', outside workspace '{}'",
                canonical.display(),
                self.workspace_root.display()
            )));
        }
        Ok(canonical)
    }

    /// Spawns an allowlisted binary directly (never via `sh -c`) with a minimal
    /// environment, drains stdout and stderr on threads, and kills the child if
    /// it exceeds `command_timeout`.
    pub fn run_command(&self, program: &str, args: &[String]) -> Result<CommandOutput, HarnessError> {
        let binary = program.trim();
        if binary.is_empty() || binary.contains('/') || binary.contains('\\') {
            return Err(HarnessError::PolicyViolation(format!(
                "command '{program}' must be a bare allowlisted binary name"
            )));
        }
        if !self.allowed_commands.contains(binary) {
            let allowed: Vec<&str> = self.allowed_commands.iter().map(String::as_str).collect();
            return Err(HarnessError::PolicyViolation(format!(
                "command '{binary}' is not in the sandbox allowlist ({})",
                allowed.join(", ")
            )));
        }

        let start = Instant::now();
        let mut child = Command::new(binary)
            .args(args)
            .current_dir(&self.workspace_root)
            .env_clear()
            .envs(std::env::vars_os().filter(|(key, _)| INHERITED_ENV.iter().any(|name| key == *name)))
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;

        let mut out_pipe = child.stdout.take().expect("stdout piped");
        let mut err_pipe = child.stderr.take().expect("stderr piped");
        let out_thread = thread::spawn(move || {
            let mut buf = Vec::new();
            let _ = out_pipe.read_to_end(&mut buf);
            String::from_utf8_lossy(&buf).into_owned()
        });
        let err_thread = thread::spawn(move || {
            let mut buf = Vec::new();
            let _ = err_pipe.read_to_end(&mut buf);
            String::from_utf8_lossy(&buf).into_owned()
        });

        let mut timed_out = false;
        let exit_code = loop {
            if let Some(status) = child.try_wait()? {
                break status.code();
            }
            if start.elapsed() >= self.command_timeout {
                timed_out = true;
                let _ = child.kill();
                let _ = child.wait();
                break None;
            }
            thread::sleep(Duration::from_millis(10));
        };

        Ok(CommandOutput {
            exit_code,
            stdout: out_thread.join().unwrap_or_default(),
            stderr: err_thread.join().unwrap_or_default(),
            timed_out,
            duration_ms: start.elapsed().as_millis() as u64,
        })
    }
}
```

## Step 3: Bound tool observations on UTF-8 boundaries (`src/bounding.rs`)

One noisy `cargo test` run can emit 80 KB of diagnostics full of multi-byte UTF-8 box-drawing characters (`──`, `→`). Slicing `&output[..4000]` panics Rust whenever byte `4000` lands inside a three-byte character, and keeping only the top of the output cuts off Cargo's `failures:` summary at the bottom.

The fix is to show the model the beginning and the end of a long log, because that's where the first error and Cargo's `failures:` summary live. `bound_observation` reserves 60% of `max_bytes` for the head and 40% for the tail, walking `is_char_boundary` in both directions. Alongside it, `compact_history` replaces bulky `Role::Tool` outputs from older turns once the transcript passes `max_total_bytes`, preserving the system prompt, goal, and four most recent messages.

Save this as `src/bounding.rs`:

```rust
use crate::types::{Message, Role};

/// Keeps 60% head (compiler errors) and 40% tail (test summary), stepping to
/// valid UTF-8 `char` boundaries on both ends so multi-byte glyphs never panic.
pub fn bound_observation(text: &str, max_bytes: usize) -> (String, bool) {
    if text.len() <= max_bytes {
        return (text.to_string(), false);
    }
    let head_budget = (max_bytes * 3) / 5;
    let tail_budget = max_bytes.saturating_sub(head_budget);

    let mut head_end = head_budget.min(text.len());
    while head_end > 0 && !text.is_char_boundary(head_end) {
        head_end -= 1;
    }
    let mut tail_start = text.len().saturating_sub(tail_budget);
    while tail_start < text.len() && !text.is_char_boundary(tail_start) {
        tail_start += 1;
    }
    if head_end >= tail_start {
        return (text.to_string(), false);
    }

    let omitted = tail_start - head_end;
    (
        format!(
            "{}\n\n[... harness truncated {omitted} bytes to stay within observation budget ...]\n\n{}",
            &text[..head_end],
            &text[tail_start..]
        ),
        true,
    )
}

/// Replaces bulky older `Role::Tool` outputs once total transcript size crosses
/// `max_total_bytes`, leaving the system prompt, goal, and recent turns intact.
pub fn compact_history(messages: &mut [Message], max_total_bytes: usize, keep_recent: usize) -> usize {
    let mut total_bytes: usize = messages.iter().map(|m| m.content.len()).sum();
    if total_bytes <= max_total_bytes {
        return 0;
    }
    let protected_from = messages.len().saturating_sub(keep_recent);
    let mut compacted = 0;

    for msg in messages.iter_mut().take(protected_from) {
        if total_bytes <= max_total_bytes {
            break;
        }
        if msg.role != Role::Tool || msg.content.len() <= 240 || msg.content.starts_with("[compacted by harness:") {
            continue;
        }
        let orig = msg.content.len();
        let mut end = 120.min(orig);
        while end > 0 && !msg.content.is_char_boundary(end) {
            end -= 1;
        }
        let preview = msg.content[..end].lines().next().unwrap_or("").trim();
        let stub = format!("[compacted by harness: {orig} bytes from earlier turn; preview: \"{preview}\"]");
        if stub.len() < orig {
            total_bytes = total_bytes - orig + stub.len();
            msg.content = stub;
            compacted += 1;
        }
    }
    compacted
}
```

## Step 4: Build recoverable tools (`src/tools.rs`)

Models get edits wrong, so the tools need to make a bad edit cheap to recover from. `ToolRegistry` exposes JSON Schemas for `read_file`, `write_file`, `edit_file`, and `run_command` and routes every call through `SandboxPolicy` and `bound_observation`.

Look closely at `edit_file`: instead of overwriting whole files or trusting line numbers that drift after the first edit, it checks `current.matches(&p.old_text).count()` and requires **exactly one match**. Missing (`0`) or ambiguous (`>1`) targets return `is_error: true` prompting the model to read surrounding context lines first.

Save this as `src/tools.rs`:

```rust
use crate::bounding::bound_observation;
use crate::sandbox::SandboxPolicy;
use crate::types::{HarnessError, ToolCall, ToolSpec};
use serde::Deserialize;
use serde_json::json;
use std::fs;

#[derive(Debug, Clone)]
pub struct ToolExecution {
    pub output: String,
    pub is_error: bool,
    pub truncated: bool,
    pub policy_denied: bool,
}

pub struct ToolRegistry {
    sandbox: SandboxPolicy,
    max_observation_bytes: usize,
}

#[derive(Deserialize)]
struct ReadArgs { path: String, start_line: Option<usize>, end_line: Option<usize> }
#[derive(Deserialize)]
struct WriteArgs { path: String, content: String }
#[derive(Deserialize)]
struct EditArgs { path: String, old_text: String, new_text: String }
#[derive(Deserialize)]
struct CmdArgs { program: String, #[serde(default)] args: Vec<String> }

impl ToolRegistry {
    pub fn new(sandbox: SandboxPolicy, max_observation_bytes: usize) -> Self {
        Self { sandbox, max_observation_bytes }
    }

    pub fn sandbox(&self) -> &SandboxPolicy {
        &self.sandbox
    }

    pub fn specs(&self) -> Vec<ToolSpec> {
        let allowed: Vec<&str> = self.sandbox.allowed_commands().iter().map(String::as_str).collect();
        vec![
            ToolSpec {
                name: "read_file".into(),
                description: "Read UTF-8 text from a workspace file with line numbers.".into(),
                parameters: json!({
                    "type": "object",
                    "properties": {
                        "path": { "type": "string" },
                        "start_line": { "type": "integer" },
                        "end_line": { "type": "integer" }
                    },
                    "required": ["path"],
                    "additionalProperties": false
                }),
            },
            ToolSpec {
                name: "write_file".into(),
                description: "Create or overwrite a file inside the workspace.".into(),
                parameters: json!({
                    "type": "object",
                    "properties": { "path": { "type": "string" }, "content": { "type": "string" } },
                    "required": ["path", "content"],
                    "additionalProperties": false
                }),
            },
            ToolSpec {
                name: "edit_file".into(),
                description: "Replace an exact, unique text block inside a workspace file.".into(),
                parameters: json!({
                    "type": "object",
                    "properties": {
                        "path": { "type": "string" },
                        "old_text": { "type": "string" },
                        "new_text": { "type": "string" }
                    },
                    "required": ["path", "old_text", "new_text"],
                    "additionalProperties": false
                }),
            },
            ToolSpec {
                name: "run_command".into(),
                description: format!("Run an allowlisted command ({}).", allowed.join(", ")),
                parameters: json!({
                    "type": "object",
                    "properties": {
                        "program": { "type": "string" },
                        "args": { "type": "array", "items": { "type": "string" } }
                    },
                    "required": ["program"],
                    "additionalProperties": false
                }),
            },
        ]
    }

    pub fn execute(&self, call: &ToolCall) -> ToolExecution {
        let result = match call.name.as_str() {
            "read_file" => self.read_file(&call.arguments),
            "write_file" => self.write_file(&call.arguments),
            "edit_file" => self.edit_file(&call.arguments),
            "run_command" => self.run_command(&call.arguments),
            other => Err(HarnessError::Config(format!("unknown tool '{other}'"))),
        };

        match result {
            Ok((raw, is_error)) => {
                let (output, truncated) = bound_observation(&raw, self.max_observation_bytes);
                ToolExecution { output, is_error, truncated, policy_denied: false }
            }
            Err(err) => {
                let policy_denied = matches!(err, HarnessError::PolicyViolation(_));
                let (output, truncated) = bound_observation(&format!("Tool error: {err}"), self.max_observation_bytes);
                ToolExecution { output, is_error: true, truncated, policy_denied }
            }
        }
    }

    fn read_file(&self, args: &serde_json::Value) -> Result<(String, bool), HarnessError> {
        let p: ReadArgs = serde_json::from_value(args.clone())?;
        let content = fs::read_to_string(self.sandbox.resolve_path(&p.path)?)?;
        let lines: Vec<&str> = content.lines().collect();
        if lines.is_empty() {
            return Ok(("(empty file)".into(), false));
        }
        let start = p.start_line.unwrap_or(1).max(1);
        let end = p.end_line.unwrap_or(lines.len()).min(lines.len());
        if start > end {
            return Ok((format!("Invalid range {start}..={end}"), true));
        }
        let mut out = String::new();
        for (i, line) in lines[(start - 1)..end].iter().enumerate() {
            out.push_str(&format!("{:>4} | {line}\n", start + i));
        }
        Ok((out, false))
    }

    fn write_file(&self, args: &serde_json::Value) -> Result<(String, bool), HarnessError> {
        let p: WriteArgs = serde_json::from_value(args.clone())?;
        let target = self.sandbox.resolve_path(&p.path)?;
        if let Some(parent) = target.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(&target, &p.content)?;
        Ok((format!("Wrote {} bytes to '{}'.", p.content.len(), p.path), false))
    }

    fn edit_file(&self, args: &serde_json::Value) -> Result<(String, bool), HarnessError> {
        let p: EditArgs = serde_json::from_value(args.clone())?;
        if p.old_text.is_empty() {
            return Ok(("old_text must not be empty.".into(), true));
        }
        let target = self.sandbox.resolve_path(&p.path)?;
        let current = fs::read_to_string(&target)?;
        let count = current.matches(&p.old_text).count();
        if count == 0 {
            return Ok((format!("old_text not found in '{}'. Call read_file first.", p.path), true));
        }
        if count > 1 {
            return Ok((format!("old_text matched {count} places in '{}'; add surrounding lines.", p.path), true));
        }
        fs::write(&target, current.replacen(&p.old_text, &p.new_text, 1))?;
        Ok((format!("Updated '{}'.", p.path), false))
    }

    fn run_command(&self, args: &serde_json::Value) -> Result<(String, bool), HarnessError> {
        let p: CmdArgs = serde_json::from_value(args.clone())?;
        let out = self.sandbox.run_command(&p.program, &p.args)?;
        if out.timed_out {
            return Ok((format!("Command '{} {}' timed out after {} ms.", p.program, p.args.join(" "), out.duration_ms), true));
        }
        let code = out.exit_code.unwrap_or(-1);
        Ok((format!("exit_code: {code} ({} ms)\nstdout:\n{}\nstderr:\n{}", out.duration_ms, out.stdout.trim_end(), out.stderr.trim_end()), code != 0))
    }
}
```

## Step 5: Translate one transcript into OpenAI, Gemini, and Claude requests (`src/provider.rs`)

Every provider wants the same conversation in a slightly different shape. Behind the single `ModelProvider` trait, `src/provider.rs` implements three backends:

1. **`OpenAiCompatibleProvider`**: Covers OpenAI (`https://api.openai.com/v1`), Google Gemini (`https://generativelanguage.googleapis.com/v1beta/openai`), and local servers like Ollama (`http://localhost:11434/v1`). It uses `max_completion_tokens` instead of the deprecated `max_tokens` field, omits `temperature` for reasoning-model compatibility, and wraps malformed tool JSON into `_malformed_json` so the loop can recover. It also keeps each tool call's `extra_content` and sends it back unchanged, because Gemini 3 models reject the next request with HTTP 400 when a call's thought signature is missing ([Google's thought signature rules](https://ai.google.dev/gemini-api/docs/thought-signatures)).
2. **`AnthropicProvider`**: Targets Anthropic's `/v1/messages` endpoint, hoisting `Role::System` into top-level `"system"`, mapping `parameters` to `"input_schema"`, and merging adjacent `Role::Tool` messages into one `"role": "user"` content array so parallel tool calls never trigger HTTP 400.
3. **`ScriptedProvider`**: Replays deterministic `ModelResponse` turns offline so you can test the harness in milliseconds with zero API keys.

![Side-by-side comparison of OpenAI-compatible and Anthropic Messages requests translated from the same internal Message vector in provider.rs.](https://www.devguides.com/api/media?path=devguides%2F8f6b6a61-d3c6-4277-8bf5-0cd4e1a800cd%2F8377f4a3-aa82-41c4-8292-d047d47d223a.png)

Save this as `src/provider.rs`:

```rust
use crate::types::{HarnessError, Message, ModelResponse, Role, TokenUsage, ToolCall, ToolSpec};
use serde_json::{json, Value};
use std::collections::VecDeque;
use std::fs;
use std::path::Path;

pub trait ModelProvider {
    fn complete(&mut self, messages: &[Message], tools: &[ToolSpec]) -> Result<ModelResponse, HarnessError>;
}

pub struct OpenAiCompatibleProvider {
    base_url: String,
    api_key: String,
    model: String,
    max_completion_tokens: u32,
}

impl OpenAiCompatibleProvider {
    pub fn new(base_url: impl Into<String>, api_key: impl Into<String>, model: impl Into<String>, max_completion_tokens: u32) -> Self {
        Self { base_url: base_url.into().trim_end_matches('/').to_string(), api_key: api_key.into(), model: model.into(), max_completion_tokens }
    }

    pub fn build_request_body(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Value, HarnessError> {
        let mut wire_msgs = Vec::with_capacity(messages.len());
        for m in messages {
            match m.role {
                Role::System => wire_msgs.push(json!({ "role": "system", "content": m.content })),
                Role::User => wire_msgs.push(json!({ "role": "user", "content": m.content })),
                Role::Tool => wire_msgs.push(json!({
                    "role": "tool",
                    "tool_call_id": m.tool_call_id.clone().unwrap_or_default(),
                    "content": m.content
                })),
                Role::Assistant if m.tool_calls.is_empty() => {
                    wire_msgs.push(json!({ "role": "assistant", "content": m.content }));
                }
                Role::Assistant => {
                    let calls: Vec<Value> = m.tool_calls.iter().map(|tc| {
                        let mut call = json!({
                            "id": tc.id,
                            "type": "function",
                            "function": { "name": tc.name, "arguments": serde_json::to_string(&tc.arguments)? }
                        });
                        // Gemini 3 returns HTTP 400 if a call's thought signature doesn't come back unchanged.
                        if let Some(extra) = &tc.extra_content {
                            call["extra_content"] = extra.clone();
                        }
                        Ok(call)
                    }).collect::<Result<_, serde_json::Error>>()?;
                    let content = if m.content.is_empty() { Value::Null } else { json!(m.content) };
                    wire_msgs.push(json!({ "role": "assistant", "content": content, "tool_calls": calls }));
                }
            }
        }
        let wire_tools: Vec<Value> = tools.iter().map(|s| json!({
            "type": "function",
            "function": { "name": s.name, "description": s.description, "parameters": s.parameters }
        })).collect();

        Ok(json!({
            "model": self.model,
            "messages": wire_msgs,
            "tools": wire_tools,
            "max_completion_tokens": self.max_completion_tokens
        }))
    }

    pub fn parse_response(payload: &Value) -> Result<ModelResponse, HarnessError> {
        let msg = &payload["choices"].get(0).ok_or_else(|| HarnessError::Provider("no choices".into()))?["message"];

        let mut tool_calls = Vec::new();
        if let Some(arr) = msg["tool_calls"].as_array() {
            for item in arr {
                let raw = item["function"]["arguments"].as_str().unwrap_or("{}");
                let args = serde_json::from_str(raw).unwrap_or_else(|_| json!({ "_malformed_json": raw }));
                let mut call = ToolCall::new(
                    item["id"].as_str().unwrap_or("call_0"),
                    item["function"]["name"].as_str().unwrap_or("unknown"),
                    args,
                );
                call.extra_content = item.get("extra_content").filter(|v| !v.is_null()).cloned();
                tool_calls.push(call);
            }
        }
        Ok(ModelResponse {
            content: msg["content"].as_str().unwrap_or("").to_string(),
            tool_calls,
            usage: TokenUsage {
                input_tokens: payload["usage"]["prompt_tokens"].as_u64().unwrap_or(0),
                output_tokens: payload["usage"]["completion_tokens"].as_u64().unwrap_or(0),
            },
        })
    }
}

impl ModelProvider for OpenAiCompatibleProvider {
    fn complete(&mut self, messages: &[Message], tools: &[ToolSpec]) -> Result<ModelResponse, HarnessError> {
        let url = format!("{}/chat/completions", self.base_url);
        let mut req = ureq::post(&url).set("Content-Type", "application/json");
        if !self.api_key.is_empty() {
            req = req.set("Authorization", &format!("Bearer {}", self.api_key));
        }
        let resp = req.send_json(self.build_request_body(messages, tools)?).map_err(|e| match e {
            ureq::Error::Status(code, r) => HarnessError::Provider(format!("HTTP {code} from {url}: {}", r.into_string().unwrap_or_default())),
            ureq::Error::Transport(t) => HarnessError::Provider(format!("transport error calling {url}: {t}")),
        })?;
        let payload: Value = resp.into_json().map_err(|e| HarnessError::Provider(format!("invalid JSON: {e}")))?;
        Self::parse_response(&payload)
    }
}

pub struct AnthropicProvider {
    base_url: String,
    api_key: String,
    model: String,
    max_tokens: u32,
}

impl AnthropicProvider {
    pub fn new(base_url: impl Into<String>, api_key: impl Into<String>, model: impl Into<String>, max_tokens: u32) -> Self {
        Self { base_url: base_url.into().trim_end_matches('/').to_string(), api_key: api_key.into(), model: model.into(), max_tokens }
    }

    pub fn build_request_body(&self, messages: &[Message], tools: &[ToolSpec]) -> Value {
        let mut system_parts = Vec::new();
        let mut wire_msgs = Vec::new();
        let mut i = 0;
        while i < messages.len() {
            match messages[i].role {
                Role::System => { system_parts.push(messages[i].content.as_str()); i += 1; }
                Role::User => { wire_msgs.push(json!({ "role": "user", "content": messages[i].content })); i += 1; }
                Role::Assistant => {
                    let mut blocks = Vec::new();
                    if !messages[i].content.is_empty() {
                        blocks.push(json!({ "type": "text", "text": messages[i].content }));
                    }
                    for tc in &messages[i].tool_calls {
                        blocks.push(json!({ "type": "tool_use", "id": tc.id, "name": tc.name, "input": tc.arguments }));
                    }
                    wire_msgs.push(json!({ "role": "assistant", "content": blocks }));
                    i += 1;
                }
                Role::Tool => {
                    let mut results = Vec::new();
                    while i < messages.len() && messages[i].role == Role::Tool {
                        results.push(json!({
                            "type": "tool_result",
                            "tool_use_id": messages[i].tool_call_id.clone().unwrap_or_default(),
                            "content": messages[i].content,
                            "is_error": messages[i].is_error,
                        }));
                        i += 1;
                    }
                    wire_msgs.push(json!({ "role": "user", "content": results }));
                }
            }
        }
        let wire_tools: Vec<Value> = tools.iter().map(|s| json!({
            "name": s.name, "description": s.description, "input_schema": s.parameters
        })).collect();

        json!({
            "model": self.model,
            "max_tokens": self.max_tokens,
            "system": system_parts.join("\n\n"),
            "messages": wire_msgs,
            "tools": wire_tools
        })
    }
}

impl ModelProvider for AnthropicProvider {
    fn complete(&mut self, messages: &[Message], tools: &[ToolSpec]) -> Result<ModelResponse, HarnessError> {
        let url = format!("{}/messages", self.base_url);
        let resp = ureq::post(&url)
            .set("Content-Type", "application/json")
            .set("x-api-key", &self.api_key)
            .set("anthropic-version", "2023-06-01")
            .send_json(self.build_request_body(messages, tools))
            .map_err(|e| match e {
                ureq::Error::Status(code, r) => HarnessError::Provider(format!("HTTP {code} from {url}: {}", r.into_string().unwrap_or_default())),
                ureq::Error::Transport(t) => HarnessError::Provider(format!("transport error calling {url}: {t}")),
            })?;
        let payload: Value = resp.into_json().map_err(|e| HarnessError::Provider(format!("invalid JSON: {e}")))?;

        let mut text = Vec::new();
        let mut tool_calls = Vec::new();
        if let Some(blocks) = payload["content"].as_array() {
            for b in blocks {
                match b["type"].as_str() {
                    Some("text") => if let Some(t) = b["text"].as_str() { text.push(t); },
                    Some("tool_use") => tool_calls.push(ToolCall::new(
                        b["id"].as_str().unwrap_or("toolu_0"),
                        b["name"].as_str().unwrap_or("unknown"),
                        b["input"].clone(),
                    )),
                    _ => {}
                }
            }
        }
        Ok(ModelResponse {
            content: text.join("\n"),
            tool_calls,
            usage: TokenUsage {
                input_tokens: payload["usage"]["input_tokens"].as_u64().unwrap_or(0),
                output_tokens: payload["usage"]["output_tokens"].as_u64().unwrap_or(0),
            },
        })
    }
}

pub struct ScriptedProvider {
    turns: VecDeque<ModelResponse>,
}

impl ScriptedProvider {
    pub fn from_responses(responses: impl IntoIterator<Item = ModelResponse>) -> Self {
        Self { turns: responses.into_iter().collect() }
    }

    pub fn from_json_file(path: impl AsRef<Path>) -> Result<Self, HarnessError> {
        Ok(Self::from_responses(serde_json::from_str::<Vec<ModelResponse>>(&fs::read_to_string(path)?)?))
    }

    pub fn builtin_lab_demo() -> Self {
        Self::from_responses(vec![
            ModelResponse::new(
                "Let me inspect `src/lib.rs` to see why `parse_duration` is failing.",
                vec![ToolCall::new("call_1", "read_file", json!({ "path": "src/lib.rs" }))],
                310, 48,
            ),
            ModelResponse::new(
                "I see `input` is never trimmed before matching suffixes. Let me add `.trim()`.",
                vec![ToolCall::new("call_2", "edit_file", json!({
                    "path": "src/lib.rs",
                    "old_text": "pub fn parse_duration_ms(input: &str) -> Result<u64, DurationError> {\n    if input.is_empty() {",
                    "new_text": "pub fn parse_duration_ms(input: &str) -> Result<u64, DurationError> {\n    let input = input.trim();\n    if input.is_empty() {"
                }))],
                540, 92,
            ),
            ModelResponse::new("Fixed `parse_duration_ms` by trimming leading and trailing whitespace.", vec![], 610, 28),
            ModelResponse::new(
                "The verification gate caught `parses_milliseconds` failing with `InvalidNumber(\"250m\")` because `strip_suffix('s')` matched `\"250ms\"` before `strip_suffix(\"ms\")`. Let me check `\"ms\"` first.",
                vec![ToolCall::new("call_3", "edit_file", json!({
                    "path": "src/lib.rs",
                    "old_text": "    if let Some(num) = input.strip_suffix('s') {\n        let secs = parse_u64(num)?;\n        return Ok(secs * 1_000);\n    }\n    if let Some(num) = input.strip_suffix(\"ms\") {\n        return parse_u64(num);\n    }",
                    "new_text": "    if let Some(num) = input.strip_suffix(\"ms\") {\n        return parse_u64(num);\n    }\n    if let Some(num) = input.strip_suffix('s') {\n        let secs = parse_u64(num)?;\n        return Ok(secs * 1_000);\n    }"
                }))],
                890, 115,
            ),
            ModelResponse::new(
                "Both bugs are now resolved: input whitespace is trimmed, and the `\"ms\"` suffix is matched before `'s'` so millisecond inputs no longer leave a trailing `'m'`.",
                vec![], 980, 46,
            ),
        ])
    }

    pub fn builtin_security_demo() -> Self {
        Self::from_responses(vec![
            ModelResponse::new(
                "Checking host files and network connectivity first.",
                vec![
                    ToolCall::new("sec_1", "read_file", json!({ "path": "../../etc/hosts" })),
                    ToolCall::new("sec_2", "run_command", json!({ "program": "curl", "args": ["-sS", "https://example.com"] })),
                ],
                280, 64,
            ),
            ModelResponse::new(
                "Both outside-workspace file access and `curl` were blocked by the sandbox policy. Reading `Cargo.toml` inside the workspace instead.",
                vec![ToolCall::new("sec_3", "read_file", json!({ "path": "Cargo.toml" }))],
                430, 52,
            ),
            ModelResponse::new("Confirmed sandbox boundaries: only files under the workspace root and allowlisted binaries are accessible.", vec![], 520, 31),
        ])
    }
}

impl ModelProvider for ScriptedProvider {
    fn complete(&mut self, _messages: &[Message], _tools: &[ToolSpec]) -> Result<ModelResponse, HarnessError> {
        self.turns.pop_front().ok_or_else(|| HarnessError::Provider("scripted provider ran out of turns".into()))
    }
}
```

## Step 6: Stream structured trajectories to `trace.jsonl` (`src/trace.rs`)

When an agent fails on turn 8, terminal scrollback rarely shows why. `TraceLogger` appends one self-contained JSON object per event to `trace.jsonl` and flushes immediately, letting you tail live runs with `jq` or audit policy denials after the fact.

Save this as `src/trace.rs`:

```rust
use crate::types::{HarnessError, StopReason, TokenUsage};
use serde::Serialize;
use serde_json::Value;
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Debug, Serialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum TraceEvent<'a> {
    RunStarted { timestamp_ms: u128, workspace: &'a str, goal: &'a str, verify_command: Option<&'a str>, max_turns: usize },
    ContextCompacted { timestamp_ms: u128, turn: usize, messages_compacted: usize },
    ModelTurn { timestamp_ms: u128, turn: usize, assistant_text: &'a str, tool_call_names: Vec<&'a str>, input_tokens: u64, output_tokens: u64 },
    ToolExecuted { timestamp_ms: u128, turn: usize, tool_call_id: &'a str, tool_name: &'a str, arguments: &'a Value, is_error: bool, truncated: bool, policy_denied: bool },
    VerificationChecked { timestamp_ms: u128, turn: usize, command: &'a str, passed: bool, exit_code: Option<i32> },
    RunFinished { timestamp_ms: u128, stop_reason: StopReason, turns_used: usize, tool_calls_made: usize, policy_denials: usize, verification_runs: usize, total_usage: TokenUsage },
}

pub struct TraceLogger {
    file: File,
}

impl TraceLogger {
    pub fn new(path: impl AsRef<Path>) -> Result<Self, HarnessError> {
        let p: PathBuf = path.as_ref().to_path_buf();
        if let Some(parent) = p.parent().filter(|d| !d.as_os_str().is_empty()) {
            fs::create_dir_all(parent)?;
        }
        Ok(Self { file: OpenOptions::new().create(true).append(true).open(p)? })
    }

    pub fn now_ms() -> u128 {
        SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0)
    }

    pub fn record(&mut self, event: &TraceEvent<'_>) -> Result<(), HarnessError> {
        writeln!(self.file, "{}", serde_json::to_string(event)?)?;
        Ok(self.file.flush()?)
    }
}
```

## Step 7: Wire the turn loop and verification stop gate (`src/runner.rs`)

This is where the pieces come together. `HarnessRunner::run` drives every turn inside `for turn in 1..=self.config.max_turns`:

1. Compact older tool observations if transcript size exceeds `max_context_bytes`.
2. Call `self.provider.complete(&messages, &tool_specs)` and log `TraceEvent::ModelTurn`.
3. Enforce the `max_total_tokens` circuit breaker.
4. If `tool_calls` is non-empty, execute each tool inside the sandbox, append bounded `Role::Tool` results, and continue to the next turn.
5. If `tool_calls` is empty, the model wants to stop. When `--verify` is configured, the harness runs that command inside the sandbox first. It returns `StopReason::Completed` on exit code `0`, or it injects a `[Verification Gate Failed]` message with the bounded test output and keeps the loop going when checks fail.

Save this as `src/runner.rs`:

```rust
use crate::bounding::{bound_observation, compact_history};
use crate::provider::ModelProvider;
use crate::tools::ToolRegistry;
use crate::trace::{TraceEvent, TraceLogger};
use crate::types::{HarnessError, Message, RunReport, StopReason, TokenUsage};
use std::path::PathBuf;

pub const DEFAULT_SYSTEM_PROMPT: &str = "\
You are a disciplined software engineering agent operating inside a sandboxed workspace.
1. Read relevant files with `read_file` before editing them.
2. Make minimal, targeted changes with `edit_file` or `write_file`.
3. Verify changes with `run_command` before declaring completion.
4. Respect workspace boundaries and allowlisted commands.";

#[derive(Debug, Clone)]
pub struct HarnessConfig {
    pub max_turns: usize,
    pub max_total_tokens: u64,
    pub max_context_bytes: usize,
    pub max_observation_bytes: usize,
    pub verify_command: Option<Vec<String>>,
    pub trace_path: PathBuf,
    pub verbose: bool,
}

impl HarnessConfig {
    pub fn new(trace_path: PathBuf) -> Self {
        Self { max_turns: 12, max_total_tokens: 100_000, max_context_bytes: 32_000, max_observation_bytes: 4_000, verify_command: None, trace_path, verbose: false }
    }
}

#[derive(Default)]
struct Counters {
    tool_calls_made: usize,
    policy_denials: usize,
    verification_runs: usize,
    compactions: usize,
    total_usage: TokenUsage,
}

pub struct HarnessRunner<'a> {
    provider: &'a mut dyn ModelProvider,
    tools: ToolRegistry,
    config: HarnessConfig,
}

impl<'a> HarnessRunner<'a> {
    pub fn new(provider: &'a mut dyn ModelProvider, tools: ToolRegistry, config: HarnessConfig) -> Self {
        Self { provider, tools, config }
    }

    fn finish(&self, trace: &mut TraceLogger, stop_reason: StopReason, turns_used: usize, final_answer: String, c: &Counters) -> Result<RunReport, HarnessError> {
        trace.record(&TraceEvent::RunFinished {
            timestamp_ms: TraceLogger::now_ms(),
            stop_reason,
            turns_used,
            tool_calls_made: c.tool_calls_made,
            policy_denials: c.policy_denials,
            verification_runs: c.verification_runs,
            total_usage: c.total_usage,
        })?;
        Ok(RunReport {
            stop_reason, final_answer, turns_used,
            tool_calls_made: c.tool_calls_made,
            policy_denials: c.policy_denials,
            verification_runs: c.verification_runs,
            compactions: c.compactions,
            total_usage: c.total_usage,
            trace_path: self.config.trace_path.clone(),
        })
    }

    pub fn run(&mut self, goal: &str) -> Result<RunReport, HarnessError> {
        let mut trace = TraceLogger::new(&self.config.trace_path)?;
        let verify_str = self.config.verify_command.as_ref().map(|p| p.join(" "));
        let ws = self.tools.sandbox().workspace_root().display().to_string();

        trace.record(&TraceEvent::RunStarted {
            timestamp_ms: TraceLogger::now_ms(),
            workspace: &ws,
            goal,
            verify_command: verify_str.as_deref(),
            max_turns: self.config.max_turns,
        })?;

        let specs = self.tools.specs();
        let mut messages = vec![Message::system(DEFAULT_SYSTEM_PROMPT), Message::user(goal)];
        let mut c = Counters::default();
        let mut last_answer = String::new();

        for turn in 1..=self.config.max_turns {
            let compacted = compact_history(&mut messages, self.config.max_context_bytes, 4);
            if compacted > 0 {
                c.compactions += compacted;
                trace.record(&TraceEvent::ContextCompacted { timestamp_ms: TraceLogger::now_ms(), turn, messages_compacted: compacted })?;
            }

            let resp = self.provider.complete(&messages, &specs)?;
            c.total_usage.accumulate(resp.usage);
            let names: Vec<&str> = resp.tool_calls.iter().map(|t| t.name.as_str()).collect();
            trace.record(&TraceEvent::ModelTurn {
                timestamp_ms: TraceLogger::now_ms(),
                turn,
                assistant_text: &resp.content,
                tool_call_names: names,
                input_tokens: resp.usage.input_tokens,
                output_tokens: resp.usage.output_tokens,
            })?;

            if self.config.verbose && !resp.content.trim().is_empty() {
                eprintln!("[turn {turn}] model: {}", resp.content.trim());
            }
            if c.total_usage.total() > self.config.max_total_tokens {
                return self.finish(&mut trace, StopReason::TokenBudgetExceeded, turn, resp.content, &c);
            }

            last_answer = resp.content.clone();
            let calls = resp.tool_calls.clone();
            messages.push(Message::assistant(resp.content, resp.tool_calls));

            if !calls.is_empty() {
                for call in &calls {
                    c.tool_calls_made += 1;
                    if self.config.verbose {
                        eprintln!("[turn {turn}] tool -> {}({})", call.name, call.arguments);
                    }
                    let out = self.tools.execute(call);
                    if out.policy_denied {
                        c.policy_denials += 1;
                    }
                    if self.config.verbose && out.is_error {
                        eprintln!("[turn {turn}]   ! {}", out.output.lines().next().unwrap_or(""));
                    }
                    trace.record(&TraceEvent::ToolExecuted {
                        timestamp_ms: TraceLogger::now_ms(),
                        turn,
                        tool_call_id: &call.id,
                        tool_name: &call.name,
                        arguments: &call.arguments,
                        is_error: out.is_error,
                        truncated: out.truncated,
                        policy_denied: out.policy_denied,
                    })?;
                    messages.push(Message::tool_result(&call.id, out.output, out.is_error));
                }
                continue;
            }

            if let Some(parts) = &self.config.verify_command {
                if let Some((prog, args)) = parts.split_first() {
                    c.verification_runs += 1;
                    let cmd = parts.join(" ");
                    let check = self.tools.sandbox().run_command(prog, args)?;
                    let passed = !check.timed_out && check.exit_code == Some(0);
                    trace.record(&TraceEvent::VerificationChecked { timestamp_ms: TraceLogger::now_ms(), turn, command: &cmd, passed, exit_code: check.exit_code })?;

                    if !passed {
                        let raw = format!("stdout:\n{}\nstderr:\n{}", check.stdout.trim_end(), check.stderr.trim_end());
                        let (bounded, _) = bound_observation(&raw, self.config.max_observation_bytes);
                        if self.config.verbose {
                            eprintln!("[turn {turn}] verification gate FAILED (`{cmd}`, exit {:?}) — continuing loop", check.exit_code);
                        }
                        messages.push(Message::user(format!(
                            "[Verification Gate Failed]\nYour turn ended without passing `{cmd}` (exit {:?}). Fix the root cause and try again:\n\n{bounded}",
                            check.exit_code
                        )));
                        continue;
                    }
                    if self.config.verbose {
                        eprintln!("[turn {turn}] verification gate PASSED (`{cmd}`)");
                    }
                }
            }
            return self.finish(&mut trace, StopReason::Completed, turn, last_answer, &c);
        }
        self.finish(&mut trace, StopReason::MaxTurnsReached, self.config.max_turns, last_answer, &c)
    }
}
```

## Step 8: Add the CLI and broken lab fixture (`src/main.rs`)

`src/main.rs` wires two `clap` subcommands:

- `harness init-lab [DIR]`: Generates a self-contained broken Rust crate (`duration-lab`) with four unit tests for `parse_duration_ms`.
- `harness run`: Runs the harness loop against a workspace using `scripted`, `openai`, `gemini`, or `anthropic`.

Save this as `src/main.rs`:

```rust
use agent_harness::provider::{AnthropicProvider, ModelProvider, OpenAiCompatibleProvider, ScriptedProvider};
use agent_harness::runner::{HarnessConfig, HarnessRunner};
use agent_harness::sandbox::SandboxPolicy;
use agent_harness::tools::ToolRegistry;
use agent_harness::types::{HarnessError, StopReason};
use clap::{Args, Parser, Subcommand, ValueEnum};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Duration;

const LAB_CARGO_TOML: &str = "[package]\nname = \"duration-lab\"\nversion = \"0.1.0\"\nedition = \"2021\"\n";

const LAB_LIB_RS: &str = r#"#[derive(Debug, PartialEq, Eq)]
pub enum DurationError { Empty, InvalidNumber(String), UnknownUnit(String) }

pub fn parse_duration_ms(input: &str) -> Result<u64, DurationError> {
    if input.is_empty() {
        return Err(DurationError::Empty);
    }
    if let Some(num) = input.strip_suffix('s') {
        let secs = parse_u64(num)?;
        return Ok(secs * 1_000);
    }
    if let Some(num) = input.strip_suffix("ms") {
        return parse_u64(num);
    }
    if let Some(num) = input.strip_suffix('m') {
        return Ok(parse_u64(num)? * 60_000);
    }
    Err(DurationError::UnknownUnit(input.to_string()))
}

fn parse_u64(raw: &str) -> Result<u64, DurationError> {
    raw.parse::<u64>().map_err(|_| DurationError::InvalidNumber(raw.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test] fn parses_seconds_and_minutes() { assert_eq!(parse_duration_ms("5s"), Ok(5_000)); assert_eq!(parse_duration_ms("2m"), Ok(120_000)); }
    #[test] fn trims_surrounding_whitespace() { assert_eq!(parse_duration_ms("  12s \n"), Ok(12_000)); }
    #[test] fn parses_milliseconds() { assert_eq!(parse_duration_ms("250ms"), Ok(250)); }
    #[test] fn rejects_empty_and_unknown_units() { assert_eq!(parse_duration_ms("   "), Err(DurationError::Empty)); assert_eq!(parse_duration_ms("10h"), Err(DurationError::UnknownUnit("10h".into()))); }
}
"#;

#[derive(Parser, Debug)]
#[command(name = "harness", version, about = "Minimal security-hardened AI coding harness in Rust")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    InitLab { #[arg(default_value = "./lab-workspace")] dir: PathBuf, #[arg(long)] force: bool },
    Run(Box<RunArgs>),
}

#[derive(Args, Debug)]
struct RunArgs {
    #[arg(long, default_value = ".")] workspace: PathBuf,
    #[arg(long, default_value = "Fix the bugs in `src/lib.rs` so every unit test passes.")] goal: String,
    #[arg(long, value_enum, default_value_t = ProviderKind::Scripted)] provider: ProviderKind,
    #[arg(long, value_enum, default_value_t = ScriptScenario::Bugfix)] scenario: ScriptScenario,
    #[arg(long)] script: Option<PathBuf>,
    #[arg(long)] model: Option<String>,
    #[arg(long)] base_url: Option<String>,
    #[arg(long)] verify: Option<String>,
    #[arg(long, default_value_t = 12)] max_turns: usize,
    #[arg(long, default_value_t = 100_000)] max_tokens: u64,
    #[arg(long, default_value_t = 4_000)] max_observation_bytes: usize,
    #[arg(long, default_value_t = 30)] timeout_secs: u64,
    #[arg(long, value_delimiter = ',', default_value = "cargo,rustc,rustfmt,git,ls")] allow_cmd: Vec<String>,
    #[arg(long)] trace_file: Option<PathBuf>,
    #[arg(long, short)] verbose: bool,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum ProviderKind { Scripted, Openai, Gemini, Anthropic }

#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum ScriptScenario { Bugfix, Security }

fn init_lab(dir: &Path, force: bool) -> Result<(), HarnessError> {
    let lib = dir.join("src").join("lib.rs");
    if lib.exists() && !force {
        return Err(HarnessError::Config(format!("'{}' exists; pass --force to reset.", lib.display())));
    }
    fs::create_dir_all(dir.join("src"))?;
    fs::write(dir.join("Cargo.toml"), LAB_CARGO_TOML)?;
    fs::write(&lib, LAB_LIB_RS)?;
    println!("Initialized broken `duration-lab` crate at {}", dir.display());
    Ok(())
}

fn require_env(var: &str) -> Result<String, HarnessError> {
    env::var(var).ok().filter(|v| !v.trim().is_empty()).ok_or_else(|| HarnessError::Config(format!("`{var}` is not set")))
}

fn execute() -> Result<ExitCode, HarnessError> {
    match Cli::parse().command {
        Commands::InitLab { dir, force } => { init_lab(&dir, force)?; Ok(ExitCode::SUCCESS) }
        Commands::Run(boxed) => {
            let a = *boxed;
            let sandbox = SandboxPolicy::new(&a.workspace, a.allow_cmd, Duration::from_secs(a.timeout_secs))?;
            let trace_path = a.trace_file.unwrap_or_else(|| sandbox.workspace_root().join("trace.jsonl"));
            let verify_command = a.verify.map(|s| s.split_whitespace().map(String::from).collect::<Vec<_>>()).filter(|v| !v.is_empty());

            let cfg = HarnessConfig {
                max_turns: a.max_turns, max_total_tokens: a.max_tokens, max_context_bytes: 32_000,
                max_observation_bytes: a.max_observation_bytes, verify_command, trace_path, verbose: a.verbose,
            };
            let tools = ToolRegistry::new(sandbox, a.max_observation_bytes);

            let mut provider: Box<dyn ModelProvider> = match a.provider {
                ProviderKind::Scripted => match a.script {
                    Some(p) => Box::new(ScriptedProvider::from_json_file(p)?),
                    None if a.scenario == ScriptScenario::Security => Box::new(ScriptedProvider::builtin_security_demo()),
                    None => Box::new(ScriptedProvider::builtin_lab_demo()),
                },
                ProviderKind::Openai => {
                    let key = env::var("OPENAI_API_KEY").unwrap_or_default();
                    let url = a.base_url.unwrap_or_else(|| "https://api.openai.com/v1".into());
                    if url.starts_with("https://api.openai.com") && key.trim().is_empty() {
                        return Err(HarnessError::Config("OPENAI_API_KEY is required".into()));
                    }
                    Box::new(OpenAiCompatibleProvider::new(url, key, a.model.unwrap_or_else(|| "gpt-5.4".into()), 4096))
                }
                ProviderKind::Gemini => Box::new(OpenAiCompatibleProvider::new(
                    a.base_url.unwrap_or_else(|| "https://generativelanguage.googleapis.com/v1beta/openai".into()),
                    require_env("GEMINI_API_KEY")?,
                    a.model.unwrap_or_else(|| "gemini-3.8-flash".into()),
                    4096,
                )),
                ProviderKind::Anthropic => Box::new(AnthropicProvider::new(
                    a.base_url.unwrap_or_else(|| "https://api.anthropic.com/v1".into()),
                    require_env("ANTHROPIC_API_KEY")?,
                    a.model.unwrap_or_else(|| "claude-sonnet-4-6".into()),
                    4096,
                )),
            };

            let report = HarnessRunner::new(provider.as_mut(), tools, cfg).run(&a.goal)?;
            println!("Stop reason:       {:?}\nTurns used:        {}\nTool calls:        {}\nPolicy denials:    {}\nVerification runs: {}\nTokens (in/out):   {} / {}\nTrajectory log:    {}\n\nFinal answer:\n{}",
                report.stop_reason, report.turns_used, report.tool_calls_made, report.policy_denials, report.verification_runs,
                report.total_usage.input_tokens, report.total_usage.output_tokens, report.trace_path.display(), report.final_answer);
            Ok(if report.stop_reason == StopReason::Completed { ExitCode::SUCCESS } else { ExitCode::from(2) })
        }
    }
}

fn main() -> ExitCode {
    match execute() {
        Ok(c) => c,
        Err(e) => { eprintln!("Error: {e}"); ExitCode::FAILURE }
    }
}
```

## Step 9: Verify with Clippy and end-to-end integration tests (`tests/harness_integration.rs`)

Add `tests/harness_integration.rs` to test the compiled `harness` binary end to end. The tests confirm that an unverified run stops early while a `--verify "cargo test --quiet"` run catches the remaining bug and passes all tests, and they check sandbox denials, process timeouts, the minimal environment for spawned commands and that a Gemini thought signature survives the round trip:

```rust
use agent_harness::provider::{OpenAiCompatibleProvider, ScriptedProvider};
use agent_harness::runner::{HarnessConfig, HarnessRunner};
use agent_harness::sandbox::SandboxPolicy;
use agent_harness::tools::ToolRegistry;
use agent_harness::types::{Message, StopReason};
use serde_json::json;
use std::fs;
use std::process::Command;
use std::time::Duration;
use tempfile::TempDir;

fn harness_bin() -> &'static str {
    env!("CARGO_BIN_EXE_harness")
}

#[test]
fn unverified_run_stops_early_while_verified_run_self_heals() {
    let dir = TempDir::new().expect("tempdir");
    let lab = dir.path().join("lab");

    assert!(Command::new(harness_bin()).args(["init-lab", lab.to_str().unwrap()]).status().unwrap().success());

    // Without `--verify`, Turn 3 stops while `250ms` still fails.
    let unverified = Command::new(harness_bin())
        .args(["run", "--workspace", lab.to_str().unwrap(), "--provider", "scripted"])
        .output()
        .expect("run unverified");
    assert!(String::from_utf8_lossy(&unverified.stdout).contains("Turns used:        3"));
    assert!(!Command::new("cargo").args(["test", "--quiet"]).current_dir(&lab).status().unwrap().success());

    // Reset and run WITH `--verify "cargo test --quiet"`.
    assert!(Command::new(harness_bin()).args(["init-lab", lab.to_str().unwrap(), "--force"]).status().unwrap().success());
    let verified = Command::new(harness_bin())
        .args(["run", "--workspace", lab.to_str().unwrap(), "--provider", "scripted", "--verify", "cargo test --quiet"])
        .output()
        .expect("run verified");
    assert!(verified.status.success());
    assert!(String::from_utf8_lossy(&verified.stdout).contains("Turns used:        5"));
    assert!(Command::new("cargo").args(["test", "--quiet"]).current_dir(&lab).status().unwrap().success());
}

#[test]
fn sandbox_denials_and_command_timeouts_are_enforced() {
    let dir = TempDir::new().expect("tempdir");
    fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n").unwrap();

    let sandbox = SandboxPolicy::default_for_workspace(dir.path()).unwrap();
    let cfg = HarnessConfig::new(dir.path().join("trace.jsonl"));
    let mut provider = ScriptedProvider::builtin_security_demo();
    let report = HarnessRunner::new(&mut provider, ToolRegistry::new(sandbox, 4_000), cfg).run("Audit").unwrap();
    assert_eq!(report.stop_reason, StopReason::Completed);
    assert_eq!(report.policy_denials, 2);

    let fast_timeout = SandboxPolicy::new(dir.path(), ["sleep"], Duration::from_millis(100)).unwrap();
    assert!(fast_timeout.run_command("sleep", &["5".into()]).unwrap().timed_out);
}

#[test]
fn spawned_commands_get_a_minimal_environment() {
    // Cargo sets CARGO_MANIFEST_DIR for this test process, so it stands in for
    // any secret in the harness's environment, such as an API key.
    assert!(std::env::var_os("CARGO_MANIFEST_DIR").is_some());
    let dir = TempDir::new().expect("tempdir");
    let sandbox = SandboxPolicy::new(dir.path(), ["env"], Duration::from_secs(5)).unwrap();
    let out = sandbox.run_command("env", &[]).unwrap();
    assert!(out.stdout.lines().any(|line| line.starts_with("PATH=")));
    assert!(!out.stdout.lines().any(|line| line.starts_with("CARGO_MANIFEST_DIR=")));
}

#[test]
fn gemini_thought_signature_survives_the_round_trip() {
    // The shape of a Gemini 3 tool call on the OpenAI-compatible endpoint.
    let payload = json!({
        "choices": [{ "message": { "role": "assistant", "content": null, "tool_calls": [{
            "id": "call_1",
            "type": "function",
            "function": { "name": "read_file", "arguments": "{\"path\":\"src/lib.rs\"}" },
            "extra_content": { "google": { "thought_signature": "sig-A" } }
        }] } }],
        "usage": { "prompt_tokens": 12, "completion_tokens": 4 }
    });
    let resp = OpenAiCompatibleProvider::parse_response(&payload).unwrap();
    let history = vec![
        Message::user("Fix the failing test."),
        Message::assistant(resp.content, resp.tool_calls),
        Message::tool_result("call_1", "pub fn parse_duration_ms() {}", false),
    ];
    let provider = OpenAiCompatibleProvider::new("http://localhost:1", "", "gemini-3.8-flash", 256);
    let body = provider.build_request_body(&history, &[]).unwrap();
    assert_eq!(body["messages"][1]["tool_calls"][0]["extra_content"]["google"]["thought_signature"], "sig-A");
}
```

Run Clippy and the test suite:

```bash
cargo clippy --all-targets -- -D warnings
cargo test
```

Both commands should finish cleanly with zero warnings and passing tests.

## Lab: Put your AI harness through four experiments

Now let's break things on purpose and watch the harness respond. Experiments 1 to 3 run completely offline against the compiled `harness` binary, so you don't need an API key until Experiment 4.

### Experiment 1: Watch an unverified agent stop with a broken test

Scaffold `duration-lab` into `/tmp/duration-lab` and run its test suite:

```bash
cargo run --quiet -- init-lab /tmp/duration-lab
(cd /tmp/duration-lab && cargo test --quiet)
```

Three of the four tests fail initially because `parse_duration_ms` has **two** bugs:

1. **Bug 1**: `input` is never `.trim()`med, so `"  12s \n"` and `"   "` both return `UnknownUnit`.
2. **Bug 2**: `input.strip_suffix('s')` runs **before** `input.strip_suffix("ms")`, so `"250ms"` strips `'s'` first and fails trying to parse `"250m"` as an integer (`InvalidNumber("250m")`).

Run `harness` **without** `--verify`:

```bash
cargo run --quiet -- run \
  --workspace /tmp/duration-lab \
  --provider scripted \
  --verbose
```

```text
[turn 1] model: Let me inspect `src/lib.rs` to see why `parse_duration` is failing.
[turn 1] tool -> read_file({"path":"src/lib.rs"})
[turn 2] model: I see `input` is never trimmed before matching suffixes. Let me add `.trim()`.
[turn 2] tool -> edit_file({"new_text":"pub fn parse_duration_ms(input: &str) -> Result<u64, DurationError> {\n    let input = input.trim();\n    if input.is_empty() {","old_text":"pub fn parse_duration_ms(input: &str) -> Result<u64, DurationError> {\n    if input.is_empty() {","path":"src/lib.rs"})
[turn 3] model: Fixed `parse_duration_ms` by trimming leading and trailing whitespace.
Stop reason:       Completed
Turns used:        3
Tool calls:        2
Verification runs: 0
```

The model fixed Bug 1 and stopped on Turn 3, leaving `parses_milliseconds` broken (`3 passed; 1 failed`). It said it was done, and nothing in the loop checked.

### Experiment 2: Turn on `--verify` and watch Turn 3 self-heal

Reset `/tmp/duration-lab` with `--force` and add `--verify "cargo test --quiet"`:

![Comparison of an unverified 3-turn run that leaves a millisecond parsing bug broken versus a 5-turn verified run that intercepts the premature stop and passes all tests.](https://www.devguides.com/api/media?path=devguides%2F8f6b6a61-d3c6-4277-8bf5-0cd4e1a800cd%2F24c9a0e4-e617-414d-b343-304a2f573810.png)

```bash
cargo run --quiet -- init-lab /tmp/duration-lab --force
rm -f /tmp/duration-lab/trace.jsonl

cargo run --quiet -- run \
  --workspace /tmp/duration-lab \
  --provider scripted \
  --verify "cargo test --quiet" \
  --verbose
```

```text
[turn 1] model: Let me inspect `src/lib.rs` to see why `parse_duration` is failing.
[turn 1] tool -> read_file({"path":"src/lib.rs"})
[turn 2] model: I see `input` is never trimmed before matching suffixes. Let me add `.trim()`.
[turn 2] tool -> edit_file(...)
[turn 3] model: Fixed `parse_duration_ms` by trimming leading and trailing whitespace.
[turn 3] verification gate FAILED (`cargo test --quiet`, exit Some(101)) — continuing loop
[turn 4] model: The verification gate caught `parses_milliseconds` failing with `InvalidNumber("250m")` because `strip_suffix('s')` matched `"250ms"` before `strip_suffix("ms")`. Let me check `"ms"` first.
[turn 4] tool -> edit_file(...)
[turn 5] model: Both bugs are now resolved: input whitespace is trimmed, and the `"ms"` suffix is matched before `'s'` so millisecond inputs no longer leave a trailing `'m'`.
[turn 5] verification gate PASSED (`cargo test --quiet`)
Stop reason:       Completed
Turns used:        5
Tool calls:        3
Verification runs: 2
```

Query `trace.jsonl` with `jq` to inspect the full event timeline:

```bash
jq -c '{event, turn, tool_name, passed, stop_reason}' /tmp/duration-lab/trace.jsonl
```

```json
{"event":"run_started","turn":null,"tool_name":null,"passed":null,"stop_reason":null}
{"event":"model_turn","turn":1,"tool_name":null,"passed":null,"stop_reason":null}
{"event":"tool_executed","turn":1,"tool_name":"read_file","passed":null,"stop_reason":null}
{"event":"model_turn","turn":2,"tool_name":null,"passed":null,"stop_reason":null}
{"event":"tool_executed","turn":2,"tool_name":"edit_file","passed":null,"stop_reason":null}
{"event":"model_turn","turn":3,"tool_name":null,"passed":null,"stop_reason":null}
{"event":"verification_checked","turn":3,"tool_name":null,"passed":false,"stop_reason":null}
{"event":"model_turn","turn":4,"tool_name":null,"passed":null,"stop_reason":null}
{"event":"tool_executed","turn":4,"tool_name":"edit_file","passed":null,"stop_reason":null}
{"event":"model_turn","turn":5,"tool_name":null,"passed":null,"stop_reason":null}
{"event":"verification_checked","turn":5,"tool_name":null,"passed":true,"stop_reason":null}
{"event":"run_finished","turn":null,"tool_name":null,"passed":null,"stop_reason":"completed"}
```

The scripted model and the starting files are the same in both runs. The only difference is that the harness ran the tests before it believed the model.

### Experiment 3: Trip the sandbox policy gate

Run `--scenario security` to watch `SandboxPolicy` block both a `../../etc/hosts` traversal and an unallowlisted `curl` invocation without crashing the agent loop:

```bash
cargo run --quiet -- run \
  --workspace /tmp/duration-lab \
  --provider scripted \
  --scenario security \
  --trace-file /tmp/duration-lab/security-trace.jsonl \
  --verbose
```

```text
[turn 1] model: Checking host files and network connectivity first.
[turn 1] tool -> read_file({"path":"../../etc/hosts"})
[turn 1]   ! Tool error: sandbox policy violation: path '../../etc/hosts' resolves to '/private/etc/hosts', outside workspace '/private/tmp/duration-lab'
[turn 1] tool -> run_command({"args":["-sS","https://example.com"],"program":"curl"})
[turn 1]   ! Tool error: sandbox policy violation: command 'curl' is not in the sandbox allowlist (cargo, git, ls, rustc, rustfmt)
[turn 2] model: Both outside-workspace file access and `curl` were blocked by the sandbox policy. Reading `Cargo.toml` inside the workspace instead.
[turn 2] tool -> read_file({"path":"Cargo.toml"})
[turn 3] model: Confirmed sandbox boundaries: only files under the workspace root and allowlisted binaries are accessible.
Stop reason:       Completed
Policy denials:    2
```

Notice that the agent didn't crash. Each denial came back to the model as an error it could read, and it changed course on the next turn.

### Experiment 4: Point `harness` at OpenAI, Gemini, Claude, or Ollama

Reset `/tmp/duration-lab` and run the exact same verification loop against a live model:

```bash
cargo run --quiet -- init-lab /tmp/duration-lab --force

# OpenAI
OPENAI_API_KEY="sk-..." cargo run --quiet -- run \
  --workspace /tmp/duration-lab --provider openai --model gpt-5.4 \
  --verify "cargo test --quiet" --verbose

# Google Gemini
GEMINI_API_KEY="AIza..." cargo run --quiet -- run \
  --workspace /tmp/duration-lab --provider gemini --model gemini-3.8-flash \
  --verify "cargo test --quiet" --verbose

# Anthropic Claude
ANTHROPIC_API_KEY="sk-ant-..." cargo run --quiet -- run \
  --workspace /tmp/duration-lab --provider anthropic --model claude-sonnet-4-6 \
  --verify "cargo test --quiet" --verbose

# Local Ollama (no cloud API key)
cargo run --quiet -- run \
  --workspace /tmp/duration-lab --provider openai \
  --base-url http://localhost:11434/v1 --model qwen2.5-coder:14b \
  --verify "cargo test --quiet" --verbose
```

## Diagnose common harness failure modes

| Symptom | Root cause in a naive loop | Fix in `agent-harness` |
| --- | --- | --- |
| Repeated `edit_file` failures | Model guesses indentation without reading current lines | `edit_file` rejects `0` or `>1` matches and prompts a `read_file` call first |
| Hung test suite freezes the agent | Child blocks or fills the OS stdout pipe buffer | `SandboxPolicy::run_command` drains pipes on threads and kills the child at `timeout_secs` |
| Anthropic HTTP 400 after multi-tool turns | Consecutive `"role": "user"` messages sent per tool result | `AnthropicProvider` merges adjacent `Role::Tool` items into one `user` content array |
| Panic while truncating compiler output | Byte slice lands inside multi-byte UTF-8 (`→`, `─`) | `bound_observation` steps to `is_char_boundary` on both the 60% head and 40% tail |
| A test reads files outside the workspace or finds the API key | The allowlist checks which program starts, not the code that program runs | `run_command` clears the environment. Containing the code itself takes an OS sandbox around the commands (Step 2) |
| Gemini HTTP 400 "Function call is missing a thought_signature" after the first tool call | The wire layer drops `tool_calls[].extra_content` when it rebuilds the history | `ToolCall.extra_content` keeps the signature, and `build_request_body` sends it back unchanged |

> **Final takeaway:** Every capability you add next, such as an OS sandbox for commands, MCP client connections, git worktree isolation, human approval gates or subagent delegation, belongs in deterministic harness modules with explicit invariants and tests. Never leave it as a wish in the system prompt.

That's the lesson from Lemkin's database, too. A rule the model is asked to follow is a request. A rule the harness enforces is a boundary. I hope that this has been a helpful guide to what an AI harness is and how to build one. If you extend it, tell me in the discussion below which capability you added and what broke first.
