Coding tutorial · Build it from scratch

Build an Agent Harness From Scratch

We start from an eight-line loop and add each piece it is missing, until the agent can find a bug, fix it, run the tests and show its work.

Coding agentsTool callingSandboxing

A working coding agent. It reads a repository, searches it, edits code, runs the tests, sees the failure, repairs it and checks the fix. Every action lands in a log you can replay.

Time
About three hours
Hardware
Any laptop CPU. Docker is optional, for step 8. No GPU.
You need
Python 3.10+, git, pytest. The harness uses only the standard library. PyTorch and Transformers are for the real-model run.
Package
harness
Final repo tree c10-agent-harness/
c10-agent-harness/
├── README.md  # how to run everything, results table
├── conftest.py
├── harness/  # the package
│   ├── __init__.py
│   ├── agent.py  # step 19: the full loop
│   ├── compaction.py  # step 15: summarise old turns
│   ├── context.py  # step 10: what the model sees
│   ├── editing.py  # step 6: edit formats and the applier
│   ├── events.py  # step 14: the JSONL event log
│   ├── fs_tools.py  # step 4: read, list, write, read-before-write
│   ├── git_tools.py  # step 17: status, diff, log, checkpoints
│   ├── loop_minimal.py  # step 1: the eight-line loop
│   ├── messages.py  # step 1: messages, calls, responses
│   ├── parsing.py  # step 3: text to structured calls
│   ├── permissions.py  # step 9: risk levels and the policy
│   ├── planning.py  # step 13: the checklist
│   ├── replay.py  # step 14: log to transcript
│   ├── repomap.py  # step 12: the repository map
│   ├── sandbox.py  # steps 5 and 8: process core, both backends
│   ├── search.py  # step 11: text search and symbols
│   ├── shell.py  # step 5: the shell tool
│   ├── tokens.py  # step 10: the token estimate
│   ├── tools.py  # step 2: schemas, validation, execution
│   ├── toolset.py  # step 19: the default tools and presets
│   ├── tracing.py  # step 18: spans and the summary
│   ├── truncation.py  # step 16: giant outputs
│   ├── verify.py  # step 7: tests, lint, typecheck, build
│   └── models/  # step 1 and 19: one interface, three clients
│       ├── __init__.py
│       ├── base.py
│       ├── hf_local.py
│       ├── openai_compat.py
│       └── scripted.py
├── examples/
│   └── toy_repo/  # a small project with one real bug
├── scripts/  # runnable entry points
│   ├── compare_trusted.py
│   ├── demo_docker_sandbox.py
│   ├── demo_fix_test.py
│   ├── minimal_loop.py
│   ├── run_hf_agent.py
│   ├── run_openai_agent.py
│   └── show_schemas.py
├── benchmarks/  # scripts that print the tables in this post
│   ├── bench_compaction.py
│   ├── bench_edit_formats.py
│   ├── bench_overheads.py
│   └── bench_truncation.py
├── tests/  # pytest suite
│   ├── helpers.py
│   ├── test_agent.py
│   ├── test_docker_sandbox.py
│   ├── test_editing.py
│   ├── test_fs_shell_sandbox.py
│   ├── test_git_models.py
│   ├── test_repo_context.py
│   ├── test_tools_and_parsing.py
│   └── test_verify_permissions.py
└── results/  # saved real outputs
    ├── bench_compaction.txt
    ├── bench_edit_formats.txt
    ├── bench_overheads.txt
    ├── bench_truncation.txt
    ├── compaction_series.json
    ├── compare_trusted.txt
    ├── demo_events.jsonl
    ├── demo_output.txt
    ├── docker_sandbox.txt
    ├── hf_events.jsonl
    ├── hf_output.txt
    ├── minimal_loop.txt
    ├── openai_stub_output.txt
    └── schemas.txt

The plan

A model can write a tool call. What else has to exist before it can fix a failing test on its own, without hurting anything?

That extra code is the harness. We build it the way this series builds everything. We write the simplest version, run it, watch it fail, and add the piece that fixes the failure. We start with an eight-line loop and end with about 3,300 lines of small modules.

The theory post explains why harnesses look the way they do. Here we write one and measure it.

The design reasoning inInside an AI agent harness

Most of the tutorial uses a scripted model. It replies from a fixed list, so every run is the same. That is not a shortcut around the hard part, because the tools, the tests, the edits and the permission checks all run for real. It lets us test the harness without needing a model that behaves. Step 19 connects a real model and reports what happened.

Clone the repo once.

$ git clone https://github.com/srini-anirudh/blog-coding-tutorials.git
$ cd blog-coding-tutorials
$ python -m venv .venv && .venv/bin/pip install -e ".[dev]"

That install is for the whole series, so it pulls PyTorch, Transformers, Datasets and more. For this tutorial alone, .venv/bin/pip install pytest is enough until the real model in step 19 and the real tokenizer in step 2. We checked that lighter install with minimal_loop.py, demo_fix_test.py and two test files.

Commands run from the repo root. A terminal that needs the tutorial folder starts with cd c10-agent-harness and ends with cd ... Where no script exists for a check, the terminal holds a short Python snippet to paste, and the output below it comes from that snippet.

A note on the numbers. Token counts and pass or fail counts below come from scripted runs and do not depend on the machine. Timings do, so each one names its hardware. Most saved files in results/ end with a hardware: line that the script does not print. We move it to the label on the output block.

Step 01

Write the minimal loop

Goal An agent in eight lines, and a clear list of the ways it fails.

An agent is a loop. Call the model. If it asks for a tool, run the tool, add the result to the context, and call the model again. If it does not ask for a tool, stop.

def run_minimal(model, tools: dict[str, Callable[..., str]], task: str) -> list[dict]:
    context = [{"role": "user", "content": task}]
    while True:
        response = model.complete(context, tools=[])
        context.append(response.to_message().to_dict())
        if response.final:
            break
        for call in response.tool_calls:
            result = tools[call.name](**call.arguments)
            context.append({"role": "tool", "tool_call_id": call.id, "content": str(result)})
    return context
Listing 1The whole agent, in its first form. The highlighted lines are the loop.

Read it line by line. The context is a plain list of messages, and it starts with the task. model.complete takes the list and returns a response. We append that response at once, because the model must see its own past calls on the next turn. If the response is final we stop. Otherwise we run each call and append each result.

Nothing here is a tensor. The object that flows around this loop is a list of dictionaries, so this table does the job a shape table does in other tutorials.

The messages in the context, in the format Hugging Face chat templates accept
RoleFieldsMeaning
userrole, contentThe task.
assistantrole, content, tool_callsWhat the model said, and zero or more calls.
tool_calls[i]id, type, function.name, function.argumentsOne requested call. We keep the arguments as a dict.
toolrole, content, tool_call_idA result, tied to the call it answers by id.

OpenAI-compatible servers want function.arguments as a JSON string, not a dict. to_wire in openai_compat.py converts them on the way out.

The model is a ScriptedModel. It takes a list of raw replies and returns them in order. It parses each one with the same parser a real model's text goes through, so a badly formed reply breaks the same way.

    def final(self) -> bool:
        return not self.tool_calls and not self.parse_errors
Listing 2The stop rule. A reply with a parse error is not final, and this detail matters in a moment.

Run the script. It does one good run and then breaks the loop in three ways.

$ .venv/bin/python c10-agent-harness/scripts/minimal_loop.py
--- a good run ---
user       'What is 2 + 3?' 
assistant  '' ["add({'a': 2, 'b': 3})"]
tool       '5' 
assistant  '2 + 3 = 5.' 

--- break 1: the model names a tool that does not exist ---
the whole run dies: KeyError 'multiply'

--- break 2: the arguments do not fit the function ---
the whole run dies: TypeError <lambda>() missing 1 required positional argument: 'b'

--- break 3: a malformed call (a real model would repeat this forever) ---
no tool ran, no error reached the model, and the loop called it 5 times until the script ran out

Figure 1The eight-line loop running. The first seven frames are the good run. The last three are the failures from the script output above.

Checkpoint

  • The good run ends with four messages: user, assistant, tool, assistant.
  • You can say why the third break does not raise anything.
Step 02

Generate tool schemas from functions

Goal Write a Python function once, and get the schema the model reads from it.

The minimal loop passes tools=[], so the model knows nothing about what it can call. A model learns its tools from a JSON schema: a name, a description and the arguments. We could write those by hand. Then the schema and the function would drift apart, and the model would read a description of code that no longer exists.

So we generate the schema. The function's signature gives the types and the docstring gives the words.

How the schema reaches the model inHow language models learn to use tools
def build_tool(fn: Callable[..., Any], name: str | None = None,
               risk: Risk | Callable[[dict], Risk] = Risk.READ) -> Tool:
    """Inspect `fn` and build its Tool, including the JSON schema."""
    hints = typing.get_type_hints(fn)
    summary, param_docs = parse_docstring(fn.__doc__)
    props: dict[str, Any] = {}
    required: list[str] = []
    context_param = None
    for pname, p in inspect.signature(fn).parameters.items():
        hint = hints.get(pname, str)
        if hint is ToolContext:
            context_param = pname
            continue
        prop = type_to_schema(hint)
        if pname in param_docs:
            prop["description"] = param_docs[pname]
        if p.default is inspect.Parameter.empty:
            required.append(pname)
        elif p.default is not None:
            prop["default"] = p.default.value if isinstance(p.default, enum.Enum) else p.default
        props[pname] = prop
    params = {"type": "object", "properties": props, "required": required,
              "additionalProperties": False}
    return Tool(name or fn.__name__, fn, summary, params, risk, context_param)
Listing 3Building a tool from a function. The highlighted lines handle the injected context and decide what is required.

A parameter annotated ToolContext is skipped. That is how a tool gets the workspace and the sandbox without the model ever seeing them. A parameter with no default is required. A default of None means optional, with nothing written into the schema.

The types go through one small function.

def type_to_schema(tp: Any) -> dict[str, Any]:
    """Translate one type hint into a JSON-schema fragment."""
    if tp in _PRIMITIVES:
        return dict(_PRIMITIVES[tp])
    if inspect.isclass(tp) and issubclass(tp, enum.Enum):
        return {"type": "string", "enum": [m.value for m in tp]}
    origin, args = get_origin(tp), get_args(tp)
    if origin is Literal:
        kinds = {type(a) for a in args}
        base = type_to_schema(kinds.pop()) if len(kinds) == 1 else {}
        return {**base, "enum": list(args)}
    if origin in (Union, types.UnionType):
        non_null = [a for a in args if a is not type(None)]
        if len(non_null) == 1:            # Optional[X]: nullability is expressed by "not required"
            return type_to_schema(non_null[0])
        return {"anyOf": [type_to_schema(a) for a in non_null]}
    if origin in (list, tuple, set, frozenset):
        return {"type": "array", "items": type_to_schema(args[0])} if args else {"type": "array"}
    if origin is dict:
        return {"type": "object"}
    raise TypeError(f"no JSON schema for type hint {tp!r}")
Listing 4Type hints to JSON schema. An optional type arrives as a union, and we keep the non-null part. An unknown hint raises at import time, not at call time.

Figure 2Each part of read_file and the schema field it becomes. Blue marks a mapping. Orange marks a parameter that is removed.

Now look at the real output and at what it costs. A schema is not free. It goes into the prompt on every turn.

$ .venv/bin/python c10-agent-harness/scripts/show_schemas.py --tokenizer Qwen/Qwen2.5-0.5B-Instruct
preset         tools  estimate  tokenizer
full              20      3160       1676
minimal            4       834        453
small-model        5       998        537

tool                      estimate  tokenizer
read_file                      195        108
list_dir                       163         85
write_file                     155         79
edit_file                      237        128
apply_patch                    144         82
search                         218        118
find_files                     141         77
find_symbol                    133         71
repo_map                       171         94
run_command                    213        117
run_tests                      179        100
run_linter                     136         72
run_typecheck                  133         70
build                          129         67
update_plan                    179        102
git_status                      89         48
git_diff                       157         81
git_log                        111         57
checkpoint                     129         67
revert_to_checkpoint           127         70

text              estimate  tokenizer   ratio
english prose          320        321    1.00
python code           2580       2241    1.15
json schemas          3160       1676    1.89

The estimate column is our cheap token counter from step 10. The tokenizer column is a real tokenizer. Prose matches almost exactly. JSON is overcounted by 1.89 times, because the estimate treats every brace and quote as its own token. We will come back to that.

Checkpoint

  • show_schemas.py prints the schema for read_file, with no ctx in it.
  • You can predict the schema of a new function before you run it.
Step 03

Parse and validate tool calls

Goal Turn all three failures from step 1 into messages the model can act on.

A tool call is text until we parse it. Models trained on the Hermes format write it inside a tag.

<tool_call>
{"name": "read_file", "arguments": {"path": "calc.py"}}
</tool_call>

Two jobs follow. Parsing asks whether this is a well-formed call. Validation asks whether this call fits a tool we have. They fail differently, so they are separate.

