transition2.aiStart a project

Software Factories & AI-Assisted Engineering

Build an AI Agent Harness From Scratch in an Hour

A loop, a tool registry, one hook and a write-ahead log are enough to stop an agent deleting what it should not. Here is the whole thing.

Eric MacDougall ·

Answer first

An agent harness is a loop with a rulebook. Build four parts: a loop that asks the model for the next action, a tool registry that maps names to functions, a pre-tool hook that can deny an action, and a write-ahead log that records the intent before the tool runs. About sixty lines of standard-library Python is enough to show the idea and to prove, with a test, that an unguarded agent deletes your file and a guarded one does not.

!Diagram of the harness loop: the model proposes an action, the harness logs the intent, guard hooks allow or deny, then the tool runs and its result is logged, or the denial is logged and reported back to the model.

What the harness is for

The model proposes. The harness decides what actually happens. Everything that must be true regardless of what the model says, such as "never delete outside this folder" or "record before acting", belongs in code the model cannot talk its way past. Instructions in a prompt are advice. A hook is enforcement. For the wider picture, see the pinned harness README; this post builds only the smallest useful core.

Step-by-step build

  1. The loop. Ask the model for an action given the history. If it returns a final answer, stop. If it returns a tool call, continue. Add a step limit so a confused model cannot loop forever.
  2. The registry. A dictionary from tool names to functions. Register write_file and delete_file for a work directory.
  3. The write-ahead log. Before running a tool, append a JSON line with the step, tool and arguments, flush and fsync. After the tool, append a result line.
  4. The hook. A list of functions that take the tool name and arguments and return None to allow or a reason string to deny. A denial is logged and fed back to the model as a result.
  5. Two real rules. Deny any path that resolves outside the work directory (resolve links first). Deny a delete with no stated reason.
  6. Tests with a failing control. One test runs the same delete with the hooks off and shows the file disappears. If that test passes, your guard tests mean something.

The core in one place

def run(self, task, max_steps=8):
    history = [("user", task)]
    for step in range(max_steps):
        action = self.model(history)
        if "final" in action:
            self.wal("final", text=action["final"]); return action["final"]
        name, args = action["tool"], action["args"]
        self.wal("intent", step=step, tool=name, args=args)      # before acting
        reason = next((r for h in self.hooks if (r := h(name, args))), None)
        if reason:
            self.wal("denied", step=step, tool=name, reason=reason)
            history.append(("tool", f"DENIED: {reason}")); continue
        result = self.tools[name](**args)
        self.wal("result", step=step, tool=name, ok=True)
        history.append(("tool", result))
    self.wal("stopped", reason="max_steps"); return "stopped: step limit"

A scripted model stands in for the real one, so the lab needs no API key and gives the same answer every time. A small demo script prints the log below. We ran a scripted agent that tries to delete a file without a reason, then tries again with one:

{"event": "intent", "step": 0, "tool": "delete_file", "args": {"path": "keep.txt"}}
{"event": "denied", "step": 0, "tool": "delete_file", "reason": "delete needs a reason"}
{"event": "intent", "step": 1, "tool": "delete_file", "args": {"path": "keep.txt", "reason": "user asked"}}
{"event": "result", "step": 1, "tool": "delete_file", "ok": true}
{"event": "final", "text": "ok"}

What the tests prove

Eight tests ran and passed. The log shows intent, result and final in order on the happy path. A delete with no reason is denied and the file survives. A path that escapes the work directory is denied and the outside file survives. The control test builds the same harness without hooks and confirms the file is deleted, which is the failure the guard exists to prevent. A link inside the work directory that points outside it is refused. A call to a tool that does not exist is denied and logged, with no crash. A step limit stops a model that loops. And when a tool raises an error, the log still contains the intent line and no result line, so you can see what was attempted.

What this toy does not do

  • The reason check only requires that a reason exists. A made-up reason passes. It makes deletion deliberate and recorded, not correct.
  • The hook runs in the same process. An agent that can run arbitrary code, or edit the hook, defeats it. Treat it as a guard against careless actions, not a security boundary.
  • The log is local and has no redaction, so do not put secrets in arguments.
  • There is no recovery: after a crash you can read the log but nothing resumes the work.
  • The model here is scripted. We did not test it against a live model.

Where to go next

Add redaction to the log, a spend cap per run, a second hook that flags commands you cannot parse (and decide which way it leans when unsure), and a way to resume from the log. Each is a separate small piece. See Guard Hooks for Agent Shells and A Write-Ahead Log for AI Agents for those two parts in more depth.

FAQ

What is an agent harness?
The code around a model that runs its loop: it asks the model for an action, checks the action against rules, runs the tool, records what happened and feeds the result back. The model decides; the harness enforces.
Why log the intent before running the tool?
If the process dies during the tool, a log written only afterwards shows nothing. An intent line, flushed to disk first, tells you what was attempted and that no result followed.
Is a guard hook a security boundary?
No. A hook in the same process catches careless actions. It does not stop an agent that can edit the hook, run code outside the harness or use a tool the hook never sees.
Do I need a framework to build one?
No. The core is about sixty lines of standard-library Python. Frameworks help once you need persistence across restarts, many tools or many agents.

Sources