Harness Engineering for Agents
Pure State Machines Fail-Closed Security & Systems Rigor
An agent system that runs a user's shell commands and edits their files cannot afford ambiguity about what it is allowed to do. A single misrouted secret, one unvalidated tool output that gets interpreted as instructions, or a retry loop that re-executes a side effect after a crash can destroy trust in the entire system. The industry answer has been to add more layers of prompting: "be careful with the user's data," "never run dangerous commands." These are verbal guardrails, not computational ones. They fail the moment the model hallucinates, gets confused by context, or faces a prompt injection.
The alternative is to build the harness itself as a pure state machine. Pure, meaning all decision logic about retries, permission levels, and recovery paths is separated from I/O and clocks. State machine, meaning the harness's behavior is a finite set of states and transitions, not a free-form loop that can drift into unexpected territory. When you combine this with a fail-closed security model every permission gate defaults to denial and a rigorous boundary between trusted and untrusted code, the harness becomes auditable, testable, and provably safe. This section hardens the architecture you built in the previous three weeks: the loop, the context control, and the durable execution all become constrained by written constitutions, pure functions, and enforced module boundaries.
Architectural Constitution and Boundaries
Every production agent begins as a single TypeScript file that gradually accretes imports, helpers, and global state. After a few hundred lines, it is impossible to tell which modules are allowed to call the shell, which can read secrets, and which are pure data transformers. The fix is to write a composition root a single file that creates all long-lived objects and wires them together with explicit dependency injection. No module imports a database client or a sandbox handle directly; it receives them through its constructor or a factory function. This makes the dependency graph a directed acyclic graph you can verify with a static analysis tool.
The composition root also enforces module import boundaries. The sandbox provider, which executes shell commands, lives in one directory. The session loop, which drives the ReAct cycle, lives in another. The pure retry planner, which decides whether to retry after an error, lives in a third with zero I/O imports. You encode these rules in a file like RULES.md and enforce them with a linter or a build step that rejects any import crossing the boundary in the wrong direction. The core state machine never imports fs, net, or child_process. The payoff is that you can compile this same core to three targets: a CLI binary, a WebAssembly module that runs in a browser sandbox, and a Node-API native addon. The build script build.zig selects the target-specific I/O shim, but the pure decision logic remains byte-identical across all three.
spec: static diagram of three build targets (CLI, WASM, Node-API) each wrapping a central Core State Machine block. Arrows from Core to each target labelled "pure decision logic". Outside each target, a thin I/O shim labelled "fs, net, child_process" connects to its platform. The labels say "Core: zero I/O imports, pure retry/recovery planners".
Pure Decision Logic and Formal Verification
A retry planner decides: after a tool call returns an error, should the agent retry the same tool, escalate to a human, or abort the entire task? If this decision contains a single call to Date.now() or Math.random(), the planner becomes nondeterministic. You cannot replay a session and get the same decision. You cannot reproduce a crash. The solution is a zero-I/O, zero-clock, zero-allocation planner: a pure function that takes the error type, the step count, and a static config, and returns a retry action or a terminal failure. No database access, no network calls, no access to the system clock. This function lives in its own module with no dependencies on the rest of the harness.
Once the planner is pure, you can verify its behavior with model checking. Write a TLA+ specification of the recovery protocol: the planner's states, the transitions (retry, escalate, abort), and the conditions that trigger each transition. Then let the TLA+ model checker explore all reachable states. It will find deadlocks, infinite retry loops, and state transitions that are reachable but should not be. For example, you might discover that a "lease expired" error can trigger a retry that immediately fails again because the lease has already been yielded, creating a 2-state cycle that never terminates. The model checker finds this in seconds. You fix the planner by adding a "lease lost" terminal state, and the model checker confirms the fix.
Common trap: Believing that a pure function is "obviously correct" because it has no side effects. A pure function can still have infinite loops or incorrect transition logic. Model checking catches those, not just I/O violations.
Fail-Closed Security and Prompt-Injection Defense
Every tool call in the agent passes through a single permission choke point. This is a function that takes the tool name, its arguments, and a permission level, and returns either a "denied", "approved", or "needs-human" decision. The permission level is one of three values: "ask" (prompt the user every time), "auto" (allow tool calls that the agent deems safe), and "full-access" (allow everything for a trusted agent). The critical design rule is that the choke point defaults to "ask" for any tool not in an explicit allowlist. And the allowlist is defined statically, not generated by the LLM.
The hardest defense is against prompt injections that trick the model into running arbitrary shell commands. The harness mitigates this through cross-shell command parsing parity. It does not just pass the LLM's command string to the shell. Instead, it parses the command string using the same parsing rules as the target shell (sh, dash, bash, zsh) and checks that the command matches an allowlist pattern. A command like rm -rf / is caught at parse time because no allowlist entry matches it. A command that tries to obfuscate itself with shell metacharacters is caught because the parser recognizes the unescaped expansion. The key insight is that you cannot rely on the LLM to sanitize its own output. You must apply a deterministic parser that matches the system shell's grammar.
Every LLM output that contains a security-relevant decision, such as "I will grant full access to the user's home directory," is evidence-quoted back to the model for confirmation. The harness runs a second, minimal inference call that takes the output and asks: "Confirm or deny this action: [quoted output]." If the model does not confirm with the exact quoted text, the action is held in a fail-closed hold and escalated. This prevents the LLM from being tricked into granting permissions via a prompt injection that hides the dangerous action in the middle of a long response.
spec: static diagram of the permission flow. Input from LLM goes to "Cross-Shell Parser" box, then to "Allowlist Match" box (yes/no check). If no, flow goes to "Permission Choke Point" which branches to "Ask User", "Auto Allow (limited)", or "Full Access". If parser fails, flow goes to "Fail-Closed Denial". Bottom label: "single choke point defaults to ask".
Prompt-Cache and Token Economics
Each step of the agent loop consumes tokens for the system prompt, the tool registry, the conversation history, and the newly generated output. In a production agent running hundreds of steps, the token cost can dwarf the inference cost. The solution is to make the prompt prefix as stable as possible. The system instructions, the tool definitions, and the interaction protocol must not change between steps in a session. A stable prefix guarantees that the LLM provider's prompt cache will reuse its cached attention computation, reducing latency and cost by 5-10x.
To keep the prefix stable, the harness uses minimal static tool registries. Instead of dynamically generating tool descriptions from a database, it defines them in a static TypeScript array that changes only with a code deployment. The Model Context Protocol (MCP) schema for each tool is loaded lazily on first use, not appended to every prompt. The resulting tool registry is small (under 500 tokens for a typical agent) and identical for every step of the session.
Image attachments and large file outputs are kept out of the prompt cache. The harness computes a SHA-256 hash of any image and stores the hash in the transcript log. The image itself is offloaded to a disk-backed store that the LLM provider fetches only when the hash changes. Similarly, long tool outputs are truncated and stubbed: the harness stores the full output in a separate log and inserts a short stub token (e.g., <tool_output:sha256:abc123>) into the context window. The LLM sees the stub and can request the full output if needed.
Mental hook: Every token you put into the prompt prefix must be there on every step. If it is not needed on every step, lazy-load it. If it is not needed at all, delete it.
Distributed Fencing
When multiple workers may hold the same task, for example, if a crash causes a second worker to pick up the task, you need to prevent stale writers from corrupting state. The harness uses optimistic writer fencing. Every state mutation carries a monotonically increasing generation number. When a worker attempts to write, it includes its generation number. The storage layer rejects any write whose generation number is less than the current stored value, raising an FxFencedError. The worker must then abort and yield its lease.
The lease itself has a deadline. A worker acquires a lease for, say, 30 seconds. If the deadline passes without a renewal, the lease is automatically released. This prevents a crashed worker from holding a lease forever. But leases introduce a subtle problem: a worker that has completed a side effect, such as writing a file, and then loses its lease before it can commit the result, has created an orphan side effect. The harness handles this by ensuring that all side effects are replay-safe. The file write is idempotent if the worker restarts, it overwrites the same file with the same content. The database insert is idempotent because it uses a requestId as a unique key.
Every durable execution session has a stable executionId, derived from the task ID and an attempt counter. The worker includes this executionId in every side effect. A downstream system, such as an email service, can deduplicate based on executionId. A worker that restarts with the same executionId will produce the same side effects, and the downstream system will ignore duplicates. A worker that restarts with a new executionId will produce new side effects, but the old worker's effects will have been rolled back by the fencing mechanism.
Capstone: Retry State Machine Allowlists and Cache Test
Build a pure retry state machine as a TypeScript class with no I/O, no clock access, and no allocations. The machine has five states: Idle, Retrying, Escalated, Aborted, and Success. It takes an input of { errorType: string, retryCount: number, maxRetries: number } and returns the next state and a reason string. Write a static allowlist for shell commands (e.g., ["ls", "cat", "grep", "head", "tail", "wc", "find"]) and implement the cross-shell parser that rejects commands not in the allowlist. Then add a cache-prefix regression test: a script that starts a mock LLM provider, sends 10 identical requests, and asserts that the prompt prefix is byte-identical across all 10. If the prefix changes, the test fails, alerting you that a code change destabilized the cache.
AI-generated study article from SophistAI. Sign up free to study it with an AI tutor.