def _decode_call(blob: str) -> tuple[ToolCall | None, str | None]:
    """Decode one JSON blob into a ToolCall, or explain why not."""
    try:
        obj: Any = json.loads(blob)
    except json.JSONDecodeError as e:
        snippet = blob[max(0, e.pos - 30): e.pos + 30].replace("\n", "\\n")
        return None, f"invalid JSON in tool call ({e.msg} at char {e.pos}): ...{snippet}..."
    if not isinstance(obj, dict):
        return None, f"tool call must be a JSON object, got {type(obj).__name__}"
    name = obj.get("name")
    if not isinstance(name, str) or not name:
        return None, 'tool call needs a string "name" field'
    args = obj.get("arguments", obj.get("parameters", {}))
    if isinstance(args, str):           # some models double-encode the arguments
        try:
            args = json.loads(args) if args.strip() else {}
        except json.JSONDecodeError as e:
            return None, f"arguments for {name!r} are a string that is not valid JSON ({e.msg})"
    if not isinstance(args, dict):
        return None, f"arguments for {name!r} must be a JSON object"
    return ToolCall(name=name, arguments=args, raw=blob), None
Listing 5Decoding one call. It returns a call or an explanation, and never raises. The highlighted lines forgive two slips that real models make.

The parser is strict about structure and forgiving about small things. Some models write parameters instead of arguments, and some encode the arguments as a JSON string. Both are safe to repair. A broken string is not, so it becomes an error with the position and a snippet of the text around it.

Validation runs after parsing, against the schema we generated in step 2.

    def validate(self, call: ToolCall) -> list[str]:
        """Return a list of human-readable problems; empty means the call may run.

        Coerced values are written back into `call.arguments`.
        """
        if call.name not in self._tools:
            return [f"unknown tool {call.name!r}; available tools: {', '.join(self.names)}"]
        if not isinstance(call.arguments, dict):
            return [f"arguments must be a JSON object, got {type(call.arguments).__name__}"]
        params = self._tools[call.name].parameters
        props = params["properties"]
        errors = [f"missing required argument {r!r}" for r in params["required"] if r not in call.arguments]
        for key, value in list(call.arguments.items()):
            if key not in props:
                errors.append(f"unexpected argument {key!r}; allowed: {', '.join(props) or 'none'}")
                continue
            if self.coerce:
                value = call.arguments[key] = _coerce(value, props[key])
            errors += check_value(value, props[key], key)
        return errors
Listing 6Validation reports every problem at once, so the model fixes them in one retry instead of several.

The small helper _coerce accepts a quoted number such as "12" for an integer field, because small models often write that. You can turn it off with coerce=False.

A call can pass both checks and still fail, because the tool itself can have a bug. So execution catches everything.

    def execute(self, call: ToolCall, ctx: ToolContext | None = None) -> ToolOutput:
        """Run a validated call. Exceptions become error outputs, never crashes."""
        t = self._tools[call.name]
        kwargs = dict(call.arguments)
        if t.context_param:
            kwargs[t.context_param] = ctx
        try:
            out = t.fn(**kwargs)
        except ToolError as e:
            return ToolOutput(f"Error: {e}", is_error=True)
        except Exception as e:  # a tool bug must not kill the loop; the model sees a short report
            return ToolOutput(f"Error: {type(e).__name__}: {e}", is_error=True)
        return out if isinstance(out, ToolOutput) else ToolOutput(str(out))
Listing 7Exceptions become error outputs. A ToolError is a message we wrote for the model. Anything else is a bug, and the model gets a short report instead of the loop dying.

In the full loop, an error of either kind goes back to the model. format_call_errors writes the message, and the loop counts consecutive failures. After four in a row it stops with the status protocol_errors. That closes the third break from step 1: the model hears about the problem, and the retries have a limit.

Checkpoint

  • A malformed call is not a final answer, and the model gets told why.
  • A wrong tool name returns a list of the right names. It does not raise.
Step 04

Add filesystem tools

Goal Read, list, search, write and patch, with every path held inside the workspace.

A coding agent needs five operations on files. They live in different modules, because search and patching are big enough to deserve their own steps.

The five filesystem operations
OperationToolWhere
readread_fileThis step
listlist_dirThis step
writewrite_fileThis step
searchsearch, find_files, find_symbolStep 11
patchedit_file, apply_patchStep 6

Two small pieces of code do the safety work.

def resolve(ctx: ToolContext, path: str) -> Path:
    """Workspace-relative path to an absolute one; refuse anything that escapes the root."""
    root = Path(ctx.workspace).resolve()
    full = (root / path).resolve()
    if not full.is_relative_to(root):
        raise ToolError(f"path {path!r} is outside the workspace")
    return full
Listing 8The path check. resolve() follows symlinks first, so a link that points outside the workspace is caught too.
class FileTracker:
    """Remembers the content hash of every file the model has seen."""

    seen: dict[str, str] = field(default_factory=dict)

    def mark_read(self, path: Path, text: str) -> None:
        self.seen[str(path)] = digest(text)

    def check_fresh(self, path: Path) -> None:
        """Raise unless the model's last view of `path` matches what is on disk."""
        if not path.exists():
            return  # creating a new file needs no prior read
        key = str(path)
        if key not in self.seen:
            raise ToolError(f"read {path.name} before editing it")
        if self.seen[key] != digest(path.read_text()):
            raise ToolError(f"{path.name} changed since you last read it; read it again before editing")
Listing 9Read-before-write. The tracker remembers a hash of what the model last saw, and refuses an edit if the file on disk differs.

The tracker needs a reason. A model edits from memory. If the file changed since it read it, or it never read it at all, then the edit is based on a view of the file that is out of date. That is a silent way to lose someone's work. The check costs the model one more read, and it prevents that loss.

read_file returns numbered lines. Models refer to line numbers, and a real file has no line numbers to quote. It also stops at 400 lines unless asked for more, and it says so in the output.

def read_file(ctx: ToolContext, path: str, start: int = 1, end: int | None = None) -> str:
    """Read a text file and return it with line numbers.

    Args:
        path: File path relative to the workspace root.
        start: First line to show (1-based).
        end: Last line to show (inclusive). Omit to read up to 400 lines.
    """
    full = resolve(ctx, path)
    if not full.is_file():
        raise ToolError(f"no such file: {path}")
    text = full.read_text(errors="replace")
    if ctx.files is not None:
        ctx.files.mark_read(full, text)
    lines = text.splitlines()
    end = min(end or start + 399, len(lines))
    body = number_lines("\n".join(lines[start - 1:end]), start)
    more = f"\n[lines {start}-{end} of {len(lines)}]" if end < len(lines) or start > 1 else ""
    return body + more
Listing 10The read tool. Note the call to mark_read: reading is what earns the right to edit.

Checkpoint

  • test_paths_cannot_escape_the_workspace and test_symlink_escape_is_blocked pass.
  • test_write_requires_a_fresh_read passes.
Step 05

Add the shell tool

Goal Run a command, and report exit code, stdout and stderr, with a timeout that actually kills everything.

The obvious version is subprocess.run(command, shell=True, capture_output=True, timeout=60). It looks finished. We tried it with a command that starts a background child, the way a test server or a build tool does.

$ cd c10-agent-harness
$ ../.venv/bin/python - <<'EOF'
import os, subprocess, tempfile, time
from pathlib import Path

with tempfile.TemporaryDirectory() as d:
    pidfile = Path(d) / "child.pid"
    t0 = time.monotonic()
    try:
        subprocess.run(["/bin/sh", "-c", f"sleep 30 & echo $! > {pidfile}; sleep 30"],
                       capture_output=True, timeout=1)
    except subprocess.TimeoutExpired:
        print(f"timeout path: raised after {time.monotonic() - t0:.1f}s")
    pid = int(pidfile.read_text())
    os.kill(pid, 0)                            # raises if the child is gone
    print("background child still alive: True")
    os.kill(pid, 9)
t0 = time.monotonic()
r = subprocess.run(["/bin/sh", "-c", "sleep 3 & echo done"], capture_output=True, text=True)
print(f"normal path: run() returned after {time.monotonic() - t0:.1f}s with {r.stdout.strip()!r}")
EOF
$ cd ..
timeout path: raised after 1.0s
background child still alive: True
normal path: run() returned after 3.0s with 'done'

That shows two real bugs. When the timeout fires, Python kills only the process it started, and the background child lives on. In a loop that runs for hours, those children add up. In the normal path, the shell exits at once but the background child still holds the output pipe, so the call waits for that child. A model that runs server & would block the agent.

The fix is to give each command its own process group, and to act on the whole group.

def run_process(argv: list[str], cwd: Path, env: dict[str, str], timeout_s: float,
                preexec: Callable[[], None] | None = None, memory_mb: int | None = None,
                capture_bytes: int = 1_000_000, label: str | None = None,
                on_kill: Callable[[], None] | None = None) -> ExecResult:
    """Run argv in its own session; enforce the timeout and memory cap on the whole group."""
    start = time.monotonic()
    proc = subprocess.Popen(argv, cwd=cwd, env=env, stdin=subprocess.DEVNULL,
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                            start_new_session=True, preexec_fn=preexec)
    pgid = proc.pid  # start_new_session makes the child a group leader
    out, err = _Capture(capture_bytes), _Capture(capture_bytes)
    readers = [threading.Thread(target=_pump, args=(proc.stdout, out), daemon=True),
               threading.Thread(target=_pump, args=(proc.stderr, err), daemon=True)]
    for t in readers:
        t.start()

    killed: str | None = None
    ticks = 0
    while proc.poll() is None:
        ticks += 1
        if time.monotonic() - start > timeout_s:
            killed = "timeout"
        elif memory_mb is not None and ticks % 5 == 0 and _group_rss_mb(pgid) > memory_mb:
            killed = "memory"  # polled every ~0.25 s: `ps` is too slow to call every tick
        if killed:
            if on_kill:
                on_kill()
            kill_group(pgid)
            break
        try:
            proc.wait(timeout=0.05)  # returns as soon as the child exits; a sleep would add 50 ms to every command
        except subprocess.TimeoutExpired:
            pass
    proc.wait()
    # The leader exited, but `cmd &` children may still hold the pipes open.
    # Kill the rest of the group so nothing outlives the tool call.
    kill_group(pgid, grace_s=0.1)
    for t in readers:
        t.join(timeout=2)
    return ExecResult(command=label or " ".join(argv),
                      exit_code=None if killed else proc.returncode,
                      stdout=out.text(), stderr=err.text(),
                      duration_s=time.monotonic() - start,
                      timed_out=killed == "timeout", killed_reason=killed,
                      stdout_bytes=out.total, stderr_bytes=err.total)
Listing 11The process core, shared by both sandboxes. The highlighted lines start the group, watch the clock and clean up what is left.

Read the highlighted lines in order. start_new_session=True makes the child the leader of a new group, so its pid is also the group id. The loop checks the clock on each tick and checks memory on every fifth tick, because calling ps is slow. After the leader exits, a final kill_group removes anything it left behind. That line is what fixes the second bug.

Figure 3One command with a 1 second timeout, from Popen to the returned result. The timeout and the grace period are to scale. The earlier frames are placed for reading and were not measured.

Output needs the same care. If a command prints for a long time, we cannot hold it all in memory. _Capture keeps the first and last half of its budget and counts what it dropped.

class _Capture:
    """Keep the first and last `cap/2` bytes of a stream. Constant memory for any output size."""

    def __init__(self, cap: int):
        self.half = cap // 2
        self.head = bytearray()
        self.tail: deque[bytes] = deque()
        self.tail_len = 0
        self.total = 0

    def feed(self, chunk: bytes) -> None:
        self.total += len(chunk)
        room = self.half - len(self.head)
        if room > 0:
            self.head += chunk[:room]
            chunk = chunk[room:]
        if chunk:
            self.tail.append(chunk)
            self.tail_len += len(chunk)
            while self.tail_len - len(self.tail[0]) >= self.half:
                self.tail_len -= len(self.tail.popleft())

    def text(self) -> str:
        tail = b"".join(self.tail)
        dropped = self.total - len(self.head) - len(tail)
        mid = f"\n... [{dropped} bytes not captured] ...\n".encode() if dropped > 0 else b""
        return (bytes(self.head) + mid + tail).decode("utf-8", errors="replace")
Listing 12Constant memory for any amount of output. The total is always correct, even when the bytes are gone.

Capture has a cost that step 16 comes back to: past 1 MB, the middle of the output is gone. The tool itself is short. It turns a result into text for the model.

