GNGiseldo Neo and Alana NeoBooks
Building AI Agents7 / 18

The harness

“If the model is a source of decisions, the harness is what decides which decisions are allowed.”

Objective

Assemble the complete harness — tool registry, policies, budget and tracing — and understand why the system prompt is not a security boundary. By the end, the reader has an agent that tries to perform destructive actions and is stopped by the code, not by the model’s goodwill.

4.1 Six responsibilities

If the loop is the engine, the harness is the car. The harness is everything around the loop that makes it usable: the tools, the policies, the budget, tracing, context management, skill loading.

The distinction is useful because it organizes the work. The loop almost never changes. The harness changes all the time — it is where you add a tool, tighten a policy, improve the logging.

A minimal but honest harness has six responsibilities:

  1. Tool registry — a map from name →\rightarrow function + schema, with validation.

  2. Policies — rules the model cannot violate, enforced in code, not in the prompt.

  3. Budget — ceilings on steps, time and tokens, with an explicit stop reason.

  4. Tracing — a record of what happened, in a queryable format.

  5. Context — assembling the history and compacting it when it grows.

  6. Skills — loading procedures on demand.

4.2 Policies: the model cannot be trusted

The most important sentence in this book, for anyone about to put an agent into production: the model is not a security boundary. Instructions in the system prompt are suggestions. A model can be convinced to ignore them — by a malicious user, by poisoned text on a page it read, or simply by confusion.

Policies are rules enforced in code, after the model has decided and before the action happens.

Listing 4.1. Deny policy enforced at the point of execution.

DENY_PATTERNS = [
    r"\brm\s+-rf\b",
    r"\bformat\b",
    r"\bshutdown\b",
    r":\(\)\s*\{",              # fork bomb
    r"curl[^|]*\|\s*(ba)?sh",   # pipe-to-shell
]

def check_command(command: str) -> None:
    for pat in DENY_PATTERNS:
        if re.search(pat, command):
            raise PolicyError(
                f"command blocked by policy: matched /{pat}/")

Two observations about this list.

First, it is a denylist, and denylists always leak. The robust defense is not “forbid what is bad” but “permit only what is good” — an allowlist. The example uses denial because it is instructive, but in a real system you want the opposite: a small set of permitted commands, and everything else blocked by default.

Second, the policy must be enforced at the point of execution, not while building the prompt. If the check exists only in the system prompt, it is a suggestion. If it is in check_command, it is a barrier.

A real allowlist. In production, the recommended pattern is something like this: the shell tool accepts only a fixed set of programs (ls, cat, grep, python) and rejects any other executable. This survives a compromised model, a poisoned prompt and a creative hallucination. A denylist survives none of the three.

4.3 Budget: stopping is a feature

A harness without a budget is a harness that will surprise you with the bill. The budget must be explicit and must produce a readable stop reason.

Listing 4.2. Budget with three ceilings and a named stop reason.

@dataclass
class Budget:
    max_steps: int = 10
    max_tokens: int = 800
    max_seconds: float = 2.0
    steps: int = 0
    tokens_used: int = 0
    started: float = field(default_factory=time.monotonic)
    stop_reason: str | None = None

    def charge(self, text: str) -> bool:
        self.tokens_used += max(1, round(len(text) / 3.6))
        if self.tokens_used > self.max_tokens:
            self.stop_reason = f"token_budget ({self.tokens_used} > {self.max_tokens})"
            return False
        return True

    def tick(self) -> bool:
        self.steps += 1
        if self.steps > self.max_steps:
            self.stop_reason = f"step_budget ({self.max_steps})"
            return False
        if time.monotonic() - self.started > self.max_seconds:
            self.stop_reason = f"time_budget ({self.max_seconds}s)"
            return False
        return True

Running it with three different configurations, the behavior is exactly as expected:

Listing 4.3. Output of three budget configurations.

generous           -> stopped: step_budget (50)  (steps=51, tokens=6450)
tight tokens       -> stopped: token_budget (903 > 800)  (steps=7, tokens=903)
tight steps        -> stopped: step_budget (3)  (steps=4, tokens=387)

The detail that matters: the stop is always named. An agent that stops with “step limit reached” can be debugged; an agent that simply hangs cannot.

4.4 Tracing: what actually happened

Every harness needs a record. Not a print — a structured record, in JSON Lines, that you can load later and analyze.

Listing 4.4. Append-only tracing in JSON Lines.

def trace(event: str, **payload) -> None:
    with TRACE.open("a", encoding="utf-8") as fh:
        fh.write(json.dumps({"t": round(time.time(), 3),
                             "event": event, **payload},
                            ensure_ascii=False) + "\n")

JSON Lines is the right choice for three reasons: it is append-only (it does not get corrupted if the process dies midway), it is easy to filter with jq or Python, and it is easy to feed into an observability tool later.

What to record: every tool call with arguments and result, every stop decision, every policy block, every context compaction. The trace is the difference between “the agent got it wrong” and “the agent got it wrong because in step 4 the tool returned an empty result and it interpreted that as success”.

4.5 The complete harness, running

Putting policies, validation, budget and tracing together in a single script gives this result:

Listing 4.5. Harness output: four calls, two blocked.

available skills (metadata only in the prompt):
  - environment-report: How to inspect the local environment and produce
    a short report.

[step 1] run_shell({'command': 'python --version'}) -> 'Python 3.14.9'
[step 2] run_shell({'command': 'rm -rf /'}) -> '{"error": "policy:
          command blocked by policy"}'
[step 3] read_file({'path': '../../../etc/passwd'}) -> '{"error":
          "policy: read outside the workspace blocked"}'
[step 4] run_shell({'command': 'ls skills'}) -> 'environment-report'

loading skill on demand:
  environment-report: 673 chars loaded into context

trace written to trace.jsonl: 4 events

Four calls, two blocked, one successful, one skill loaded. The agent tried to read outside the workspace and was stopped — not because the model is polite, but because the harness did not let it.

Note also the read policy: the read_file above resolves the path and checks that it is inside the working directory before opening it. This check is the same idea as the shell policy, applied to files. The agent sees {"error": "policy: read outside the workspace blocked"} as an observation, and the process continues.

4.6 Errors worth distinguishing

A well-built harness distinguishes at least four types of error, because the model reacts differently to each:

CategoryExampleHow the model reacts
Policy errorForbidden commandTends to rephrase or give up
Argument errorMissing required fieldTends to fix it and retry
Environment errorFile does not existTends to investigate before repeating
Tool errorInternal bug, exceptionTends to repeat and fail again

Table 4.1. Error categories in a harness.

The fourth row is the most treacherous. If the tool has a deterministic bug, the model will repeat the same call, get the same error and repeat again until it exhausts the budget. Putting a per-tool attempt counter in the harness solves this: on the second identical failure, the harness returns an error with an explicit instruction (“this tool is failing repeatedly; do not try again”).

Common pitfall

Turning off tracing in production “because it generates too many files”. The result is that the first real incident — cost exploded, the agent deleted something, a wrong answer reached the customer — has no record to investigate. Tracing is cheap insurance: if the volume is a concern, rotate files and define retention; do not turn it off.