Gates that must be able to fail
A gate is only as good as its evidence. Five in my coding loop read a proxy, two of them one the loop wrote itself. Breaking the work on purpose shows which.
By Nelson D’Souza · · 15 min read
- AI Agents
- Verification
- Testing
- Go
In this note
- The loop
- Who writes the evidence
- 140 acks for an empty file
- Verification that ran nothing
- The agent writes its own tests
- The shapes a proxy takes
- Done, with no code
- A timeout that did not bound time
- A task id that walked out of the repo
- The cheapest pass was a bug
- A double that ran ahead of the server
- Reviewers are a gate too
- Five gates, one proxy
- How to tell
- Break the work and watch it go red
- Read the test's name for a quantifier
- Look at the distribution
My coding loop has a gate that refuses to start a task until the task has acknowledged what the loop has learned. Over eight days it passed all 24 task starts it guarded. I only looked closely when I opened its records to quote one, and found that nothing had been learned.
That gate is one of five in the loop that passed while the work they guarded was wrong. Each one checked a proxy: something that is usually true when the work is right, and cheap to read. In two of them the loop also manufactured the proxy. An unattended agent loop is where that costs the most, because nobody watches each step. The other four had been fixed earlier, as they surfaced. Breaking the work on purpose is how to check the rest, and the tests underneath the gates fail the same ways.
The loop#
Bob the Builder is a Go command-line tool I built to run a delivery loop on a repository with as little supervision as I can get away with. Its command is adev, and it keeps its state in a .adev directory inside the repository. It picks a task, gives it to a coding agent in an isolated git worktree, runs the task’s checks, opens a pull request, has a sandboxed reviewer read the diff, and records what it learned before it moves to the next task. Nobody watches each step, so every step ends at a gate—which means a silent bug in a gate is worse than a bug in the code.
The architecture document describes the tool as a closed-loop delivery controller. The loop has nine stages, and a failed gate sends the work back with a fix task rather than forward.
- Plan the task to Acquire context
- Acquire context to Execute in a worktree
- Execute in a worktree to Verified?
- Verified? to Bounded repair, then escalate: “no”
- Verified? to Publish the PR: “yes”
- Publish the PR to Review clean?
- Review clean? to One fix task per finding: “no”
- Review clean? to Capture a learning: “yes”
- Capture a learning to Distil into principles.md
- Distil into principles.md to Next task's ack hashes principles.md
- One fix task per finding to Execute in a worktree: “rework”
Some of the gates enforce structural isolation rather than judgement. The reviewer runs in a read-only bwrap sandbox, sees only the pull request’s diff, and must cite a file and line for every finding. A review is refused if the local branch head does not match the pull request’s head, so nobody reviews a diff that is no longer the code. Still, diff-only LLM reviewers generate false positives and miss cross-file callers (as seen in Alfred below). Each finding becomes a fix task whose id is a hash of the finding (PRFIX- plus twelve hex characters), so the same finding found twice maps to the same task.
The rest follow the standard practice for agent loops. An agent reports that the tests pass, the task is done, the command timed out, the principles were read, and each report becomes a gate: an exit code, a status field, a file on disk. That is the right move, since machine-readable evidence checked every time beats a report. Every gate below was built that way, and each one passed while the work it guarded was wrong.
Who writes the evidence#
140 acks for an empty file#
Before a task starts, the loop requires a memory ack: a small JSON record with the task id, a timestamp and the SHA-256 of .adev/learnings/principles.md. RequireAck refuses to start the task unless the record exists and its hash matches the file as it is now. The intent is that no task starts until the current distilled principles have been acknowledged, and that every old ack goes stale when they change.
When I opened the ack directory to quote one, I found 140 acks written over eight days, all for review-fix (PRFIX-) tasks. Every one carries the same hash:
$ grep -h principles_hash .adev/learnings/acks/*.json | sort | uniq -c
140 "principles_hash": "fef2d3ba3723541df1b17b16e8a8d07ac51eff60895a4fd38bc666338d5de988",
$ printf '# Principles\n\n' | sha256sum
fef2d3ba3723541df1b17b16e8a8d07ac51eff60895a4fd38bc666338d5de988 -That is the hash of a heading and a blank line. There is no principles file in the directory. There is no learnings file either: the directory contains the acks and nothing else. Here is the function that produced the hash:
func CurrentPrinciplesHash(repoRoot string) (string, error) {
path := filepath.Join(repoRoot, ".adev", "learnings", "principles.md")
b, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
b = []byte("# Principles\n\n")
} else {
return "", err
}
}
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:]), nil
}A missing file is treated as the default text. And adev init seeds principles.md with exactly that default text, so a missing file and a freshly created one hash the same. Then there’s the question of who writes the ack. When the review loop turns findings into fix tasks, it calls MemoryAck for every new task id, right away. The record the gate checks is written by the same loop the gate is supposed to constrain.
So every check passed. Seventeen of those fix tasks were started, 24 times in all, and RequireAck found the hash fresh at every start. The compliance audit asks whether each started task has an ack file, and every one did. Neither check asks whether there was anything to acknowledge. Over those eight days the loop recorded no learnings and distilled no principles, and the gate that exists to carry learning into the next task reported success every time.
- File exists? to Use the default text: “no”
- File exists? to Read the file (seeded with the same text): “yes”
- Use the default text to SHA-256; the review loop writes the ack
- Read the file (seeded with the same text) to SHA-256; the review loop writes the ack
- SHA-256; the review loop writes the ack to Hash matches?
- Hash matches? to Proposed: any principles?: “yes, every time”
- Proposed: any principles? to Warn: nothing distilled yet: “no”
- Proposed: any principles? to Start the task: “yes; ack records the count”
This gate’s fix is still open. When the principles file is absent or equal to the seeded default, the ack should fail, or at minimum warn loudly with “nothing distilled yet”. And the ack should record the principle count alongside the hash. The distiller already returns a PrincipleCount; the ack ignores it. With the count in the record, an audit would see “140 acks, 0 principles” where today it sees 140 clean records.
A brand-new repository has no principles, and a hard failure would block its first task. A warning in the audit record lets the loop run without anyone mistaking an empty ritual for memory.
The count closes the empty-file case and leaves a deeper one. An ack records that a hash was current when the task started. It says nothing about whether the coding agent read the principles, because the agent never signs it. The review loop calls MemoryAck for the fix tasks it creates, and for other tasks adev memory ack is a step run before task start that hashes the file and reads nothing else. For the ack to mean the principles were read, the agent would have to do something with them that the loop can check. Nothing in the loop does that yet.
Verification that ran nothing#
The ack was written by the loop. The verify gate had the same problem one stage earlier.
Every task card has a ## Verification section, and the verify stage runs each entry as a shell command. Task cards are generated from a plan, and plans are written by people and models, so a Verify line is sometimes prose, something like “parser handles empty input”. The planner had a friendly fallback for that. This is the line the fix removed:
// internal/planner/materialize.go, before the fix
out = append(out, fmt.Sprintf("echo %q", trimmed))A descriptive Verify line became echo "parser handles empty input". That exits 0. The verify stage ran the list, saw only zeros, and passed. The gate measured “every command in the list exited 0”, and the planner had made sure there was always a list of commands that would.
The fix rejects descriptive text and echo-only entries in three places: when the plan is turned into task cards, when a card is validated, and when verification runs. The first strict version then rejected CGO_ENABLED=0 go test ./..., which is a real command, so leading KEY=value assignments are allowed when a real command follows them. A line that is only an assignment is still invalid.
The fix is narrower than it sounds. It closes the downgrade the planner performed. It doesn’t prove a command checks anything: true is a real command, exits 0, and would pass.
The agent writes its own tests#
The same question reaches the tests themselves. In the loop’s strict profiles, a task that changes code without changing tests fails with test_delta_missing, and the test packages a task touches must fail before implementation starts, a red baseline. The coding agent writes those tests. Orchestration runs verification itself and keeps the agent’s own list of tests it ran only as advisory evidence, so the agent doesn’t get to report its own result. The checks being run were still written by the thing being checked.
That’s the pattern in all three. If the system being gated also writes the record the gate reads, the gate can catch mistakes in the writing and nothing about the work. The ack came from the review loop, the echo from the planner, and the tests from the agent.
The shapes a proxy takes#
The other gates read something the work really does produce. They read too little of it.
Done, with no code#
task complete moved a task forward without any link to a commit. A task could reach review with last_commit empty, and the audit trail could not say which code a finished task referred to. The gate checked that someone had asked for the transition.
Completion now needs a commit whose subject starts with <TASK_ID>:, and the rules are narrow on purpose:
- Subject only. A task id mentioned in a commit body does not count. A body can mention any task, so a mention is no evidence of work on it.
- Reachable from
HEAD. A matching commit that exists only on another branch does not count, because it isn’t the code being shipped. - Non-empty. A matching commit that changes no files is refused.
- Recorded. The matched SHA is stored in
last_commit, andaudit traceemits agit/task_linkrecord for it.
Each rule has a regression test: no history, wrong prefix, prefix only in the body, commit only on another ref, and the valid case. It’s still a proxy. A commit with the right subject that touches one unrelated file would pass. But the work leaves it in the repository, where an audit can follow it to the code.
The audit trail needed the same treatment. A learning recorded from an earlier review shows that task, review and escalation transitions could succeed while the append of their state event failed, because the event write was treated as best effort after the change. Now the state change rolls back if its audit event does not land. A transition without its record is the same failure as a task without its commit.
- Starts in pending.
- pending to in_progress: “memory ack required”
- in_progress to in_review: “commit '<ID>:' reachable from HEAD”
- in_review to done: “review passes”
- in_review to changes_requested: “findings”
- changes_requested to in_progress: “rework”
- done is a final state.
A timeout that did not bound time#
The executor that runs the coding agent has a timeout, implementation_executor_timeout_seconds. It used Go’s exec.CommandContext(...).Run(): when the context expires, the child is killed and Run returns.
Except that the executor’s output is captured into buffers, so Run also waits until the copying from the child’s pipes finishes, and a pipe stays open while any process holds its write end. A shell that starts a background process hands that process its stdout. Kill the shell and the grandchild keeps the pipe open, and Run keeps waiting.
The regression test made this concrete. It sets a 150 ms timeout and runs a command that starts a background child sleeping for 5 seconds. The timeout fired, the error said “timed out”, and the call returned after about 5 seconds, when the grandchild finished its sleep. The old test checked the error text, which was correct. It never looked at the clock.
- Orchestrator to Executor shell: “start the executor”
- Executor shell to Background child: “fork; child inherits stdout”
- Orchestrator, internally: “150 ms deadline fires”
- Orchestrator to Executor shell: “before: kill the shell only”
- Background child replies to Orchestrator: “pipe still open; Run() waits ~5 s”
- Orchestrator to Background child: “after: kill(-pgid) at the deadline”
- Executor shell replies to Orchestrator: “Wait() returns within the bound”
- Orchestrator, internally: “test asserts elapsed time and dead child”
The fix, on Unix, gives the executor its own process group, replaces Run with explicit Start and Wait, and has the deadline timer kill the whole group (syscall.Kill(-pid, SIGKILL)) while Wait is in progress. Go 1.20’s Cmd.WaitDelay would also have bounded the wait, by closing the pipes after a grace period, but it leaves the grandchild running. Killing the group ends both. The kill is SIGKILL with no SIGTERM first, so the agent gets no grace period. A git command it was running at that moment can leave a lock file in the worktree, and nothing in the loop clears one. The test now asserts two things the old one didn’t: elapsed time under 2 seconds, and that the background child’s process id no longer exists.
A task id that walked out of the repo#
Task ids flow into file paths: message threads, run artifacts, acks. The only check was that the id was not empty. msg send --task '../../outside' exited 0 and created directories outside the thread namespace, and task complete '../../outside_task' could write <repo>/outside_task/artifacts.json.
This is path traversal, one of the oldest classes in the book, and it enters the same way every time. An identifier becomes a path the moment something joins it into one, and a check written for the identifier says nothing about the path. “Not empty” is a proxy for “safe to join into a path”, and a poor one. The same crossing turns up across my other agents in Defend where data changes role. The fix is one validator, called at the command line, in the application layer and in the message store:
var allowed = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$`)It also rejects path separators and dot segments with their own error messages, so the person who typed the bad id learns why. The important word is one. Three ad hoc checks drift apart over time. One function can still be left out at a new boundary, but it can’t disagree with itself.
The cheapest pass was a bug#
Tests take the same shapes, and here they matter more, because the agent writes them. Two from other projects of mine show shapes an agent could produce as readily as I did.
Some rules have no cheap behavioural test, so you write a structural guard: a test that reads the source and checks the rule there. In Geysera, guards like that had matched a module’s own docstring, which explained the rule in prose. So one guard stripped comments before searching:
re.sub(r"^\s*#.*$", "", src, flags=re.M) # the whole file, strings includedA line-based regex can’t tell a comment from a # inside a string, which is the standing limit of matching source without parsing it. The cheapest way to pass that guard was to move the explanation inside the SQL string and start it with #. That’s what happened. # isn’t a comment in PostgreSQL, so the statement became a syntax error, and the tests stayed green.
The earlier gates failed to see a defect. This one pushed toward one. In a loop, a red gate goes to bounded repair, and whatever does the repair is rewarded for the smallest change that turns it green. If the smallest change is a bug, the gate is the hazard.
A double that ran ahead of the server#
The chess tutor’s frontend tests run against a test double that stands in for the server’s game state. Its contract tests asked whether the double had fallen behind the real payload, missing a key the server sends. Nobody asked whether it had run ahead. The move list was written to mark blunders, its tests passed, and no mark ever appeared in the running app, because the real server never sent classification. Only the double did.
The move keys are now checked exactly, both ways: missing keys fail and extra keys fail. An agent that writes a feature and its fixture in the same task can make this mistake in one step, because the fixture describes the payload the feature needs and nothing compares it with the server.
Reviewers are a gate too#
The reviewer stage fails the same way when its output is read as a verdict. In Alfred, a knowledge base maintained by an LLM agent, I run model reviewers in parallel, one lens each. After one feature phase, seven of them reported 38 issues. I fixed 18, deferred 6 that were really feature work, and dismissed 14. Two of the fixed ones would have broken production: a migration that added a status without updating its CHECK constraint, and a path-containment helper called with its arguments reversed.
What made these lists usable was treating them as candidates. In one review, four reviewers reached the same directory bug from four angles, which is good evidence, though less independent than it looks, since they share a model and its blind spots. In another, a simplicity reviewer called two exports dead when the CLI entry point imported both. That same review found fifteen todos from the previous phase still marked pending, although every one had been fixed in a commit. The status had gone stale; the commits were what counted.
Five gates, one proxy#
Line the five gates up:
| Gate | What it checked | What it was meant to prove | The check now |
|---|---|---|---|
| Verification | every listed command exited 0 | the checks ran | descriptive text and echo-only entries are rejected; true would still pass |
| Completion | a transition was requested | code for the task exists on HEAD | a non-empty commit whose subject starts with <TASK_ID>:, reachable from HEAD |
| Timeout | the deadline fired | the call returned by the deadline | the whole process group dies at the deadline; the test reads the clock |
| Task id | the string was not empty | the path stays inside the repo | one allowlist validator at every layer |
| Memory ack | the hash was fresh | the agent was handed what the loop learned | still open: fail or warn when nothing is distilled, and record the principle count |
| Agent-written tests | the agent’s own red/green test passed | the test actually asserts the requested behaviour | open: still relies on human review or mutation checks; not gated independently |
Post-fix longitudinal escape and triage rates on adev are not yet measured.
Each gate checked a proxy, and the tests underneath do the same. A string in a file stands in for “the code does this”, and a double stands in for the server. Proxies are fine until something can satisfy them without satisfying the property. In an agent loop that something is everywhere, and it isn’t only the model. None of these five needed a model to game anything. In two, my own code manufactured the proxy: the planner wrote the echo, and for the ack, the hash function supplied the default and the review loop wrote the record.
That’s why these failures are quiet. The proxy is the thing that’s almost always present, so the gate rarely fails loudly. You find out by reading the evidence itself. I found the ack problem by opening a real record to quote.
How to tell#
Break the work and watch it go red#
A gate is an instrument, and an instrument nobody has held against a known-bad input is untested. So break the work on purpose, in the shape the gate exists to catch, and confirm the gate fails. That’s mutation testing aimed by hand. Tools such as Stryker, PIT and mutmut generate the broken versions, called mutants, from a fixed set of operators; the targeted version writes one per gate. A mutant is killed when a check goes red. It survives when everything stays green.
The timeout test is one: a background child that would outlive the deadline, and an assertion on the clock. The completion tests are another, with a task id that appears only in a commit body. The loop’s red baseline is the same habit applied to the agent’s tests, with a mutant it gets for free: the code before the change.
Two details decide whether the result means anything. First, confirm the mutation landed. A find-and-replace that matches nothing changes nothing, and its green looks exactly like a gate that caught nothing. Second, when a mutant survives, ask whether it changed anything a user could see. If it did, the gate has a hole. If it didn’t, it’s an equivalent mutant: different code, same behaviour, and no test should kill it.
Read the test’s name for a quantifier#
Mutation finds faults in code that exists. An omission has no line to break. Here is a Geysera spending test:
def test_it_refuses_when_either_cap_is_reached(self, src):
assert "_daily_spend_and_cap" in src
assert "_lifetime_spend_and_cap" in srcDelete either call and it goes red, so it kills every mutant aimed at it. There were three spending ceilings: daily, lifetime and the customer’s plan. The handler checked exactly the two the test named. Either is two, and a test can’t be more complete than the model in its author’s head. When a name says either, both or the two, count the real cases before trusting it. An agent writing tests from a task card inherits whatever the card left out, and the name is where that shows. The handler now calls a single budget function, and the test asserts that one call.
Look at the distribution#
One ack looks fine. A uniq -c over all of them shows 140 copies of one value. Evidence that never varies can be legitimate, since the principles might not have changed, but it’s worth one more step: here the one value was the hash of the default text. Good evidence is something the work leaves behind: a commit on HEAD, a process that is gone, an elapsed time, a principle count.
All of this comes down to one question: what would have to be true for this gate to pass while the work is wrong, and what’s the cheapest way to make it pass? The question doesn’t retire after a fix. Asked again while I wrote this, it turned up true in the verification gate.
Built in: Bob the Builder, Chess Tutor, Geysera, Alfred