@tool(risk=lambda args: classify_command(args.get("command", "")))
def run_command(ctx: ToolContext, command: str, timeout: int = 60, cwd: str = ".") -> ToolOutput:
    """Run a shell command in the workspace sandbox and return exit code, stdout and stderr.

    Args:
        command: The shell command line, for example "python -m pytest -x -q".
        timeout: Seconds before the whole process group is killed.
        cwd: Working directory relative to the workspace root.
    """
    if ctx.sandbox is None:
        raise ToolError("no sandbox configured for shell commands")
    try:
        res = ctx.sandbox.run(command, timeout=timeout, cwd=cwd)
    except ValueError as e:  # cwd escaping the workspace
        raise ToolError(str(e)) from None
    return ToolOutput(format_exec(res, ctx.workspace), is_error=not res.ok,
                      data={"exit_code": res.exit_code, "timed_out": res.timed_out,
                            "duration_s": round(res.duration_s, 3)})
Listing 13The shell tool. The risk is a function of the arguments, because ls and rm -rf / are the same tool. Step 9 uses that.

Try it. This is what the model sees.

$ cd c10-agent-harness
$ ../.venv/bin/python - <<'EOF'
import tempfile
from pathlib import Path
from harness.sandbox import LocalSandbox
from harness.shell import run_command
from harness.tools import ToolContext

with tempfile.TemporaryDirectory() as tmp:
    ctx = ToolContext(workspace=Path(tmp), sandbox=LocalSandbox(Path(tmp)))
    print(run_command(ctx, "echo out; echo err >&2; exit 3").content)
    print(run_command(ctx, "sleep 30", timeout=1).content)
EOF
$ cd ..
exit code: 3
--- stdout ---
out
--- stderr ---
err
[0.01s, 4 B stdout, 4 B stderr]
TIMED OUT after 1.7s; the process group was killed.
exit code: None
[1.69s, 0 B stdout, 0 B stderr]

Checkpoint

  • test_timeout_kills_the_whole_process_group checks that the background child is really gone.
  • test_background_orphans_do_not_hang_the_call returns in under 5 seconds.
  • test_capture_is_bounded_and_counts_everything passes.
Step 06

Compare edit formats and build the applier

Goal Measure what each edit format does when the model makes a mistake, then build an applier that fails loudly.

There are four common ways for a model to express an edit. It can rewrite the whole file. It can quote a block and give its replacement. It can write a unified diff with exact line numbers, or a unified diff where the numbers are only hints.

Why editing is a protocol inInside an AI agent harness

Search and replace is the simplest of the careful formats. The applier tries an exact match, then ignores trailing spaces, then ignores indentation.

def apply_search_replace(text: str, search: str, replace: str, replace_all: bool = False) -> Applied:
    """Replace the unique occurrence of `search` with `replace`."""
    lines = text.splitlines()
    old, new = search.splitlines(), replace.splitlines()
    if not old:
        raise EditError("search text is empty; quote the lines you want to replace")
    for level in range(3):
        hits = find_block(lines, old, level)
        if not hits:
            continue
        if len(hits) > 1 and not replace_all:
            where = ", ".join(str(h + 1) for h in hits)
            raise EditError(f"search text matches {len(hits)} places (lines {where}); "
                            "add surrounding lines to make it unique, or set replace_all")
        for i in reversed(hits):  # back to front so earlier indices stay valid
            block = new if level < 2 else reindent(new, old, lines[i:i + len(old)])
            lines = _splice(lines, i, len(old), block)
        return Applied(_join(lines, text.endswith("\n")), LEVEL_NAMES[level], len(hits))
    raise EditError("search text not found in file.\n" + closest_region(lines, old))
Listing 14The search/replace applier. Three levels of match, a refusal if the quote is not unique, and a useful error if nothing matches.

The last line is the most useful one in this file. When the quote is not found, the error shows the region of the file that is closest. The model does not have to guess what it got wrong.

Diffs go through a parser and then apply_hunks. In strict mode the old lines must sit exactly where the header says. In anchored mode the number is only a hint: we search for the old lines and take the match nearest the hint.

def apply_hunks(text: str, hunks: list[Hunk], strict: bool = False) -> Applied:
    """Apply hunks in order. strict=True: old lines must sit exactly at old_start (no fuzz).

    Anchored mode treats old_start as a hint: it searches for the hunk's old lines
    (exact, then whitespace-tolerant) and takes the occurrence nearest the hint.
    """
    lines = text.splitlines()
    offset = 0          # how far earlier hunks moved later line numbers
    used: list[str] = []
    for k, h in enumerate(hunks, 1):
        hint = h.old_start - 1 + offset
        if not h.old:   # pure insertion: only the line number can place it
            at = max(0, min(h.old_start + offset, len(lines)))
            lines = _splice(lines, at, 0, h.new)
            offset += len(h.new)
            continue
        if strict:
            if lines[hint:hint + len(h.old)] != h.old:
                raise EditError(f"hunk {k} does not match at line {h.old_start} (strict mode).\n"
                                + closest_region(lines, h.old))
            at, level = hint, 0
        else:
            at = level = None
            for lvl in range(3):
                hits = find_block(lines, h.old, lvl)
                if hits:
                    at, level = min(hits, key=lambda s: abs(s - hint)), lvl
                    break
            if at is None:
                raise EditError(f"hunk {k} context not found in file.\n" + closest_region(lines, h.old))
        block = h.new if level < 2 else reindent(h.new, h.old, lines[at:at + len(h.old)])
        lines = _splice(lines, at, len(h.old), block)
        offset += len(h.new) - len(h.old) + (at - hint)
        used.append(LEVEL_NAMES[level] if at == hint else f"{LEVEL_NAMES[level]}, moved {at - hint:+d} lines")
    strategy = "; ".join(dict.fromkeys(used)) or "insert"
    return Applied(_join(lines, text.endswith("\n") or not text), strategy, len(hunks))
Listing 15The diff applier. offset tracks how far earlier hunks moved later line numbers.

What each format does under a slip

Now the measurement. The benchmark takes real lines of real Python and asks for a one-line edit, 200 times per cell. It writes the edit in each format, applies one kind of slip, and sorts the outcome into three groups. Correct means the file is right. Refused means the applier raised a clear error, so the model can retry. Corrupted means the applier succeeded and the file is wrong, and nobody was told.

$ .venv/bin/python c10-agent-harness/benchmarks/bench_edit_formats.py --trials 200
200 trials per cell, one-line edits in 20 real Python files

slip                              whole file      search/replace         strict diff       anchored diff
                          ok/refused/CORRUPT  ok/refused/CORRUPT  ok/refused/CORRUPT  ok/refused/CORRUPT
clean                                200/0/0             200/0/0             200/0/0             200/0/0
stale line numbers                   0/0/200             200/0/0             0/200/0             200/0/0
shifted indentation                  200/0/0             200/0/0             0/200/0             200/0/0
flattened indentation                200/0/0            77/123/0            25/175/0            36/164/0
quote too short                      200/0/0             0/200/0             200/0/0             200/0/0
lazy rewrite                         0/0/200             200/0/0             200/0/0             200/0/0
misremembered line                   0/0/200             0/200/0             0/200/0             0/200/0
total                              800/0/600           877/523/0           625/775/0          1036/364/0

mean tokens per edit                    1667                  77                 118                 122

correctrefusedcorrupted

Figure 4Outcomes per edit format. Choose a slip to see what it does. Numbers are correct / refused / corrupted, from bench_edit_formats.py. The table above holds the same data.
Edit formats, along the aspects the benchmark measures
FormatTokens per editCorrect, of 1,400Refused, of 1,400Corrupted, of 1,400Stale line numbersNon-unique quote
Whole file1,6678000600OverwritesNot affected
Search/replace778775230Not affectedRefuses
Strict diff1186257750RefusesNot affected
Anchored diff1221,0363640Not affectedNot affected

Read it this way. Whole file never refuses, which sounds good and is not. It gives the model no signal when a slip happens. Search/replace is about 20 times cheaper, and every slip it could not handle became a refusal. Anchored diff gets the most edits right. We use search/replace as the default tool because it is the smallest, with apply_patch for changes that span several places.

def reindent(new: list[str], old_block: list[str], matched: list[str]) -> list[str]:
    """Shift all of `new` by the indentation difference between what the model quoted and the file."""
    src = next((_indent(x) for x in old_block if x.strip()), "")
    dst = next((_indent(x) for x in matched if x.strip()), "")
    if src == dst:
        return new
    out = []
    for line in new:
        if not line.strip():
            out.append("")  # a blank line keeps no stray whitespace
        elif line.startswith(src):
            out.append(dst + line[len(src):])
        else:  # shallower than the quote's first line: it moves by the same amount
            width = len(_indent(line)) + len(dst) - len(src)
            if width < 0:
                raise EditError(f"cannot shift this line left by {len(src) - len(dst)} columns: {line!r}")
            out.append(dst[:width] + line.lstrip())
    return out
Listing 17The fixed version. Every line moves by the same amount.

The benchmark also calls the appliers directly. In the real tools the file tracker from step 4 catches stale files first, so a model that rewrites a whole file from an old read gets a refusal. The lazy rewrite and the misremembered line get past it, because the file on disk has not changed.

Check against git

We compare the diff applier with an implementation we did not write. The same diff goes to our applier and to git apply, on the same file, 200 times. The output is from an AMD EPYC 7R13 CPU.

def git_apply(text: str, diff: str) -> str | None:
    """Apply `diff` to `text` with real git. Returns the new text, or None if git refuses."""
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / "f.py").write_text(text)
        subprocess.run(["git", "init", "-q"], cwd=root, check=True)
        res = subprocess.run(["git", "apply", "-"], cwd=root, input=diff, text=True, capture_output=True)
        return (root / "f.py").read_text() if res.returncode == 0 else None
Listing 18Applying with real git in a temporary repository.
$ .venv/bin/python c10-agent-harness/scripts/compare_trusted.py
200 one-line edits in 20 files, each diff applied by git and by our applier

case                  git ok  strict ok  anchored ok  anchored == git
clean                    200        200          200              200
stale line numbers       200          0          200              200

On clean input all three agree on all 200. The second row taught us something. Git accepts a diff whose line numbers are off by three, because it searches for an offset. So our anchored mode behaves like git apply here, and our strict mode is stricter than git. Anchored mode and git gave the same result on all 400 diffs.

The same script compares our schemas with transformers.utils.get_json_schema, on one sample function. The types, descriptions and required lists all match. Ours also writes defaults and additionalProperties: false. Theirs marks an optional argument as nullable, and adds a return type.

Checkpoint

  • test_flattened_structure_is_refused_not_guessed and test_apply_patch_is_atomic_across_files pass.
  • You can say which row of the table made you choose your default format.
Step 07

Add verification tools with one result shape

Goal Tests, lint, type check and build all answer the same question in the same format.

An agent that cannot check its work is guessing. We could tell the model to run pytest through the shell tool. Then it has to read pytest's output, and ruff's, and mypy's, each in its own dialect. All of them answer one question: what is broken, and where?

class CheckResult:
    check: str           # "tests" | "lint" | "typecheck" | "build"
    status: str          # "pass" | "fail" | "error" | "timeout" | "unavailable"
    passed: int = 0
    failed: int = 0
    errors: int = 0
    skipped: int = 0
    diagnostics: list[Diagnostic] = field(default_factory=list)
    details: str = ""    # trimmed raw output (tracebacks) for context
    duration_s: float = 0.0
    command: str = ""

    @property
    def ok(self) -> bool:
        return self.status == "pass"

    def render(self, max_diagnostics: int = 20) -> str:
        counts = ", ".join(f"{v} {k}" for k, v in
                           (("passed", self.passed), ("failed", self.failed),
                            ("errors", self.errors), ("skipped", self.skipped)) if v)
        lines = [f"{self.check}: {self.status.upper()}" + (f" ({counts})" if counts else "")
                 + f" in {self.duration_s:.2f}s"]
        for d in self.diagnostics[:max_diagnostics]:
            loc = f"{d.file}:{d.line}" if d.line else d.file
            lines.append(f"  {loc} [{d.code}] {d.message}")
        if len(self.diagnostics) > max_diagnostics:
            lines.append(f"  ... {len(self.diagnostics) - max_diagnostics} more")
        if self.details:
            lines.append(self.details)
        return "\n".join(lines)

    def to_output(self) -> ToolOutput:
        return ToolOutput(self.render(), is_error=not self.ok, kind="test", data=asdict(self))
Listing 19One result shape for every check. The top line of render is the same whatever ran.
The four verification tools
ToolRunsIf the tool is missing
run_testspytestStatus unavailable, so it is not mistaken for a test failure
run_linterruffA built-in check for syntax errors and unused imports
run_typecheckmypyStatus unavailable
buildpython -m compileallNot applicable

Real ruff and real mypy never ran for this tutorial, because neither is installed on the machine behind these numbers. Their parsers have tests on hand-written output only, so a real version may format things differently. The pytest path, the built-in lint check and build all ran for real.

The pytest parser reads the summary line for the counts and the short report for the failures. The exit code decides the status, because the text alone cannot tell a failure from a crash.

def parse_pytest(res: ExecResult) -> CheckResult:
    out = res.stdout + "\n" + res.stderr
    r = CheckResult("tests", "pass", duration_s=res.duration_s, command=res.command)
    tail = "\n".join(out.strip().splitlines()[-3:])
    for n, kind in _SUMMARY_RE.findall(tail):
        n = int(n)
        if kind == "passed":
            r.passed = n
        elif kind == "failed":
            r.failed = n
        elif kind.startswith("error"):
            r.errors = n
        elif kind == "skipped":
            r.skipped = n
    # "tests/test_x.py:15: in test_name" lines inside each failure section
    locations = {name: (f, int(ln)) for f, ln, name in _LOCATION_RE.findall(out)}
    for line in out.splitlines():
        m = _SHORT_RE.match(line.strip())
        if m:
            kind, file, test, msg = m.groups()
            lineno = locations.get((test or "").split("[")[0], (file, None))[1]
            r.diagnostics.append(Diagnostic(file, lineno, test or kind.lower(), msg or kind))
    if res.timed_out:
        r.status = "timeout"
    elif res.exit_code == 0:
        r.status = "pass"
    elif res.exit_code == 1:
        r.status = "fail"
    elif res.exit_code == 5:
        r.status = "error"
        r.details = "no tests were collected"
    else:
        r.status = "error"
    if r.status != "pass":
        # Keep the "E   ..." assertion lines and locations; drop the passing noise.
        r.details = r.details or truncate_output(_failure_section(out), max_lines=60).text
    return r
Listing 20Normalising pytest. Exit code 1 is a failed test. Exit code 5 means no tests were collected, and that is a different problem.

Run it on a copy of the toy repo. This is the text the model gets.

$ cd c10-agent-harness
$ ../.venv/bin/python - <<'EOF'
import shutil, tempfile
from pathlib import Path
from harness.sandbox import LocalSandbox
from harness.tools import ToolContext
from harness.verify import run_tests

with tempfile.TemporaryDirectory() as tmp:
    ws = Path(tmp) / "repo"
    shutil.copytree("examples/toy_repo", ws)
    print(run_tests(ToolContext(workspace=ws, sandbox=LocalSandbox(ws))).content)
EOF
$ cd ..
tests: FAIL (4 passed, 2 failed) in 1.32s
  tests/test_stats.py:15 [test_median_even] assert 3 == 2.5
  tests/test_stats.py:28 [test_summarize] assert 3 == 2.5
=================================== FAILURES ===================================
_______________________________ test_median_even _______________________________
tests/test_stats.py:15: in test_median_even
    assert median([4, 1, 3, 2]) == 2.5
E   assert 3 == 2.5
E    +  where 3 = median([4, 1, 3, 2])
________________________________ test_summarize ________________________________
tests/test_stats.py:28: in test_summarize
    assert summarize([1, 2, 3, 4])["median"] == 2.5
E   assert 3 == 2.5

Checkpoint

  • test_run_tests_failure_is_normalised finds lines 15 and 28 in the toy repo.
  • test_parse_pytest_counts_and_statuses covers pass, no tests collected and timeout.
Step 08

Run commands in a sandbox

Goal Two backends behind one interface, with workspace mount, limits, network policy, timeout and cleanup.

The model chooses the commands, so they must not run with our full rights. Both backends implement one method: run(command, timeout, cwd) returns an ExecResult. Both use run_process from step 5. The limits live in one small dataclass.

class Limits:
    timeout_s: float = 60.0
    cpu_s: int | None = 120           # RLIMIT_CPU: kernel sends SIGXCPU
    memory_mb: int | None = 2048      # watchdog everywhere, RLIMIT_AS on Linux too
    file_size_mb: int | None = 256    # RLIMIT_FSIZE: a runaway log cannot fill the disk
    open_files: int | None = 1024
    network: bool = False             # False = deny where the OS lets us
    capture_bytes: int = 1_000_000    # per stream, head + tail kept
Listing 21One set of limits. The backends enforce them in different ways.

The local backend

LocalSandbox is a guard rail for laptops and CI. It clears the environment so API keys do not reach commands the model writes, sets resource limits, and removes network access where the operating system allows it.

    def env(self) -> dict[str, str]:
        env = {k: os.environ[k] for k in _SAFE_ENV_KEYS if k in os.environ}
        # No API keys, no tokens, no user config leak into commands the model writes.
        env.update(HOME=str(self.workspace), PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1")
        if not self.limits.network:
            env.update(HTTP_PROXY="http://127.0.0.1:9", HTTPS_PROXY="http://127.0.0.1:9", NO_PROXY="")
        env.update(self.extra_env)
        return env
Listing 22A scrubbed environment. Only a short list of variables survives, and HOME points into the workspace.
def network_wrapper() -> list[str] | None:
    """argv prefix that denies network for the child, or None if this OS offers none."""
    if sys.platform == "darwin" and Path("/usr/bin/sandbox-exec").exists():
        return ["/usr/bin/sandbox-exec", "-p", _DENY_NETWORK_PROFILE]
    if sys.platform.startswith("linux") and shutil.which("unshare"):
        return ["unshare", "--net", "--map-root-user"]
    return None
Listing 23Network denial. On Linux this is a new empty network namespace, and on macOS it is a sandbox-exec profile.

A test tries to open a connection through the sandbox. On our Linux machine, using unshare, it passes because the connection is refused.

$ .venv/bin/python -m pytest c10-agent-harness/tests/test_fs_shell_sandbox.py -k network_is_denied
1 passed, 25 deselected in 0.25s

The Docker backend

DockerSandbox runs each command in a fresh container. The workspace is bind-mounted at /workspace, and nothing else from the host is visible.

    def docker_argv(self, command: str, cwd: str = ".", name: str | None = None) -> list[str]:
        lim = self.limits
        root = Path(self.workspace).resolve()
        workdir = PurePosixPath("/workspace") / self.resolve_cwd(cwd).relative_to(root)
        argv = ["docker", "run", "--rm", "-i",
                "--name", name or f"{self.name_prefix}{uuid.uuid4().hex[:8]}",
                "--user", f"{os.getuid()}:{os.getgid()}",
                "--network", "bridge" if lim.network else "none",
                "--cpus", str(self.cpus), "--pids-limit", str(self.pids_limit),
                "--security-opt", "no-new-privileges", "--cap-drop", "ALL",
                "-v", f"{root}:/workspace:rw",
                "-w", str(workdir),
                "-e", "HOME=/workspace", "-e", "PYTHONDONTWRITEBYTECODE=1", "-e", "PYTHONUNBUFFERED=1"]
        for key, value in self.extra_env.items():
            argv += ["-e", f"{key}={value}"]
        if lim.memory_mb:
            argv += ["--memory", f"{lim.memory_mb}m", "--memory-swap", f"{lim.memory_mb}m"]
        if lim.file_size_mb:
            argv += ["--ulimit", f"fsize={lim.file_size_mb * 2**20}"]
        if lim.open_files:
            argv += ["--ulimit", f"nofile={lim.open_files}"]
        if lim.cpu_s:
            # A hard limit above the soft one makes a CPU kill exit 152 (SIGXCPU), not
            # 137 (SIGKILL), so `run` can read 137 as the memory limit.
            argv += ["--ulimit", f"cpu={lim.cpu_s}:{lim.cpu_s + 5}"]
        return argv + [self.image, "sh", "-c", command]
Listing 24The container command line. Each flag is one limit. The highlighted lines are the throwaway name, the host user, the network policy and the workspace mount.

The CPU limit sets a soft and a hard value on purpose. That makes a CPU kill exit with 152, so it is not mistaken for the memory kill, which exits with 137.

We ran this backend for real, on an AMD EPYC 7R13 with Docker 29.1.4 and image python:3.12-slim. The demo starts a fresh throwaway container for each row, checks one limit from inside it, then lets the agent fix the toy repo with every test run in a container.

$ docker pull python:3.12-slim
$ .venv/bin/python c10-agent-harness/scripts/demo_docker_sandbox.py
--- limits, each row one fresh container ---
read a mode-700 workspace              expected: hello
                                       got:      hello [exit 0, 0.34s]
write as the host user                 expected: b.txt owned by this uid
                                       got:      container uid (host uid), b.txt uid (host uid) [exit 0, 0.40s]
network none                           expected: blocked
                                       got:      blocked: [Errno 101] Network is unreachable [exit 0, 0.49s]
cgroup memory.max                      expected: 134217728
                                       got:      134217728 [exit 0, 0.40s]
cgroup cpu.max                         expected: 50000 100000
                                       got:      50000 100000 [exit 0, 0.44s]
cgroup pids.max                        expected: 16
                                       got:      16 [exit 0, 0.38s]
fork past --pids-limit                 expected: blocked
                                       got:      blocked after 14 forks: Resource temporarily unavailable [exit 0, 0.79s]
allocate 512 MB under a 128 MB limit   expected: killed_reason=memory
                                       got:      killed_reason=memory [exit 137, 0.59s]
busy loop under --ulimit cpu=1         expected: exit 152 (SIGXCPU)
                                       got:      killed_reason=None [exit 152, 2.61s]
write 5 MB under --ulimit fsize=1 MB   expected: at most 1048576 bytes
                                       got:      1048576 bytes [exit 1, 0.44s]
sleep 30 with a 2 s timeout            expected: timed out, container removed
                                       got:      timed_out=True [exit None, 2.71s]
background child outlives the command  expected: returns at once
                                       got:      done [exit 0, 0.44s]
5 MB of output                         expected: captured in bounded memory
                                       got:      1002630 chars kept of 5000000 bytes [exit 0, 0.46s]

container start to exit, `true`, median of 10: 412 ms

--- agent fixing the toy repo, every run_tests in a container ---
tests: FAIL (4 passed, 2 failed) in 1.37s
tests: PASS (6 passed) in 1.27s

hardware: AMD EPYC 7R13, 8 threads; image python:3.12-slim
The two sandbox backends, for the five things the sandbox must do
AspectLocalSandboxDockerSandbox
WorkspaceRuns in place, or in a temp copy with from_copy. Other paths stay reachable.Bind mount at /workspace. Nothing else is visible.
CPU and memoryRLIMIT_CPU, RLIMIT_AS on Linux, and a ps watchdog--cpus, --memory and cgroups, confirmed from inside the container
Networkunshare --net or sandbox-exec where present, and dead proxy variables--network none
TimeoutKill the process groupKill the CLI, and remove the container by name
CleanupKill the group after every command--rm, plus the kill hook on timeout
Cost of running true13.2 ms with the network denied, 5.7 ms without412 ms in the demo, 506.5 ms in the benchmark
NeedsNothingA Docker daemon and an image that has your test tools

All of these are medians on an AMD EPYC 7R13 CPU, from docker_sandbox.txt and bench_overheads.txt. A test suite that takes seconds will barely notice 400 ms. An agent that runs many short grep commands will.

Checkpoint

  • test_env_is_scrubbed, test_network_is_denied_by_default and test_cpu_limit_kills_a_busy_loop pass with no Docker at all.
  • With Docker and the image present, 19 tests run inside real containers: 18 in test_docker_sandbox.py and 1 in test_fs_shell_sandbox.py. Without them, those 19 skip and say why.
Step 09

Add the permission layer

Goal Classify every action by how much damage it can do, and ask a person only when it matters.

A sandbox limits what a command can reach. Permissions decide whether it runs at all. There are four levels, ordered by how bad a wrong call can be.

class Risk(IntEnum):
    READ = 0
    WORKSPACE_WRITE = 1
    EXTERNAL = 2
    DANGEROUS = 3
Listing 25Four levels. IntEnum lets us compare them with <=.

Most tools have a fixed risk. read_file is READ and edit_file is WORKSPACE_WRITE. The shell tool has a risk that depends on the command, so a classifier reads the string.

def classify_command(command: str) -> Risk:
    """Risk of a shell command string. Unknown programs default to WORKSPACE_WRITE."""
    for pattern in _DANGEROUS:
        if re.search(pattern, command):
            return Risk.DANGEROUS
    for pattern in _EXTERNAL:
        if re.search(pattern, command):
            return Risk.EXTERNAL
    # Redirection or chaining can turn a read into a write, so only simple commands
    # made entirely of read-only programs count as READ.
    if re.search(r"[>;&`]|\$\(", command):
        return Risk.WORKSPACE_WRITE
    try:
        parts = [shlex.split(seg) for seg in command.split("|")]
    except ValueError:
        return Risk.WORKSPACE_WRITE
    for words in parts:
        if not words:
            return Risk.WORKSPACE_WRITE
        prog = words[0]
        if prog == "git" and len(words) > 1 and words[1] in _READ_ONLY_GIT:
            continue
        if prog == "find" and any(w in ("-delete", "-exec") for w in words):
            return Risk.WORKSPACE_WRITE
        if prog not in _READ_ONLY_PROGRAMS:
            return Risk.WORKSPACE_WRITE
    return Risk.READ
Listing 26The classifier. It checks the worst patterns first. A command only counts as a read if every program in it is on a short list and there is no redirect or chain.

The default is the important part. An unknown program is WORKSPACE_WRITE, never READ. A false alarm costs one prompt, and a false read can cost a home directory.

class PermissionPolicy:
    """Auto-approve up to `auto_approve`; ask the approver above it.

    `deny_above` is a hard ceiling no approver can lift (e.g. CI runs that must
    never touch the network).
    """

    auto_approve: Risk = Risk.WORKSPACE_WRITE
    approver: Approver = deny_all
    deny_above: Risk = Risk.DANGEROUS

    def check(self, name: str, arguments: dict, risk: Risk) -> Decision:
        if risk > self.deny_above:
            return Decision(False, risk, f"{risk.name} actions are disabled by policy", asked=False)
        if risk <= self.auto_approve:
            return Decision(True, risk, f"auto-approved ({risk.name} <= {self.auto_approve.name})", asked=False)
        allowed = bool(self.approver(name, arguments, risk))
        reason = "approved by user" if allowed else "denied by user"
        return Decision(allowed, risk, reason, asked=True)
Listing 27The policy. Approve automatically up to a threshold, ask above it, and refuse above a ceiling that no approver can lift.
READ
WORKSPACE WRITE
EXTERNAL
DANGEROUS

Decision:

Figure 5Type any command. This is the classifier above, ported to JavaScript. We checked that it agrees with the Python version on 115 commands, including unclosed quotes and the ones in the nuance below. Change the policy to see how the decision moves.

In the loop, the check runs after validation and before execution. A denial becomes an observation, so the model can choose another way.

    def _run_tool(self, call: ToolCall, step: int) -> bool:
        """Validate, authorise, execute and record one call. Returns True on a protocol error."""
        self.log.append("ToolCall", step, id=call.id, name=call.name, arguments=call.arguments)
        errors = self.tools.validate(call)
        if errors:
            out = ToolOutput(format_call_errors(call, errors), is_error=True)
        else:
            risk = self.tools[call.name].risk_for(call.arguments)
            decision = self.policy.check(call.name, call.arguments, risk)
            if risk > Risk.READ or not decision.allowed:
                self.log.append("Approval", step, id=call.id, name=call.name, risk=risk.name,
                                allowed=decision.allowed, asked=decision.asked, reason=decision.reason)
            if not decision.allowed:
                out = ToolOutput(f"Permission denied for {call.name} ({risk.name}): {decision.reason}. "
                                 "Choose a different approach.", is_error=True)
            else:
                with self.tracer.span("tool", call.name, step) as span:
                    out = self.tools.execute(call, self.ctx)
                    span.ok = not out.is_error
Listing 28Validate, authorise, execute. Every decision above READ writes an Approval event, so the log records who allowed what.

Now try the real classifier on strings built to fool it.

$ cd c10-agent-harness
$ ../.venv/bin/python - <<'EOF'
from harness.permissions import classify_command

for command in ["""python -c "import shutil; shutil.rmtree('/')" """.strip(), "bash deploy.sh",
                "grep sudo notes.txt", "echo 'rm -rf /'"]:
    print(f"{classify_command(command).name:<16} {command}")
EOF
$ cd ..
WORKSPACE_WRITE  python -c "import shutil; shutil.rmtree('/')"
WORKSPACE_WRITE  bash deploy.sh
DANGEROUS        grep sudo notes.txt
DANGEROUS        echo 'rm -rf /'

Checkpoint

  • test_denied_call_never_executes_and_is_logged shows the tool never ran.
  • test_hard_ceiling_cannot_be_approved shows an approver cannot lift the ceiling.
Step 10

Build the context from named parts

Goal Assemble what the model sees each turn from sections, and count the tokens of each one.

In the minimal loop the context was one growing list. A real prompt has parts that change at different rates. The instructions never change. The repository state changes after an edit. The task never changes, but the plan and the step counter do. Only the history grows.

So the system message is rendered fresh each turn, and the history is kept apart from it.

class ContextBuilder:
    instructions: str = DEFAULT_INSTRUCTIONS
    sections: dict[str, Section] = field(default_factory=dict)   # e.g. {"repo": repo_section}

    def add_section(self, name: str, fn: Section) -> None:
        self.sections[name] = fn

    def build(self, state: AgentState, history: list[Message], tools: list[dict]) -> Context:
        parts: dict[str, str] = {"instructions": self.instructions}
        for name, fn in self.sections.items():
            text = fn(state)
            if text:
                parts[name] = text
        parts["task"] = task_section(state)  # last in the system message: closest to the history
        system = "\n\n".join(parts.values())
        history_dicts = [m.to_dict() for m in history]
        breakdown = {name: count_tokens(text) for name, text in parts.items()}
        breakdown["tools"] = count_tokens(dumps(tools))
        breakdown["history"] = count_message_tokens(history_dicts)
        return Context([{"role": "system", "content": system}] + history_dicts, tools, breakdown)
Listing 29The builder. Every section gets its own token count, so we can see where the window goes. Sections are plain callables, which is how the next tutorial adds memory without editing the loop.

Run it on the toy repo.

$ cd c10-agent-harness
$ ../.venv/bin/python - <<'EOF'
from pathlib import Path
from harness import AgentState, ContextBuilder, Message, coding_tools, repo_section

state = AgentState("Fix median.", Path("examples/toy_repo"))
ctx = ContextBuilder(sections={"repo": repo_section()}).build(state, [Message("user", "Fix median.")], coding_tools().schemas())
print(ctx.breakdown, "total", ctx.tokens)
print([m["role"] for m in ctx.messages], len(ctx.tools))
EOF
$ cd ..
{'instructions': 100, 'repo': 156, 'task': 18, 'tools': 3160, 'history': 7} total 3441
['system', 'user'] 20
What the model receives on each turn
PartTokens at step 1RenderedChanges when
instructions100Fixed textNever
repo156Repo map and git statusThe status changes after an edit
task18 to 57Task, plan, step numberThe plan changes
tools3,160JSON schemasNever in one run
history7 at firstAll messages so farEvery turn, and it grows

Token counts use a small estimator. It is a regular expression, and it needs no model download.

_PIECES = re.compile(r"\w+|[^\w\s]")


def count_tokens(text: str) -> int:
    """Estimated token count. Long words count as several tokens, as in BPE."""
    return sum(1 + len(p) // 8 for p in _PIECES.findall(text))
Listing 30The estimate. It is deterministic and fast, which is what a budget needs. The real tokenizer is in the table from step 2.

toolshistoryrepoinstructionstask

Figure 6Estimated context size on each step of the demo run from step 19. The note under the chart gives each section's size. Every number comes from the context field of a logged ModelResponse event.

Checkpoint

  • test_context_builder_sections_and_breakdown adds a memory section and sees it in the breakdown.
  • The total equals the sum of the sections.
Step 11

Add repository search

Goal Find text, find files and find definitions, without reading the whole repository.

The model cannot read every file. Search lets it pull in only what it needs. We write the reference first, in pure Python, because it has no dependencies and is easy to trust.

def search_python(root: Path, pattern: str, glob: str | None = None) -> list[Match]:
    """The reference implementation: slow, dependency-free, obviously correct."""
    try:
        rx = re.compile(pattern)
    except re.error as e:
        raise ToolError(f"invalid regex {pattern!r}: {e}") from None
    out = []
    for p in iter_files(root, glob):
        try:
            text = p.read_text()
        except (UnicodeDecodeError, OSError):
            continue  # binary file
        for i, line in enumerate(text.splitlines(), 1):
            if rx.search(line):
                out.append(Match(str(p.relative_to(root)), i, line))
    return out
Listing 31The reference search. It is slow and obvious, and the faster backends must agree with it.

Then we pick the fastest backend that exists on the machine.

def pick_backend(root: Path) -> str:
    if shutil.which("rg"):
        return "ripgrep"
    if shutil.which("git") and (root / ".git").exists():
        return "git-grep"
    return "python"


BACKENDS = {"ripgrep": search_ripgrep, "git-grep": search_gitgrep, "python": search_python}
Listing 32Backend choice: ripgrep if it is installed, then git grep inside a repo, then pure Python.

Text search answers where a string appears. A model usually wants to know where a function is defined and who uses it. Python's ast module gives us that for free.

def index_file(path: Path, root: Path) -> FileSymbols:
    rel = str(path.relative_to(root))
    fs = FileSymbols(rel)
    try:
        tree = ast.parse(path.read_text(errors="replace"))
    except SyntaxError:
        return fs
Listing 33The symbol index for one file: top-level functions, classes and methods, with signatures, plus every name the file uses.

find_files is the third tool. It matches paths with a glob, for when the model knows a file's shape and not its contents. Here are all three on the toy repo.

$ cd c10-agent-harness
$ ../.venv/bin/python - <<'EOF'
from pathlib import Path
from harness.search import find_files, find_symbol, search
from harness.tools import ToolContext

ctx = ToolContext(workspace=Path("examples/toy_repo"))
print(search(ctx, "def median"))
print(find_files(ctx, "tests/test_*"))
print(find_symbol(ctx, "median"))
EOF
$ cd ..
stats_lib/core.py:10: def median(xs: list[float]) -> float:
tests/test_stats.py
stats_lib/core.py:10: def median(xs: list[float]) -> float
used in: stats_lib/report.py, tests/test_stats.py

The numbers below come from running over this repository's own Python code.

$ .venv/bin/python c10-agent-harness/benchmarks/bench_overheads.py
Search over 506 Python files and 40,868 lines, AMD EPYC 7R13 CPU. Output of bench_overheads.py.
OperationTime (ms)Found
git grep72.162 matches
Pure Python91.562 matches
Symbol index build666.52,707 symbols
Definition lookup0.3858 definitions

Two gaps, stated plainly. The ripgrep backend is written, but ripgrep is not installed on the machine that ran these numbers, and no test covers that path. The plan lists embedding search as optional, and we did not build it. Exercise 1 asks you to add it and to find out whether it helps.

Checkpoint

  • test_search_backends_agree compares git grep with the reference.
  • test_symbol_index_definitions_and_references finds median on line 10 of core.py.
Step 12

Build a repository map

Goal Show the shape of the whole codebase in a few hundred tokens.

Search needs the model to know what to look for. A map tells it what exists. We use the symbol index to render each file as an outline, rank the files, and stop when the budget is spent.

def rank_files(idx: SymbolIndex, focus: str = "") -> list[tuple[str, float]]:
    """Score = cross-file references to this file's symbols + 5 per symbol named in `focus`."""
    words = set(re.findall(r"\w+", focus.lower()))
    scores: dict[str, float] = {}
    for path, fs in idx.files.items():
        defined = {s.name.split(".")[-1] for s in fs.symbols}
        refs = sum(len(defined & other.names_used) for p, other in idx.files.items() if p != path)
        stem_hits = sum(w in words for w in re.findall(r"\w+", Path(path).stem.lower()))
        named = sum(n.lower() in words for n in defined)
        scores[path] = refs + 5 * (named + stem_hits)
    return sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))
Listing 34The ranking: how often other files use this file's names, plus a boost for names the task mentions. It is a one-step version of the PageRank ranking in Aider.
def build_repo_map(root: Path, max_tokens: int = 1024, focus: str = "") -> str:
    """Render ranked file outlines until the token budget is spent."""
    idx = SymbolIndex(root)
    blocks, used, skipped = [], 0, 0
    for path, _ in rank_files(idx, focus):
        block = render_file(idx.files[path])
        cost = count_tokens(block)
        if used + cost > max_tokens:
            skipped += 1
            continue
        blocks.append(block)
        used += cost
    if skipped:
        blocks.append(f"[{skipped} more files not shown; use find_files or search]")
    return "\n".join(blocks)
Listing 35Render until the budget is gone. The last line tells the model that more exists.
$ cd c10-agent-harness
$ ../.venv/bin/python -c "from pathlib import Path; from harness.repomap import build_repo_map; print(build_repo_map(Path('examples/toy_repo')))"
$ cd ..
stats_lib/core.py
 ├ def mean(xs: list[float]) -> float
 ├ def median(xs: list[float]) -> float
 └ def variance(xs: list[float]) -> float
stats_lib/report.py
 ├ import .core
 └ def summarize(xs: list[float]) -> dict[str, float]
conftest.py
stats_lib/__init__.py
 └ import .core, .report
tests/test_stats.py
 ├ import pytest, stats_lib
 ├ def test_mean()
 ├ def test_median_odd()
 ├ def test_median_even()
 ├ def test_variance()
 ├ def test_empty()
 └ def test_summarize()

On a larger codebase the budget is what makes this useful. This is the map of this repository's Python code, from the same benchmark.

Repo map size against budget, in estimated tokens, 506 Python files
What the model getsTokens
All the source code507,771
Unbudgeted map, every signature62,579
Map at budget 81928,202
File names only6,002
Map at budget 20482,059
Map at budget 512518

Checkpoint

  • test_repo_map_respects_budget_and_says_what_it_dropped passes at a budget of 45 tokens.
  • test_repo_map_focus_boosts_named_files shows the task changing the order.
Step 13

Keep a plan outside the history

Goal A checklist the model maintains, and the harness shows on every turn.

Long tasks lose their thread. A plan helps only if the model keeps seeing it. If the plan sat in the chat history, it would scroll away and later get compacted. So it lives in the agent's state, and the context builder renders it into the system message each turn.

class Plan:
    steps: list[PlanStep] = field(default_factory=list)

    def render(self) -> str:
        return "\n".join(f"{SYMBOL[s.status]} {s.title}" for s in self.steps) or "(no plan yet)"

    @property
    def current(self) -> PlanStep | None:
        return next((s for s in self.steps if s.status == "in_progress"), None)

    def set_from_lines(self, lines: list[str]) -> None:
        steps = []
        for raw in lines:
            m = re.match(r"^\s*(\[[ >x\-]\])\s*(.+)$", raw)
            if not m:
                raise ToolError(f"plan item {raw!r} must start with [ ], [>], [x] or [-]")
            steps.append(PlanStep(m.group(2).strip(), MARKS[m.group(1)]))
        if sum(s.status == "in_progress" for s in steps) > 1:
            raise ToolError("at most one plan item can be in progress ([>])")
        self.steps = steps
Listing 36The plan. It allows one item in progress at a time, which stops a model from marking everything as active.
$ cd c10-agent-harness
$ ../.venv/bin/python - <<'EOF'
from harness.planning import Plan
from harness.tools import ToolError

plan = Plan()
print(plan.render())
plan.set_from_lines(["[x] reproduce", "[>] fix median", "[ ] run the tests"])
print(plan.render())
print("current:", plan.current.title)
try:
    plan.set_from_lines(["[>] one", "[>] two"])
except ToolError as e:
    print("error:", e)
EOF
$ cd ..
(no plan yet)
[x] reproduce
[>] fix median
[ ] run the tests
current: fix median
error: at most one plan item can be in progress ([>])

The tool that changes it is one line of real work: update_plan replaces the whole list. Replacing is simpler than editing items by index, and it makes a model restate where it is.

Checkpoint

  • test_plan_tool_round_trip passes, including both refusals.
  • test_compaction_triggers_preserves_task_and_replays shows the task surviving compaction. We build that in step 15.
Step 14

Write every action to an event log

Goal An append-only JSONL file from which the whole chat history can be rebuilt.

When a run goes wrong, you need to know what happened, in order. So every action becomes one JSON line, written at once. A crash loses at most one line.

class EventLog:
    """Append-only JSONL log. `path=None` keeps it in memory (tests, notebooks)."""

    def __init__(self, path: str | Path | None = None):
        self.path = Path(path) if path else None
        self.events: list[Event] = []
        self.subscribers: list[Callable[[Event], None]] = []
        self._t0 = time.monotonic()
        if self.path:
            self.path.parent.mkdir(parents=True, exist_ok=True)
            self.path.write_text("")  # a fresh run starts a fresh file

    def append(self, type: str, step: int, **data: Any) -> Event:
        if type not in EVENT_TYPES:
            raise ValueError(f"unknown event type {type!r}")
        ev = Event(len(self.events), step, round(time.monotonic() - self._t0, 4), type, data)
        self.events.append(ev)
        if self.path:
            with self.path.open("a") as f:  # one write per event: a crash loses at most one line
                f.write(json.dumps(asdict(ev), ensure_ascii=False) + "\n")
        for fn in self.subscribers:
            fn(ev)
Listing 37The log. Each event is written as it happens, and subscribers see it too. Tracing and memory plug in here.
The event types
EventWritten when
UserMessageThe task arrives, or the harness sends feedback on a bad call
ModelResponseThe model replies. Holds calls, parse errors, usage and the context breakdown.
ToolCall, ToolResultA call starts, and a truncated result comes back
Patch, TestResultA tool changed a file, or a check finished. Structured, so nothing needs parsing later.
ApprovalA permission check above READ, or any denial
Compaction, CheckpointThe history was summarised, or the tree was saved
Error, FinalA model failure, or the end of the run

Here is one real line from the demo run. Each line is plain JSON, so ordinary tools such as grep and jq work on it.

{"seq": 7, "step": 2, "t": 0.079, "type": "Approval", "data": {"id": "call_0002", "name": "run_command", "risk": "EXTERNAL", "allowed": false, "asked": true, "reason": "denied by user"}}

The log is the source of truth. The chat history the model sees can be derived from it.

    def to_messages(self) -> list[Message]:
        """Rebuild the chat history from events, applying compactions in order."""
        history: list[tuple[int, Message]] = []
        for e in self.events:
            d = e.data
            if e.type == "UserMessage":
                history.append((e.seq, Message("user", d["content"])))
            elif e.type == "ModelResponse":
                calls = [ToolCall(c["name"], c["arguments"], id=c["id"]) for c in d.get("tool_calls", [])]
                history.append((e.seq, Message("assistant", d.get("text", ""), calls)))
            elif e.type == "ToolResult":
                history.append((e.seq, Message("tool", d["content"], tool_call_id=d["id"], name=d["name"])))
            elif e.type == "Compaction":
                # Cut by position: an earlier summary has a later seq than the messages it precedes.
                cut = next(i for i, (s, _) in enumerate(history) if s == d["kept_from_seq"])
                history = [(e.seq, Message("user", d["summary"]))] + history[cut:]
        return [m for _, m in history]
Listing 38Rebuilding the history from events. Each compaction is replayed in order, so the result matches what the model saw at the end of the run.
$ cd c10-agent-harness
$ ../.venv/bin/python -m harness.replay results/demo_events.jsonl
$ cd ..
[  0] step  0  UserMessage   task
      The test suite fails on median for even-length lists. Fix the bug and make all tests pass.
[  1] step  0  Checkpoint    {'sha': '837fa668f030af20792daaa129974b6b859e129a', 'label': 'start of run'}
[  2] step  1  ModelResponse "I'll write a plan before touching anything." -> update_plan  [context ~3477 tok]
[  3] step  1  ToolCall      update_plan(items=['[>] reproduce the failure', '[ ] fi...)
[  4] step  1  ToolResult    update_plan

Checkpoint

  • The replay prints a readable transcript of a past run.
  • A history rebuilt from the file equals the live history.
Step 15

Compact the context when it gets too large

Goal Keep the prompt inside a budget, and keep the facts that are expensive to rediscover.

Every model call sends the whole history again. A run of N steps sends about N squared tokens in total. The benchmark shows it in the table below: doubling from 80 to 160 steps with no budget multiplies total prompt tokens by 3.9.

When the history gets too large we summarise the older part. The rules, in order: task state survives because it is not in the history. Important failures from the dropped turns are kept word for word. Older turns become one line each. Recent turns stay whole, and a cut never separates a call from its result.

def extractive_summary(messages: list[Message], max_failure_lines: int = 24) -> str:
    """A deterministic summary: one line per tool call, plus verbatim failure heads."""
    results = {m.tool_call_id: m for m in messages if m.role == "tool"}
    lines: list[str] = []
    touched: list[str] = []
    failures: list[str] = []
    for m in messages:
        if m.role == "user" and m.content.startswith(SUMMARY_HEADER):
            old_lines, old_touched, old_failures = _split_summary(m.content)
            lines, touched, failures = lines + old_lines, touched + old_touched, failures + old_failures
        elif m.role == "user" and m.content:
            lines.append(f"- user: {m.content.splitlines()[0][:100]}")
        for c in m.tool_calls:
            r = results.get(c.id)
            head = r.content.strip().splitlines()[0][:100] if r and r.content.strip() else "(no result)"
            lines.append(f"- {c.name}({_short_args(c.arguments)}) -> {head}")
            if c.name in ("edit_file", "write_file", "apply_patch") and "path" in c.arguments:
                touched.append(c.arguments["path"])
            if r is not None and _is_failure(r.content):
                failures += r.content.strip().splitlines()[:6]
    out = [SUMMARY_HEADER] + lines
    if touched:
        out.append("Files edited so far: " + ", ".join(dict.fromkeys(touched)))
    if failures:
        # Most recent failures matter most, so a long list keeps its tail.
        out.append("Important failures (verbatim):")
        out += [f"  {line}" for line in failures[-max_failure_lines:]]
    return "\n".join(out)
Listing 39The summariser. It uses no model: one line per tool call, plus the first lines of each failure. Being deterministic means a test can check it.
    def _build_context(self, step: int) -> Context:
        messages = [m for _, m in self.history]
        context = self.builder.build(self.state, messages, self.tools.schemas())
        if context.tokens <= self.config.context_budget:
            return context
        # Compact down to a target well under the budget, not just under it; otherwise
        # every following turn crosses the line again and pays for another compaction.
        target = int(self.config.context_budget * self.config.compact_to)
        plan = after = None
        for keep in range(self.config.keep_recent_turns, 0, -1):
            plan = plan_compaction(messages, keep, self.summarizer)
            if plan is None:
                continue
            summary_msg = Message("user", plan.summary)
            after = self.builder.build(self.state, [summary_msg] + messages[plan.cut:], self.tools.schemas())
            if after.tokens <= target:
                break
        if plan is None or after is None:
            return context  # nothing old enough to drop; the model sees an over-budget context
        kept_from = self.history[plan.cut][0]
        ev = self.log.append("Compaction", step, summary=plan.summary, kept_from_seq=kept_from,
                             dropped_messages=plan.dropped, tokens_before=context.tokens,
                             tokens_after=after.tokens)
        self.history = [(ev.seq, summary_msg)] + self.history[plan.cut:]
        return after
Listing 40Where it runs in the loop. The target is below the budget on purpose: compacting only just under the line would fire again on the next turn.

This is the real summary from the demo run. It replaced 16 messages, and the context went from 4,609 to 4,087 estimated tokens.

[Summary of earlier turns, compacted by the harness]
- user: The test suite fails on median for even-length lists. Fix the bug and make all tests pass.
- update_plan(items=['[>] reproduce the failure', '[ ] find the median ...) -> plan updated:
- run_command(command='pip install pytest') -> Permission denied for run_command (EXTERNAL): denied by user. Choose a different approach.
- run_tests() -> tests: FAIL (4 passed, 2 failed) in 1.23s
- user: Your tool call could not be parsed:
- search(pattern='def median') -> stats_lib/core.py:10: def median(xs: list[float]) -> float:
- read_file(path='stats_lib/core.py') -> 1 | """Small descriptive statistics, written the way real code drifts: mostly right."""
- read_file(path='tests/test_stats.py', start=14, end=16) -> 14 | def test_median_even():
- update_plan(items=['[x] reproduce the failure', '[x] find the median ...) -> plan updated:
Important failures (verbatim):
  Permission denied for run_command (EXTERNAL): denied by user. Choose a different approach.
  tests: FAIL (4 passed, 2 failed) in 1.23s
    tests/test_stats.py:15 [test_median_even] assert 3 == 2.5
    tests/test_stats.py:28 [test_summarize] assert 3 == 2.5
  =================================== FAILURES ===================================
  _______________________________ test_median_even _______________________________
  tests/test_stats.py:15: in test_median_even

Now measure it. The benchmark runs a scripted session of N tool calls, each returning the same file-sized text.

$ .venv/bin/python c10-agent-harness/benchmarks/bench_compaction.py
 steps    budget   peak prompt   cumulative  compactions   saved
    10      none          3731        21846            0      0%
    10      4000          3731        21846            0      0%
    10      2000          1986        14170            3     35%
    20      none          7221        78351            0      0%
    20      4000          3830        47834            2     39%
    20      2000          1986        29037            6     63%
    40      none         14201       296061            0      0%
    40      4000          3998       106443            5     64%
    40      2000          1988        60349           14     80%
    80      none         28161      1150281            0      0%
    80      4000          3998       230647           12     80%
    80      2000          1999       123219           31     89%
   160      none         56081      4533921            0      0%
   160      4000          3998       488127           31     89%
   160      2000          2513       288024          106     94%

per-step prompt sizes for the 80-step run saved to results/compaction_series.json

--- long runs: where the budget stops holding ---
 steps    budget   peak prompt  held   cumulative  compactions  last summary
   320      4000          4433    NO      1080826          128          3847
   640      4000          8273    NO      3115706          448          7687
   320      8000          7961   yes      1794749           24          3727
   640      8000          8273    NO      4088445          133          7687
budget 4000: cumulative tokens grow 2.9x from 320 to 640 steps
budget 8000: cumulative tokens grow 2.3x from 320 to 640 steps
Total, no budget
Total, budget 4000
Total, budget 2000
Figure 7Prompt tokens per step in the real 80-step run, from results/compaction_series.json. Each drop is one compaction. Turn on the zoom to see the sawtooth. Hover or tap for values.

So the limit depends on the budget. In these runs the summary costs about 12 tokens per call, and the rest of the prompt about 590. A budget B therefore holds up to about (B − 590) / 12 steps: near 120 steps for 2,000, 280 for 4,000 and 620 for 8,000. That rough fit agrees with every row above. A budget of 2,000 holds at 80 steps and fails at 160, 4,000 holds at 160 and fails at 320, and 8,000 holds at 320 and fails at 640.

Past that point every turn compacts and the growth returns. From 320 to 640 steps the total grows 2.9 times at a budget of 4,000 and 2.3 times at 8,000. Those runs also compact 448 and 133 times.

All of this measures token counts only. It says nothing about whether a model would still solve the task after compaction this hard. That needs a real model and an evaluation.

Checkpoint

  • test_compaction_keeps_recent_turns_whole_and_pairs_intact checks that no result is cut off from its call.
  • test_second_compaction_extends_the_first shows summaries do not nest.
  • test_compaction_does_not_refire_every_step checks the target.
Step 16

Truncate giant outputs safely

Goal A 20,000 line log becomes about 90 lines and keeps its failing assertion, as long as the log fits in capture.

A test run can print 20,000 lines. Pasted into the context, that costs about 300,000 estimated tokens and hides the task. The usual fixes are to keep the start or keep the end. So we test them: one failing assertion at a random place in a synthetic log, 200 times.

$ .venv/bin/python c10-agent-harness/benchmarks/bench_truncation.py
20000 line log, 200 random failure positions, line budget 120

policy                    tokens shown  lines shown  assertion kept
no truncation                   299999        20000         100.0%
head only                         1808          121           0.5%
tail only                         1800          120           0.0%
head + tail                       1222           82           0.0%
head + tail + rescue              1292           87         100.0%

Every simple policy lost the assertion almost every time. So we add a third source of lines: anything in the middle that looks like an error, with one line of context on each side.

def truncate_output(text: str, max_lines: int = 120, max_line_chars: int = 400,
                    head: int = 30, tail: int = 50, max_rescued: int = 30,
                    spill_path: Path | None = None, spill_name: str | None = None) -> Truncated:
    """Head + tail + rescued error lines. `max_lines` bounds the shown line count.

    If `spill_path` is given, `text` is written there and the footer tells the model to
    read `spill_name` (the workspace-relative path) for the rest. If capture already lost
    bytes before `text` was made, the footer and the spill file both say how many.
    """
    lines = [ln if len(ln) <= max_line_chars else ln[:max_line_chars] + f" ...[{len(ln) - max_line_chars} chars]"
             for ln in text.splitlines()]
    n = len(lines)
    if n <= max_lines:
        return Truncated("\n".join(lines), n, n, 0, truncated=False)

    head, tail = min(head, max_lines // 3), min(tail, max_lines // 2)
    keep = set(range(head)) | set(range(n - tail, n))
    rescued = 0
    budget = min(max_rescued, max_lines - len(keep))
    for i in range(head, n - tail):
        if rescued >= budget:
            break
        if ERROR_PATTERNS.search(lines[i]):
            for j in (i - 1, i, i + 1):
                if head <= j < n - tail and j not in keep and rescued < budget:
                    keep.add(j)
                    rescued += 1

    out: list[str] = []
    prev = -1
    for i in sorted(keep):
        if i != prev + 1:
            out.append(f"... [{i - prev - 1} lines omitted] ...")
        out.append(lines[i])
        prev = i
    dropped = capture_dropped_bytes(text)
    lost = f"; {dropped} bytes were dropped from the middle during capture and are lost" if dropped else ""
    if spill_path is not None:
        spill_path.parent.mkdir(parents=True, exist_ok=True)
        spill_path.write_text(f"[incomplete: {dropped} bytes were dropped during capture]\n{text}" if dropped else text)
        count, saved = ("kept", "kept") if dropped else ("total", "full")
        name = spill_name or spill_path.name
        out.append(f"[output truncated: {n} lines {count}{lost}; {saved} text saved to {name}, "
                   f"read it with read_file if you need more]")
    else:
        out.append(f"[output truncated: showing {len(keep)} of {n} lines{lost}]")
    return Truncated("\n".join(out), n, len(keep), rescued, truncated=True)
Listing 41Head, tail and rescued lines. The footer says what was dropped, including bytes that capture lost before this function ran. It can also save the text to a file the model can read.
line 0line 20,000
Lines shown
Lines rescued
Assertion kept

          
Figure 8The policy running in your browser, on a 20,000 line log. This is a JavaScript port of truncate_output. The panel shows an excerpt of the kept lines. Kept spans on the strip are drawn wider than scale. It does not model the 1 MB capture limit described below.
$ cd c10-agent-harness
$ ../.venv/bin/python - <<'EOF'
from harness.truncation import truncate_output

lines = [f"tests/t.py::test_{i} PASSED" for i in range(20000)]
lines[15000] = "E       AssertionError: assert 3 == 2.5"
t = truncate_output("\n".join(lines))
print("one failure:     assertion kept", "assert 3 == 2.5" in t.text, "| rescued lines", t.rescued_lines)
for i in range(1000, 1200):
    lines[i] = f"tests/t.py::test_{i} FAILED"
t = truncate_output("\n".join(lines))
print("200 more before: assertion kept", "assert 3 == 2.5" in t.text, "| rescued lines", t.rescued_lines)
EOF
$ cd ..
one failure:     assertion kept True | rescued lines 3
200 more before: assertion kept False | rescued lines 30

Truncation happens twice. The shell tool truncates each stream as it formats the result. The loop then applies a limit to every observation, whatever tool produced it, because one forgotten tool should not be able to fill the context.

Checkpoint

  • test_truncation_keeps_head_tail_and_rescues_errors passes.
  • test_giant_output_stays_in_budget runs a 50,000 line command through the shell tool.
  • test_footer_and_spill_tell_the_truth_when_capture_dropped_bytes checks the footer and the saved file.
Step 17

Add git status, diff, log, revert and checkpoint

Goal Let the agent save and restore the working tree as often as it likes, without touching the user's branch.

Status, diff and log are thin wrappers around git. Checkpoints need more thought. The agent needs an undo button, and a commit on the user's branch is the wrong way to get one. It would move HEAD and show up in their history. So we write a commit object using a temporary index, and store it under a private ref.

def create_checkpoint(root: Path, label: str) -> str:
    """Snapshot the working tree (tracked + untracked, minus ignored). Returns the commit sha."""
    with tempfile.TemporaryDirectory() as tmp:
        env = {"GIT_INDEX_FILE": str(Path(tmp) / "index"),
               "GIT_AUTHOR_NAME": "harness", "GIT_AUTHOR_EMAIL": "harness@example.com",
               "GIT_COMMITTER_NAME": "harness", "GIT_COMMITTER_EMAIL": "harness@example.com"}
        git(root, "add", "-A", env=env)
        tree = git(root, "write-tree", env=env).strip()
    head = git(root, "rev-parse", "--verify", "-q", "HEAD", check=False).strip()
    parent = ["-p", head] if head else []
    sha = git(root, "commit-tree", tree, *parent, "-m", f"harness checkpoint: {label}", env=env).strip()
    n = len(list_checkpoints(root))
    git(root, "update-ref", f"{REF_PREFIX}{n:03d}", sha)
    return sha
Listing 42A checkpoint. GIT_INDEX_FILE points git at a throwaway index, so the user's staging area stays as it was. The ref keeps the commit from being garbage collected.
def restore_checkpoint(root: Path, sha: str) -> list[str]:
    """Make the working tree equal the checkpoint. Returns paths that were deleted."""
    git(root, "cat-file", "-e", f"{sha}^{{commit}}")
    in_checkpoint = set(git(root, "ls-tree", "-r", "--name-only", sha).splitlines())
    present = set(git(root, "ls-files", "--cached", "--others", "--exclude-standard").splitlines())
    removed = sorted(p for p in present - in_checkpoint if (Path(root) / p).exists())
    for p in removed:
        (Path(root) / p).unlink()
    git(root, "restore", f"--source={sha}", "--worktree", "--", ".")
    return removed
Listing 43Restoring. git restore brings back tracked content. It would leave new files behind, so we delete those first.
$ cd c10-agent-harness
$ ../.venv/bin/python - <<'EOF'
import tempfile
from pathlib import Path
from harness.git_tools import create_checkpoint, git, init_repo, list_checkpoints, restore_checkpoint

with tempfile.TemporaryDirectory() as tmp:
    root = Path(tmp)
    (root / "a.py").write_text("a = 1\n")
    init_repo(root)
    head = git(root, "rev-parse", "HEAD")
    sha = create_checkpoint(root, "before the agent")
    (root / "a.py").write_text("broken\n")
    (root / "junk.txt").write_text("x\n")
    print("status:", git(root, "status", "--short").splitlines())
    print("removed:", restore_checkpoint(root, sha))
    print("status:", repr(git(root, "status", "--short")))
    print("HEAD moved:", git(root, "rev-parse", "HEAD") != head, " checkpoints:", len(list_checkpoints(root)))
EOF
$ cd ..
status: [' M a.py', '?? junk.txt']
removed: ['junk.txt']
status: ''
HEAD moved: False  checkpoints: 1

The agent also saves a checkpoint by itself at the start of each run, so even a bad run has a way back. That event is the second line of the demo log.

Checkpoint

  • test_checkpoint_does_not_touch_head_or_index passes.
  • test_restore_undoes_edits_and_new_files covers edits, deletions and new files.
Step 18

Trace time, tokens and failures

Goal Answer the questions you ask after a bad run: how many calls, how many tokens, which tool was slow, how many retries.

The event log says what happened. A trace says what it cost. There is one span per model call and one per tool call.

    def span(self, kind: str, name: str, step: int) -> Iterator[Span]:
        s = Span(kind, name, step)
        t0 = time.perf_counter()
        try:
            yield s
        except Exception as e:
            s.ok, s.error = False, f"{type(e).__name__}: {e}"
            raise
        finally:
            s.duration_s = time.perf_counter() - t0
            self.spans.append(s)
Listing 44A span is a context manager. The finally records the time even if the body raises.

This is the table at the end of the demo run. It covers model calls, tool calls, tokens, latency, failures and retries.

model calls         13   latency    0.018s
tool calls          11   latency    1.849s
prompt tokens    53343   completion tokens 863
retries              0   failures 2

tool                   calls  fail   latency
edit_file                  2     1    0.003s
git_diff                   1     0    0.006s
read_file                  2     0    0.001s
run_tests                  2     1    1.812s
search                     1     0    0.028s
update_plan                3     0    0.000s

The model latency is close to zero because the model is a script. That makes this useful as a measure of the harness itself. bench_overheads.py runs 200 steps with a no-op tool.

200 steps in 0.223s: 1.11 ms per step   (AMD EPYC 7R13, 8 threads)

Checkpoint

  • test_tracer_summary_counts_tokens_and_failures passes.
  • test_transient_errors_retry_and_are_traced shows two retries in the summary.
Step 19

Assemble the agent and fix a real bug

Goal Inspect, search, edit, test, see the failure, repair and verify, with every piece from the earlier steps in the loop.

Here is the loop again. Compare it with Listing 1.

    def run(self, task: str) -> AgentResult:
        self.state.task = task
        self._append_message(self.log.append("UserMessage", 0, content=task).seq, Message("user", task))
        if self.config.checkpoint_on_start and is_repo(self.workspace):
            sha = create_checkpoint(self.workspace, "start of run")
            self.log.append("Checkpoint", 0, sha=sha, label="start of run")

        protocol_errors = 0
        for step in range(1, self.config.max_steps + 1):
            self.state.step = step
            context = self._build_context(step)
            try:
                response = self._call_model(context, step)
            except ModelError as e:
                self.log.append("Error", step, kind="model", message=str(e))
                return self._finish("model_error", str(e), step)
            ev = self.log.append("ModelResponse", step, text=response.text,
                                 tool_calls=[{"id": c.id, "name": c.name, "arguments": c.arguments}
                                             for c in response.tool_calls],
                                 parse_errors=response.parse_errors,
                                 usage={"prompt": response.usage.prompt_tokens,
                                        "completion": response.usage.completion_tokens},
                                 context=context.breakdown)
            self._append_message(ev.seq, response.to_message())

            if response.final:
                self.log.append("Final", step, text=response.text)
                return self._finish("done", response.text, step)

            step_had_protocol_error = bool(response.parse_errors)
            for call in response.tool_calls:
                step_had_protocol_error |= self._run_tool(call, step)
            if response.parse_errors:
                feedback = format_call_errors(None, response.parse_errors)
                ev = self.log.append("UserMessage", step, content=feedback, kind="feedback")
                self._append_message(ev.seq, Message("user", feedback))

            protocol_errors = protocol_errors + 1 if step_had_protocol_error else 0
            if protocol_errors >= self.config.max_protocol_errors:
                return self._finish("protocol_errors", "too many malformed tool calls in a row", step)
        return self._finish("max_steps", "step budget exhausted", self.config.max_steps)
Listing 45The production loop. It has the same shape as the eight lines, and the same stop rule. Everything else is a guard.

The eight-line loop had one exit. This one has four. The run can finish, run out of steps, hit too many protocol errors, or hit a permanent model error. Transient model errors, such as a rate limit, retry with backoff inside _call_model.

The demo

The toy repo has one real bug: median returns the upper middle value for an even-length list. The demo gives the scripted model a task and a script with three mistakes in it. It tries a forbidden install, writes broken JSON and quotes a line from memory. The script decides what the model says. The harness decides what happens next.

$ .venv/bin/python c10-agent-harness/scripts/demo_fix_test.py

Figure 9The real demo run, one frame per agent step, built from results/demo_events.jsonl. The bar shows the context against the 4,600 token budget.

Every mistake was handled in its own way. The install became a denial, the JSON became a parse error, and the stale quote became a helpful refusal. None of them stopped the run, and the task finished in 13 steps.

A real model

So we ran a real one. HFLocalModel follows the same interface. The chat template renders the tool schemas into the prompt. It generates greedily, and the same parser reads the text. This is the only part of the tutorial with tensors.

    def complete(self, messages: list[dict], tools: list[dict]) -> ModelResponse:
        import torch

        self.last_prompt = self.render(messages, tools)
        ids = self.tokenizer(self.last_prompt, return_tensors="pt").input_ids.to(self.device)
        # ids: (1, T_prompt) token ids
        t0 = time.perf_counter()
        with torch.no_grad():
            out = self.model.generate(ids, max_new_tokens=self.max_new_tokens, do_sample=False,
                                      pad_token_id=self.tokenizer.eos_token_id)
        # out: (1, T_prompt + T_new); the reply is the tail
        new = out[0, ids.shape[1]:]
        # <tool_call> is a plain added token in Qwen's vocab, but skip_special_tokens would also
        # drop it in some tokenizers, so decode everything and strip the end markers ourselves.
        text = self.tokenizer.decode(new, skip_special_tokens=False)
        for marker in ("<|im_end|>", "<|endoftext|>", "<|eot_id|>"):
            text = text.split(marker)[0]
        resp = response_from_text(text.strip(), Usage(ids.shape[1], int(new.shape[0])))
        resp.raw = text
        self.last_latency_s = time.perf_counter() - t0
        return resp
Listing 46A local Hugging Face model as a client. The comments state the shapes.
Tensors in one model call
TensorShapeMeaning
ids(1, T_prompt)The rendered prompt, tool schemas included, as token ids.
out(1, T_prompt + T_new)What generate returns: the prompt, then the reply.
new(T_new,)The reply only. We decode this.
What generate does inThe mechanics of LLM inference
$ .venv/bin/python c10-agent-harness/scripts/run_hf_agent.py --device cpu
model: Qwen/Qwen2.5-0.5B-Instruct on cpu, 494M parameters
[  0] step  0  UserMessage   task
      The test suite fails on median for even-length lists. Find the bug in stats_lib/core.py, fix it with edit_file, and run run_tests to check.
[  1] step  0  Checkpoint    {'sha': '73f991f6930c8dcf8d811210d7f0284301b37e1d', 'label': 'start of run'}
[  2] step  1  ModelResponse '' -> edit_file  [context ~1345 tok]
[  3] step  1  ToolCall      edit_file(path='stats_lib/core.py', search='median(odd)', replace='median(even)', replace_all=True)
[  4] step  1  Approval      edit_file risk=WORKSPACE_WRITE allowed=True (auto-approved (WORKSPACE_WRITE <= WORKSPACE_WRITE))
[  5] step  1  ToolResult    ERROR edit_file
      Error: read core.py before editing it
[  6] step  2  ModelResponse "I see that there was an error when trying to open 'stats_lib/core.py'." -> (final answer)  [context ~1407 tok]
[  7] step  2  Final         {'text': "I see that there was an error when trying to open 'stats_lib/core.py'. Let's try again."}

status: done after 2 steps
model calls          2   latency   13.457s
tool calls           1   latency    0.000s
prompt tokens     2239   completion tokens 68
retries              0   failures 1

tool                   calls  fail   latency
edit_file                  1     1    0.000s

bug fixed: False
test runs: []

This is the honest result. The model did not fix the bug. It tried an edit on its first move, without reading the file, and with a search string that does not exist. The harness refused it for being unread. The model replied in plain text that it would try again, and plain text means the run is over. The status says done, and the bug is still there.

Grading agents properly inThe agent evaluation playbook

Any server that speaks the OpenAI chat format also works, through OpenAICompatModel. It uses only the standard library, and reads its settings from the environment so that keys stay out of code and logs.

$ export OPENAI_BASE_URL=http://localhost:8000/v1
$ export OPENAI_API_KEY=...
$ export HARNESS_MODEL=your-model-name
$ .venv/bin/python c10-agent-harness/scripts/run_openai_agent.py

We have not run this client against a real model, so we have no numbers for it. The tests run it against a small fake HTTP server in the same process. They cover the request format, the mapping of errors to retries, and bad JSON in the arguments. results/openai_stub_output.txt is a full run against a local stub that replays scripted replies. It tests the client and the loop, and it says nothing about any real model.

Checkpoint

  • test_end_to_end_fixes_the_failing_test goes from 2 failed to 6 passed with real pytest.
  • The demo ends with status: done after 13 steps and writes 50 events.

The minimal loop and the full agent compared

Rows are the failures we met. Columns show what each loop does about them. Read down the middle column to see why each piece exists. The last column names the test that checks each row.

What happens when something goes wrong
FailureEight-line loopFull agentBuilt inTest
Unknown tool nameKeyError, run diesError lists the real namesStep 3test_validation_errors_go_back_and_the_model_recovers
Malformed JSONSpins with no feedbackParse error returned, four strikesStep 3test_too_many_protocol_errors_stops_the_run
Tool raisesRun diesShort report to the modelStep 3test_tool_bug_does_not_kill_the_loop
Stale editWrites it anywayRefused, read againStep 4test_stale_context_is_refused
Command hangsBlocks foreverGroup killed, status reportedStep 5test_timeout_kills_the_whole_process_group
Dangerous commandRunsAsks, and a denial is an observationStep 9test_denied_call_never_executes_and_is_logged
Huge outputAll in the contextHead, tail and rescued errors, within the 1 MB captureStep 16test_giant_observation_is_truncated_by_the_loop
Long runQuadratic costCompaction caps the prompt until the summary outgrows the budgetStep 15test_compaction_triggers_preserves_task_and_replays
Rate limitRun diesRetry with backoffStep 19test_transient_errors_retry_and_are_traced
Crash midwayEverything is lostHistory rebuilt from the logStep 14test_event_log_jsonl_round_trip

The pattern to notice: almost none of this is about the model. Most of the eight-line loop's failures are the harness not telling the model what went wrong, or not limiting what a wrong move can do.

Run everything

The final folder, and every command that produced a number in this post.

c10-agent-harness/ final tree
c10-agent-harness/
├── README.md  # how to run everything, results table
├── conftest.py
├── harness/  # the package
│   ├── __init__.py
│   ├── agent.py  # step 19: the full loop
│   ├── compaction.py  # step 15: summarise old turns
│   ├── context.py  # step 10: what the model sees
│   ├── editing.py  # step 6: edit formats and the applier
│   ├── events.py  # step 14: the JSONL event log
│   ├── fs_tools.py  # step 4: read, list, write, read-before-write
│   ├── git_tools.py  # step 17: status, diff, log, checkpoints
│   ├── loop_minimal.py  # step 1: the eight-line loop
│   ├── messages.py  # step 1: messages, calls, responses
│   ├── parsing.py  # step 3: text to structured calls
│   ├── permissions.py  # step 9: risk levels and the policy
│   ├── planning.py  # step 13: the checklist
│   ├── replay.py  # step 14: log to transcript
│   ├── repomap.py  # step 12: the repository map
│   ├── sandbox.py  # steps 5 and 8: process core, both backends
│   ├── search.py  # step 11: text search and symbols
│   ├── shell.py  # step 5: the shell tool
│   ├── tokens.py  # step 10: the token estimate
│   ├── tools.py  # step 2: schemas, validation, execution
│   ├── toolset.py  # step 19: the default tools and presets
│   ├── tracing.py  # step 18: spans and the summary
│   ├── truncation.py  # step 16: giant outputs
│   ├── verify.py  # step 7: tests, lint, typecheck, build
│   └── models/  # step 1 and 19: one interface, three clients
│       ├── __init__.py
│       ├── base.py
│       ├── hf_local.py
│       ├── openai_compat.py
│       └── scripted.py
├── examples/
│   └── toy_repo/  # a small project with one real bug
├── scripts/  # runnable entry points
│   ├── compare_trusted.py
│   ├── demo_docker_sandbox.py
│   ├── demo_fix_test.py
│   ├── minimal_loop.py
│   ├── run_hf_agent.py
│   ├── run_openai_agent.py
│   └── show_schemas.py
├── benchmarks/  # scripts that print the tables in this post
│   ├── bench_compaction.py
│   ├── bench_edit_formats.py
│   ├── bench_overheads.py
│   └── bench_truncation.py
├── tests/  # pytest suite
│   ├── helpers.py
│   ├── test_agent.py
│   ├── test_docker_sandbox.py
│   ├── test_editing.py
│   ├── test_fs_shell_sandbox.py
│   ├── test_git_models.py
│   ├── test_repo_context.py
│   ├── test_tools_and_parsing.py
│   └── test_verify_permissions.py
└── results/  # saved real outputs
    ├── bench_compaction.txt
    ├── bench_edit_formats.txt
    ├── bench_overheads.txt
    ├── bench_truncation.txt
    ├── compaction_series.json
    ├── compare_trusted.txt
    ├── demo_events.jsonl
    ├── demo_output.txt
    ├── docker_sandbox.txt
    ├── hf_events.jsonl
    ├── hf_output.txt
    ├── minimal_loop.txt
    ├── openai_stub_output.txt
    └── schemas.txt
$ .venv/bin/python -m pytest c10-agent-harness -m "not slow and not gpu and not network"
$ .venv/bin/python c10-agent-harness/scripts/minimal_loop.py
$ .venv/bin/python c10-agent-harness/scripts/show_schemas.py --tokenizer Qwen/Qwen2.5-0.5B-Instruct
$ .venv/bin/python c10-agent-harness/scripts/demo_fix_test.py
$ .venv/bin/python c10-agent-harness/scripts/run_hf_agent.py --device cpu
$ .venv/bin/python c10-agent-harness/scripts/demo_docker_sandbox.py
$ .venv/bin/python c10-agent-harness/scripts/compare_trusted.py
$ .venv/bin/python c10-agent-harness/benchmarks/bench_edit_formats.py --trials 200
$ .venv/bin/python c10-agent-harness/benchmarks/bench_compaction.py
$ .venv/bin/python c10-agent-harness/benchmarks/bench_truncation.py
$ .venv/bin/python c10-agent-harness/benchmarks/bench_overheads.py

On an AMD EPYC 7R13 with Docker present, the offline suite gives 178 passed in about 33 seconds. With the Docker daemon out of reach it gives 159 passed and 19 skipped, each with its reason.

The offline set leaves out 2 tests marked network, which download from the Hugging Face Hub, and one of those is also marked slow because it loads Qwen2.5-0.5B on CPU. Both passed before the last truncation fix and were not rerun after it, because they do not use that code. Nothing in this tutorial needs a GPU.

The scripts overwrite their files in results/, so your numbers replace ours. Use git checkout on that folder to get ours back.

Key insights and nuances

Exercises

  1. Add embedding search, and test whether it helpsHard Add a fourth backend that embeds code chunks and ranks by cosine similarity. Build a small set of questions with known answers about this repo, and compare it with find_symbol and search on how often the right file comes first. Report the case where it loses.
    Hint

    Split on the symbols from index_file, not on fixed line counts. Then each chunk is already one function.

  2. Measure real slip ratesHard The edit benchmark simulates its slips. Log every edit_file and apply_patch call from a real model over 50 small tasks, and sort the failures into the same rows. Then reweight the totals table. Does your choice of default format change?
  3. Keep the assertion when the log is floodedMedium Rescue spends its 30 lines from the top, so 200 earlier failures push out the assertion in step 16. Change the budget so it covers each kind of line, or the start and the end of the matches. Rerun the flood case, and check that the one-failure case stays at 100%.
    Hint

    Group the matches by their first word. FAILED and AssertionError then compete for separate slots.

  4. Close the shell gap in LocalSandboxMedium On Linux, try unshare --mount with a bind mount, or Landlock, so that cat ../secret.txt fails. Measure the extra cost per command against the 13 ms baseline and the 412 ms Docker figure.
  5. A model-written summaryMedium Agent accepts a summarizer argument. Write one that asks the model to summarise, keeping extractive_summary as a fallback. Compare the peak at 640 steps and budget 4,000 with the 8,273 in step 15. What does each summary forget?

Continue reading

References

Grouped by topic. Every entry links to its primary source.

Agent harnesses

Editing and repository maps

Tool calling formats

Processes and sandboxes