53. Loop engineering

Chapter 52 made a spec an agent can execute, with acceptance tests as the grade. This chapter closes the loop an engineer runs around that grade: implement, have a reader that did not write it review the result, fix what the review found, and stop at a verdict. The loop is a client of the daemon, with a ledger of its own, a fix-round budget derived from this book’s production record, and a reviewer that is shown evidence before it reads a line.

One round of the loop over the daemon Session names are shown without the run id that follows the spec id in a real run. From the bottom: one wide box for the daemon, aecd, holding the sessions, the daemon's own ledger and bwrap; dashed lines join the driver and the review session to it. Above it, two session boxes. The work session, median-work, holds two turns, implement and fix. Below it the review session of round one, median-review-1. The sessions do not talk to each other: everything crosses through the driver. At the left, the driver, aec-work run, with its round ledger drawn as five lines: run, step_begin, step_end, report, stop. An arrow from the driver to the work session carries the spec and the findings; an arrow from the driver to the review session carries the spec, the diff, the acceptance results and the mutation report; an arrow from the review session back to the driver carries the reviewer's findings block. Two lightning marks show the crash points the lab kills at: the driver's, between step_begin and step_end, and the daemon's, at before-record inside its own ledger. Two arrows leave the driver, below the review session, to the right: accepted, and stopped by a breaker or the budget. aec-work run round ledger run step_begin step_end report stop driver killed after step_begin, before its step_end median-work implement fix median-review-1 spec, findings spec, diff, acceptance, mutants findings accepted stopped: breaker | budget aecd sessions, its own ledger, bwrap daemon killed at before-record

Why this layer exists

Chapter 37 made the trajectory the scored unit. Chapter 40 made a daemon that survives a kill in the middle of a turn. Chapter 52 made the statement of the work a document whose acceptance commands are chapter 37 graders. None of the three closes the loop a software engineer runs by habit: write the change, have it read by something that did not write it, fix what that reading found, stop. This chapter is that loop, aec-work run, written as a client of aecd’s control socket and nothing more; the daemon knows nothing about rounds. Four properties are stated here and shown below.

  1. The reviewer’s evidence is not the model’s word. Before the reviewer reads anything, the driver has run the acceptance tests on the attempt’s commit and planted bugs in the files the attempt changed, and the reviewer is given both reports.
  2. The loop has a budget derived from this book’s own record, and two breakers that stop a loop the budget alone would not.
  3. Every step is in a ledger of the driver’s own, with chapter 40’s durability. The driver, the daemon or both can die and the run continues from where the ledger says.
  4. No model-chosen command runs outside bwrap, and none runs without an approval the run recorded.

This book’s production loop is the case study: the roles here are the roles of the book’s AGENTS.md (“How work is done”): one implementer per task, then an independent reviewer who recomputes, fix rounds until the review is clean, and a ledger that tells a resumed session where things stand. The record of those rounds is quoted where a number is needed.

What the chapter does not build is a multi-agent graph (two roles over one daemon are not a graph), a second evaluation stack (the acceptance tests are chapter 43’s exec graders and nothing else grades), a model-written mutator, or the roles carried by chapter 45’s delegate. The last needs a reason: a reviewer needs its own session, its own role, its own trace and its own resume, and a delegate call is not idempotent, so a crash inside one cannot be replayed.

Mechanism

The loop as sessions

The package’s surface is three functions over one ledger: Run drives the loop to a verdict, Resume continues it from the ledger after a crash, and Status reads the ledger without a daemon. Result is what chapter 54 reads.

// Options is one run of the loop.
type Options struct {
    Spec            *spec.Document
    SpecFile        string         // the file Spec was parsed from: Run keeps its bytes beside the ledger (RUNDIR/spec.md) and checks them against Spec.Hash
    Client          *daemon.Client // the daemon's control socket (chapter 40)
    Git             *repo.Git
    Repo            string // the repository the worktree is cut from
    Dir             string // the run directory: ledger.jsonl, rounds/<n>/, trials.jsonl
    Budget          Budget
    Sandbox         string   // the backend for the acceptance tests and the mutation pass; "" refuses to start
    Approve         string   // deny | client (the driver answers approval/ask by AllowCommands); allow is refused (ruling X9-10)
    Reviewer        string   // the role the reviewer turn is sent under; default "aux"
    AllowCommands   []string // RE2 patterns a terminal command must match for the client approver to allow it (10b-R3); nil allows none
    AllowUnisolated bool     // run the acceptance tests and the mutation pass under a backend that does not isolate filesystem and network (tests only, every command the test's own; never set by aec-work)
    MaxMutants      int      // the cap Mutants takes; default DefaultMaxMutants
    Clock           func() time.Time
    Log             func(format string, args ...any)
}

// Budget is the fix-round budget and the breakers. A zero field is its
// default; the chapter derives the defaults from the book's own record.
type Budget struct {
    MaxRounds     int           // fix rounds after the first review; default 3
    MaxTokens     int           // prompt + completion over the run, from the trial records; default 400k
    MaxSeconds    time.Duration // wall over the run; default 1 h
    NoProgress    int           // rounds in a row whose finding count did not fall; default 2 (the breaker)
    RepeatFinding int           // a finding text that returns this many rounds running trips the breaker; default 2
}

// Step is one turn of the loop.
type Step string

const (
    Implement Step = "implement"
    Review    Step = "review"
    Fix       Step = "fix"
    LearnStep Step = "learn" // after an accepted attempt: one more primary turn that writes a skill (D-i)
    Land      Step = "land"  // chapter 54 appends it; this package stops at Verdict
)

// Finding is one line of a reviewer's report, parsed from the fenced
// report the reviewer turn ends with (the format is the book's own:
// severity, location, text).
type Finding struct {
    Severity string // critical | important | minor
    Where    string
    Text     string
    Hash     string // sha256 of Severity+Text folded, what RepeatFinding compares
}

// Round is one review and the fix that answered it.
type Round struct {
    N        int
    Findings []Finding
    Mutants  MutationReport
    Accept   []eval.Trial // the acceptance tests' trials for this round
    Fixed    bool
    Stop     string // "" while the loop goes on; else the breaker or budget that stopped it
    Began    time.Time
    Ended    time.Time
}

// Result is what Run returns and what Status reads from the ledger.
type Result struct {
    Spec     string // the spec's hash
    Branch   string
    Worktree string
    // Exclude is the ignore file the run's git commands read (the repo.Git
    // field of that name), in the run directory. The worktree holds the
    // toolchain's files that file keeps out of every commit (a build cache,
    // the scratchpad), so a Git that does not carry it sees them as untracked:
    // build the Git a consumer uses on this worktree with GitFor.
    Exclude string
    // Base is the commit the run's worktree was cut from, as the run line
    // records it (the spec's base branch name only in a ledger that predates
    // the commit). Everything that compares the attempt against its base
    // (the diff, .spec/, the eval suite, chapter 54's gates) reads this
    // commit, never the branch name, which may have moved since.
    Base string
    // Head is the worktree's head as the last step_end that moved it
    // recorded it: the branch's head, what chapter 54 lands; "" when no step
    // changed the base.
    Head    string
    Rounds  []Round
    Verdict string // accepted | rejected | stopped:<reason> | resumed
    // Tokens is prompt + completion over the step_end lines. A turn a crash
    // cut off is re-sent, and only the re-sent turn's usage reaches the
    // ledger (the first is in the daemon's trace), so after a crash the sum
    // is low by that turn.
    Tokens   int
    Seconds  float64
    Skill    string   // the learned skill's directory, "" when the learn step did not run or was refused
    Reason   string   // the reason in a rejected run's stop line
    InFlight string   // "round/step" of the step that began and did not end, for an unfinished run
    Sessions []string // the session ids the run opened, the work session first, then each round's review session (chapter 54's Attempt.Sessions)
}

// Run drives the loop to a Verdict, writing the round ledger as it goes.
// Every name carries the run id (8 hex digits from crypto/rand, drawn at the
// start and recorded in the run line), so two runs of one spec share no
// session, worktree or branch, whatever their run directories. It opens one work session (<spec id>-<run id>-work, the primary
// role) for the implementer and every fixer turn, cuts the worktree into
// that session's workspace itself (ruling P10-35: its root is the repository,
// the terminal's working directory, so `go test ./...` runs on the module) on the branch <spec id>-<run id> from the
// base commit it records (the daemon's tools see it; nothing else of the host
// does), and one review session per round (<spec id>-<run id>-review-<n>, the
// reviewer role), so each review is independent of the last; it sends the
// spec as the implementer's turn, commits what the turn left, runs the
// acceptance tests and the mutation pass under Sandbox on an export of the
// commit (never the worktree), sends the reviewer the diff and both reports,
// parses the findings, and, while the budget and breakers allow, sends the
// fixer the findings.
// accepted means the last review found nothing above minor and every
// acceptance test passed; stopped:<reason> means a breaker or the budget
// ended the loop with findings left; rejected means the attempt failed in a
// way no fix round answers: a turn that did not complete, a tampered worktree,
// a commit that cannot be graded.
func Run(ctx context.Context, o Options) (Result, error) { return run(ctx, o) }

// Resume continues a run from its ledger: the last complete step is read,
// a step that began and did not end is re-sent (its daemon turn is
// chapter 40's to resolve: a tool call in flight at the crash follows the
// daemon's resume policy, and the driver sees the turn's result or its
// resolution in session/open's Resolved), and the loop goes on. A ledger
// whose spec hash differs from the spec given is refused.
func Resume(ctx context.Context, o Options) (Result, error) { return resume(ctx, o) }

// Status reads the ledger without a daemon.
func Status(dir string) (Result, error) { return status(dir) }

Two kinds of session, both opened over the control socket. The work session holds the implementer’s turn and every fixer’s turn: one history, so the fixer sees what the implementer tried. It must be one session because the daemon fixes a session’s workspace and chapter 27’s file tools stay inside it; the attempt’s git worktree is that workspace itself, and a fixer in a session of its own could not reach it. The daemon makes the workspace an empty directory, and git worktree add cuts into an empty directory, so the driver cuts there and the terminal’s working directory is the module’s root: the model’s natural go test ./... runs on the module, with no -C and no cd. That holds when go.mod is at the repository’s top. A module whose go.mod is below the top (this book’s own layout keeps it in go/) is not served by go test ./... from the root, which matches no packages, and the allowlist has no -C to reach it.

Two consequences follow. The terminal’s HOME is the workspace, so the Go build cache (.cache), GOENV’s file (.config), GOPATH (go) and the scratchpad tool’s SCRATCH.md land at the worktree’s top, beside the attempt’s files. The driver writes a short ignore file into the run directory, which the model cannot reach, and gives git its path as core.excludesFile for every command, so those names are not staged into the attempt’s commits. A tracked go/ of source is not affected, and go/pkg and go/bin are named in that file only when the base commit holds nothing at that path: a repository that keeps source under go/pkg keeps the attempt’s new files there, at the price that the approver (below) refuses every go command while go/pkg exists. The run directory itself must lie outside the main repository, and Run refuses one inside it before it writes anything. A main repository that lies inside the work session’s workspace, where the model could write its .git, is refused as well, before the worktree is cut.

The file travels with the result (Result.Exclude, recorded in the run line, so Status and Resume return it), because anything that later asks git whether the worktree is clean must read the same file: repo.Remove without force on an accepted run’s worktree is ErrDirty for a Git that lacks it, and workflow.GitFor(git, result) builds the one that has it. Git.Exclude is refused when it lies inside the worktree the command runs in, so a file the model could rewrite cannot be the file that decides what is staged. And the gitfile at the top is the one .git the tamper check accepts, exactly as git wrote it; a write of another .git there is rejected, as a nested one is.

The review session is new for each round. Independent readings are what the repeat breaker below compares, and a reviewer that carried its previous review in its context would agree with itself. Everything the reviewer reads is in its prompt: the spec, the diff of the attempt’s commit against the base, the acceptance results and the mutation report, each quoted as data. Its own workspace is the empty directory the daemon made for its session, because the worktree is the work session’s; read_file there finds nothing, by design, and a go command there would have no module to run. The reviewer judges what the driver shows it and nothing else, which is what makes the diff the complete record of what shaped the grade (below).

Both session names, and the branch, carry a run id: <spec id>-<run>-work, <spec id>-<run>-review-<n> and <spec id>-<run>, with <run> eight hex digits drawn from crypto/rand when the run begins and recorded in the ledger’s first line. The spec id alone would not do. Two runs of one spec through one daemon, or one run directory deleted and made again at the same path, would otherwise open the first run’s sessions and be accepted with the first run’s commit. A run refuses a branch, a worktree or a session that already has turns and that its own ledger does not claim.

The roles are chapter 28’s: the implementer and the fixer run under primary, the reviewer under aux, and the capture’s routes.json is where the reviewer becomes another model. What “independent” means here is narrower than the word. The reviewer is another family with other priors, it reads the same spec and the same diff, and it reads two reports it did not write. Whether that makes its findings better than the implementer’s own model would give is a claim the chapter does not measure. It would be measured with a placebo design: the same reviewer model given the diff with and without the driver’s reports, paired by attempt, with the rule registered before the run. Exercise 5 asks for it.

The approver

A model that implements a Go change has to run go test, and the daemon’s terminal tool is marked: its NeedsApproval is unconditionally true, and the loop asks the tool after the policy has answered. Under -approve deny no model-chosen command ever runs. Under allow every one does, which this book’s rule X9-10 (chapter 52’s git section) forbids for any session with an exec tool, so aec-work run refuses -approve allow before it dials a socket. The third mode is the one the daemon already had: the approval is asked of the connection that sent the turn. The driver answers it.

// shellMeta are the bytes and sequences that make a command more than the
// one a pattern names: a separator, a pipe, a background, a substitution, a
// redirection, a quote or escape, a glob, a brace, a comment, a history
// mark. Every byte outside printable ASCII (a tab, a newline, a NUL, a
// multi-byte character) is refused as well. All are refused before any
// pattern is tried, so a looser pattern a reader writes cannot reintroduce
// them. This approver is policy, not containment: it decides which commands
// go without a person, and an approved command still runs inside the
// sandbox (bwrap under the local backend), where the filesystem, the network
// and the process table are the sandbox's to limit.
const shellMeta = ";&|`$><\\'\"*?[]~{}#!()"

// The go command's flags a client-approved command may carry, by whether
// they take a value (-flag=value or -flag value). Every other flag is
// refused, so the flags that run a program (-exec, -toolexec, -vettool),
// write a file (-o, -coverprofile, -cpuprofile, -memprofile, -trace) or
// substitute one (-overlay, -modfile, -mod, -ldflags, -gcflags) never pass on
// the command line; the same flags in a GOFLAGS file are goConfig's to refuse.
var goFlags = map[string]bool{"run": true, "count": true, "timeout": true, "tags": true, "v": false, "race": false, "short": false, "cover": false}

// goShaped says a command runs the go tool: any word is go or ends in /go.
// A wrapper (env, nice, timeout, xargs, an absolute path) is go-shaped too, so
// the argv check below cannot be skipped by putting go second.
func goShaped(argv []string) bool {
    for _, w := range argv {
        if w == "go" || strings.HasSuffix(w, "/go") {
            return true
        }
    }
    return false
}

// goArgsOK is the post-match argv check for a go-shaped command: the command
// is exactly `go build|vet|test` (the terminal's working directory is the
// module, so no -C), each later argument beginning with
// a dash is an allowed flag in one of its forms with a value from the safe
// character class, and every other argument is a package pattern: relative,
// no ".." element. A pattern author who writes a looser regular expression
// still gets this, for every command that names go anywhere.
func goArgsOK(argv []string) bool {
    if len(argv) < 2 {
        return false
    }
    switch argv[1] {
    case "build", "vet", "test":
    default:
        return false
    }
    args := argv[2:]
    for i := 0; i < len(args); i++ {
        a := args[i]
        if strings.HasPrefix(a, "-") {
            name, val, hasVal := strings.Cut(strings.TrimPrefix(strings.TrimPrefix(a, "-"), "-"), "=")
            takesVal, ok := goFlags[name]
            if !ok || name == "" || (hasVal && !takesVal) {
                return false
            }
            if takesVal && !hasVal {
                if i+1 >= len(args) || strings.HasPrefix(args[i+1], "-") {
                    return false
                }
                i++
                val = args[i]
            }
            if takesVal && !safeWord(val) {
                return false
            }
            continue
        }
        if !safeWord(a) || strings.HasPrefix(a, "/") {
            return false
        }
        for _, el := range strings.Split(a, "/") {
            if el == ".." {
                return false
            }
        }
    }
    return true
}

func safeWord(s string) bool {
    if s == "" {
        return false
    }
    for i := 0; i < len(s); i++ {
        c := s[i]
        if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.IndexByte("_./=-", c) >= 0) {
            return false
        }
    }
    return true
}

// goConfig are the files, relative to a session's workspace, through which a
// go command reads flags and modules nobody approved. The workspace is the
// terminal's HOME and its working directory, and the attempt's worktree: so
// .config/go/env is GOENV's file (GOFLAGS=-exec=… there runs a program of the
// model's choosing under an approved `go test`), go.work and go.work.sum at
// the module's top replace the module the command names, and go/pkg is
// GOPATH's module cache. A go command is refused while any of them exists,
// or while the workspace is unknown. go/ itself is not listed: a repository
// may keep source under a tracked go/ (this book does), and only GOPATH's
// own pkg/ is what the toolchain reads from it.
//
// This is best-effort shape policy and racy by nature: the model can write
// the file in the same turn after the ask is answered, and an approved
// `go test` runs the model's own code anyway, which can do whatever the file
// would (ruling P10-29). It keeps the approved command what it looks like;
// the containment is bwrap, and the sandbox keeps a command from escaping,
// not from lying about the tests it runs.
var goConfig = []string{".config/go/env", "go/pkg", "go.work", "go.work.sum"}

func goConfigPresent(ws string) bool {
    if ws == "" {
        return true
    }
    for _, rel := range goConfig {
        if _, err := os.Lstat(filepath.Join(ws, filepath.FromSlash(rel))); err == nil || !errors.Is(err, fs.ErrNotExist) {
            return true
        }
    }
    return false
}

// clientApprover answers the daemon's approval/ask for a run whose Approve
// is "client". Each pattern of o.AllowCommands compiles once, as a full
// match (^(?:p)$), so "go test" cannot allow "go test; rm".
// A terminal command is allowed when it holds no shell metacharacter and
// matches a pattern, and, if it names go, passes goArgsOK while no goConfig
// file exists in the asking session's workspace (workspace maps a session id
// to it); skill_write is allowed only while the step is Learn; every other
// marked call is denied. Nothing is allowed by default: no patterns allows no
// command. The daemon records each answer as an approval span and an audit
// record with By "client", which is the evidence.
func clientApprover(o Options, step func() Step, workspace func(session string) string) (func(daemon.AskRequest) (string, error), error) {
    pats := make([]*regexp.Regexp, 0, len(o.AllowCommands))
    for _, p := range o.AllowCommands {
        re, err := regexp.Compile("^(?:" + p + ")$")
        if err != nil {
            return nil, fmt.Errorf("workflow: allow pattern %q: %w", p, err)
        }
        pats = append(pats, re)
    }
    return func(ask daemon.AskRequest) (string, error) {
        answer := answerFor(ask, pats, step(), workspace(ask.Session))
        sum := sha256.Sum256([]byte(ask.Arguments))
        if o.Log != nil {
            o.Log("ask %s %s %s -> %s", ask.Session, ask.Name, hex.EncodeToString(sum[:])[:12], answer)
        }
        return answer, nil
    }, nil
}

func answerFor(ask daemon.AskRequest, pats []*regexp.Regexp, step Step, ws string) string {
    switch ask.Name {
    case "terminal":
        var a struct {
            Command string `json:"command"`
        }
        if json.Unmarshal([]byte(ask.Arguments), &a) != nil || a.Command == "" {
            return "deny"
        }
        for i := 0; i < len(a.Command); i++ {
            if c := a.Command[i]; c < 0x20 || c > 0x7e || strings.IndexByte(shellMeta, c) >= 0 {
                return "deny"
            }
        }
        for _, re := range pats {
            if re.MatchString(a.Command) {
                if argv := strings.Fields(a.Command); goShaped(argv) && (argv[0] != "go" || !goArgsOK(argv) || goConfigPresent(ws)) {
                    return "deny"
                }
                return "allow"
            }
        }
    case "skill_write":
        if step == LearnStep {
            return "allow"
        }
    }
    return "deny"
}

This is a shape policy over a command line. The byte refusal comes first and is not a pattern: a separator, a pipe, a substitution, a redirection, a quote, a glob, any byte outside printable ASCII is denied before any pattern is read, so a looser pattern a reader writes cannot reintroduce them, and go test ./... ; curl … is refused on the ;. The patterns are full matches. A command that names go anywhere then passes an allowlist of flags and of package patterns, and is refused while a file through which the go tool reads flags nobody approved exists in the workspace. The working directory of the daemon’s terminal is the workspace root, which is the worktree, so the command is the plain go test ./... and the allowlist has no -C (a -C anywhere is a flag it does not list). Every answer is an approval span and an audit record with By: client.

The containment is not here. An approved go test runs the model’s own code, which can do whatever the model could have typed. What stops it from escaping is bwrap, under chapter 43’s limits, and the approval is recorded so that if the shape policy were wrong the record would say what it let through. The daemon’s own backend limits matter too. The Go toolchain does not start under chapter 43’s default 512 MiB of address space, so the capture’s aecd.json carries the limits spec.SandboxLimits() returns (4 GiB of memory, 256 processes, no network, a read-only root), and the driver’s acceptance backend uses the same value. One set of limits serves both.

The evidence before the review

After each implement or fix turn the driver commits what the turn left, then grades a tracked-only export of that commit, plus the spec’s .spec/ files, never the worktree. Here is why. The worktree is a directory the model wrote into, and the go tool reads $HOME/.config/go/env, with HOME at the graded tree. A file the model wrote there is not in the commit, so it is not in the diff the reviewer reads, and yet it changes what go test does. Grading the commit’s export removes it from the grade. It does not remove the class of problem, and the section below measures how far the problem goes.

The acceptance commands run through chapter 43’s eval.Exec, as Runner.Trial runs an exec grader, under the backend the run names. Then the mutator. It enumerates, with go/ast over the changed non-test files only (a mutant in untouched code tests the fixture’s tests, which is not the question), six kinds of edit: arithmetic, relational and boolean operators, the constants 0, 1 and -1, a return’s expression zeroed, a condition negated.

// Mutant is one planted bug: a file, a position, the operator or literal
// replaced and what replaced it, produced by go/ast over the file's bytes
// (no go/printer: the file is edited at the node's byte range, so every
// other line is the original's) from the files the attempt changed (and
// only those: a mutant in untouched code tests the fixture's own tests,
// which is not the question).
type Mutant struct {
    ID     string `json:"id"` // sha256 of File, Line, Col, From, To; stable across runs
    File   string `json:"file"`
    Line   int    `json:"line"`
    Col    int    `json:"col"`
    Kind   string `json:"kind"` // arith (+ -), rel (< <= > >= == !=), bool (&& ||), const (0 1 -1), ret (a return's expression zeroed), cond (if c → if !c)
    From   string `json:"from"`
    To     string `json:"to"`
    Killed bool   `json:"killed"`
    Detail string `json:"detail,omitempty"` // the exec grader's detail for the mutant's run
}

// Mutants enumerates the mutants of the Go files named (paths under dir),
// at most max, in file and position order; the enumeration is a pure
// function of the file bytes, so a reviewer on another machine lists the
// same ids.
func Mutants(dir string, files []string, max int) ([]Mutant, error) { return mutants(dir, files, max) }

// MutationReport is the pass's result: every mutant with its verdict, the
// survivors first in the text the reviewer reads. Killed/Total is the
// mutation score; an equivalent mutant (one no test can kill, such as < to <=
// where both branches return the same value) stays in Total, so the score is
// read against the equivalents the reviewer finds among the survivors.
type MutationReport struct {
    Total    int      `json:"total"`
    Killed   int      `json:"killed"`
    Survived []Mutant `json:"survived,omitempty"`
    Timeouts int      `json:"timeouts"`
    Detail   string   `json:"detail,omitempty"` // why the pass did not run, when it did not (no Go file changed; the baseline failed)
    Seconds  float64  `json:"seconds"`
    Verdicts []Mutant `json:"verdicts,omitempty"` // every mutant with Killed and Detail set, in order (the round's report keeps it)
}

// Mutate grades the unmutated tree first and then each mutant, each in a
// fresh copy made from dir, under the backend, as eval.Exec runs the
// acceptance tests: a mutant is killed when the build or any test fails
// (status not ExpectStatus), survived when all pass; one that does not
// compile is killed by the compiler and marked so. dir must be a tree no
// sandboxed process has run in (the worktree, not the build tree the
// acceptance tests ran in): the host never writes into, or trusts, a
// directory after a sandboxed process ran there, so the mutated file is
// written into the copy before its run and the copy is removed unread. A
// symlink or any file but a regular file in dir is refused, a mutant whose
// File is not a path inside dir is refused, and a baseline that fails
// (ErrBaselineFails) refuses the pass with nothing counted. The warm Go build
// cache is the one thing carried from the baseline's copy to the mutants'
// (as inert regular files), so the toolchain builds cold once. The backend is
// the caller's to choose: Mutate checks that one is given and not that it
// isolates (Run does).
func Mutate(ctx context.Context, b sandbox.Backend, dir string, ms []Mutant, accept []eval.Exec) (MutationReport, error) {
    return mutate(ctx, b, dir, ms, accept)
}

// Text renders the report for the reviewer's turn: counts first, then one
// line per survivor with the diff of its one line, inside prompt.Quote's
// fence under the label "mutation", as every tool's text is.
func (r MutationReport) Text() string {
    var sb strings.Builder
    fmt.Fprintf(&sb, "mutants %d, killed %d, survived %d, timeouts %d, %.1f s\n", r.Total, r.Killed, len(r.Survived), r.Timeouts, r.Seconds)
    if r.Detail != "" {
        sb.WriteString(r.Detail + "\n")
    }
    for _, m := range r.Survived {
        fmt.Fprintf(&sb, "%s %s:%d:%d %s: %s -> %s\n", m.ID, m.File, m.Line, m.Col, m.Kind, m.From, m.To)
    }
    return prompt.Quote("mutation", strings.TrimRight(sb.String(), "\n"))
}

Three choices carry the weight. The edit is a replacement of the node’s bytes in the source, not a reprint, so a survivor’s line and column are the reader’s. The id is a hash of file, line, column and the two strings, so a reviewer on another machine lists the same mutants. And every mutant, and the unmutated baseline first, runs in a fresh copy made from a tree no sandboxed process has run in: the host never trusts or writes into a directory after sandboxed code ran there, and a baseline that fails refuses the pass with nothing counted.

The score. With TT mutants, KK killed and EE equivalent, meaning no test could kill them because the edit does not change behaviour,

MS=KT−E. MS = \frac{K}{T - E}.

EE is not computable: whether two programs are equivalent is undecidable in general, which is the equivalent-mutant problem the survey in Further reading treats. The pass therefore reports K/TK/T and lists the survivors, and the reviewer’s job is to sort each survivor into a gap in the tests (name the test that would kill it) or an equivalent mutant (say why). A Wilson interval over KK of TT (chapter 38’s, not rederived) says how sensitive the tests are to this operator class on this change. It does not say how many real faults the tests catch. What connects the two is the coupling hypothesis of DeMillo, Lipton and Sayward: tests that kill simple faults are sensitive enough to kill complex ones. Offutt’s experiments support it over one class of faults, and Andrews, Briand and Labiche compared mutants with real faults and with hand-seeded ones; the book treats the hypothesis as a hypothesis.

The fixture of the mutator’s own tests is the worked example, because there the equivalents are known. The mutation pass over a small Clamp function plants nine mutants and five are killed (straylight, TestMutateKillsAndSurvives in internal/workflow, over its own Clamp fixture and that fixture’s tests):

mutant edit verdict
8:5 cond x < lo to !(x < lo) killed
8:7 rel < to <= survived, equivalent: at x == lo both branches return lo
9:10 ret lo to 0 survived, test gap: no test clamps up to a non-zero bound
11:5 cond x > hi to !(x > hi) killed
11:7 rel > to >= survived, equivalent
12:10 ret hi to 0 survived, test gap
14:9 ret x to 0 killed
19:9 ret a + b to "" killed
19:11 arith + to - killed by the compiler: - is not defined on strings

Five of nine over all, five of the seven that are not equivalent; the compile kill is marked so a reviewer never credits the tests with it.

The review’s report

The reviewer’s prompt ends with the form its answer must take: a block between two marker lines, last in its final message, one finding per line. The driver parses that block and nothing else of the review’s text.

// The reviewer's report is a block of lines between two markers, the last
// thing in its final message. One finding per line, "severity | where |
// text", split on the first two bars (a fourth field joins the text); the
// word none on a line of its own is a report of no findings. Parsing uses
// strings.Split, Cut and Fields and no regular expression, so there is no
// pattern to backtrack on a hostile report.
const (
    ReportOpen  = "---findings---"
    ReportClose = "---end---"
    // MaxFindings bounds the lines read from one block; the rest are dropped
    // and one more finding says how many.
    MaxFindings = 200
    // maxBlockBytes cuts a block before it is split.
    maxBlockBytes = 64 << 10
)

// The severities, in the order the fixer reads them.
const (
    Critical  = "critical"
    Important = "important"
    Minor     = "minor"
)

// ErrNoReport is ParseFindings' answer to a message with no complete block.
// The driver turns it into one important finding: a review that did not
// report is not evidence that there was nothing to report.
var ErrNoReport = errors.New("workflow: no findings block in the review")

// ParseFindings reads the last complete block of text (a model that writes
// two gets its second read; ParseReport says how many it wrote). A line with
// a severity outside critical, important and minor is kept as an important
// finding "unparsed: <line>", so a malformed line is never dropped.
func ParseFindings(text string) ([]Finding, error) {
    fs, _, err := ParseReport(text)
    return fs, err
}

// ParseReport is ParseFindings plus the number of complete blocks found.
func ParseReport(text string) ([]Finding, int, error) {
    lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n")
    var block []string
    blocks, start := 0, -1
    for i, l := range lines {
        switch strings.TrimSpace(l) {
        case ReportOpen:
            start = i
        case ReportClose:
            if start >= 0 {
                block, blocks, start = lines[start+1:i], blocks+1, -1
            }
        }
    }
    if blocks == 0 {
        return nil, 0, ErrNoReport
    }
    joined := strings.Join(block, "\n")
    if len(joined) > maxBlockBytes {
        joined = joined[:maxBlockBytes]
    }
    var out []Finding
    dropped := 0
    var body []string
    for _, l := range strings.Split(joined, "\n") {
        if strings.TrimSpace(l) != "" {
            body = append(body, l)
        }
    }
    if len(body) == 1 && strings.EqualFold(strings.TrimSpace(body[0]), "none") {
        return nil, blocks, nil
    }
    for _, l := range body {
        if len(out) >= MaxFindings {
            dropped++
            continue
        }
        out = append(out, parseLine(l))
    }
    if dropped > 0 {
        out = append(out, newFinding(Important, "report", fmt.Sprintf("the report held %d more lines than the %d read; they were dropped", dropped, MaxFindings)))
    }
    return out, blocks, nil
}

func parseLine(l string) Finding {
    sev, rest, ok := strings.Cut(l, "|")
    if ok {
        where, text, ok2 := strings.Cut(rest, "|")
        sev = strings.ToLower(strings.TrimSpace(sev))
        if ok2 && (sev == Critical || sev == Important || sev == Minor) {
            return newFinding(sev, strings.TrimSpace(where), strings.TrimSpace(text))
        }
    }
    return newFinding(Important, "report", "unparsed: "+strings.TrimSpace(l))
}

func newFinding(sev, where, text string) Finding {
    f := Finding{Severity: sev, Where: where, Text: text}
    f.Hash = FindingHash(f)
    return f
}

// fold lower-cases, collapses runs of white space to one space and trims:
// chapter 31's Normalize without its typography, in a line.
func fold(s string) string { return strings.ToLower(strings.Join(strings.Fields(s), " ")) }

// FindingHash is the first 8 bytes of sha256(severity "\n" fold(text)) in
// hex. Where is not hashed: a line number moves when a fix lands above it.
// Two reviews of two independent sessions that say the same thing in other
// words' spacing or case hash alike, which is what the repeat breaker reads.
func FindingHash(f Finding) string {
    sum := sha256.Sum256([]byte(f.Severity + "\n" + fold(f.Text)))
    return hex.EncodeToString(sum[:8])
}

The format is narrow on purpose. A marker counts only as a line of its own, after trimming white space. A finding is severity | where | text, split on the first two bars, so a bar in the text stays in the text. The word none alone in a block is the one way to report nothing. If a model writes two blocks, the last complete one is read. A line whose severity is not one of the three is kept as an important finding that begins unparsed:, so a malformed line holds the round open instead of vanishing. At most MaxFindings lines are read and the rest are counted in one more finding. The parse uses Split, Cut and Fields and no regular expression, so a hostile report has no pattern to backtrack on. The hash that the repeat breaker compares is over the severity and the folded text, not the location, because a line number moves when a fix lands above it.

A review is evidence only if it ended. Three outcomes of the review step are the same thing, one important finding that fails the round and sends the fixer: the turn did not complete (cancelled, refused, an error), the reply holds no complete block (ErrNoReport), or the server cut the reply (finish_reason length, which the loop reports as Stop.Truncated). The third is refused even when a closed none block precedes the cut, because a reply that ran on past its own report did not say it was finished, and its text is not parsed. Each acceptance trial that did not pass is added as a critical finding of the driver’s own, with where set to acceptance: and the task’s name, so a clean round means the reviewer found nothing above minor and every acceptance test passed.

Why strict, when a model that writes --- and findings--- on separate lines has plainly tried to report? Because the parse fails closed, and the two ways of being wrong do not cost the same. A block the parser misses costs one more round: the fixer is sent “no findings block”, the acceptance findings still reach it, and the next review is a fresh reading. A none the parser finds where the reviewer did not write one accepts an attempt nobody reviewed. And the text the parser reads is not only the reviewer’s: the diff is in its prompt, the attempt wrote the diff, and whatever pattern a lenient parser accepts is a pattern the attempt can write into a comment and hope the reviewer quotes. The one form this parser accepts is a pair of exact lines with the last complete block winning. A near miss can be recovered without loosening that: re-ask the reviewer in its own session, once, with the parse error, so the model rewrites its block and the parser stays as it is. The loop does not do this; the third capture’s run 2 shows what the missing re-ask cost there.

A cut needs a cap that falls before the context does, so aecd.json carries max_tokens (daemon.Config.MaxTokens), which the daemon puts into every request of the turn’s agent loop, a delegate worker’s included (the compactor’s summary request has its own cap). The cap is the completion cap of one request, not the spec’s max_tokens budget of the whole loop (stopped:max_tokens, below). 0 sets none; an OpenAI-dialect route then sends no max_tokens, and an Anthropic-dialect route, whose API requires one, sends its own 1024, so a review longer than that is cut there. Without it a runaway completion is bounded only by the model’s context, and a server may go on generating it after the client that asked has cancelled; the Walkthrough’s first attempt had no cap.

The budget as a stopping rule

A loop that stops needs a reason. The reason here is derived from the one record this book has of a loop run by people and models, so the first thing to fix is what a trial is.

A trial is a fix wave: the fixes made in answer to a review, which clears when the review after them finds nothing above minor. A definition of a round as “a review and the fix that answers it” would count the clean final review as a trial. That is the wrong unit, because a clean review is not a fix wave: nothing was fixed in it. Counted anyway, it adds a trial and no success to every chapter, lowering p^\hat p from 4/15 to 4/19 and making the loops look harder than they were (exercise 1).

The model is the simplest the record can bear. Each wave clears with probability pp, independently across waves. That is not true of any real loop, and it is the stated assumption. The record (CONTEXT.md) gives the waves each chapter of Part VII needed before its review was clean: chapter 42 five (:47, “Four code reviews and five fix rounds”), chapter 43 three (:49, “then three fix rounds and two more Opus reviews”), chapter 44 four (:50, “fix rounds 1A, 1B, 2, 3”; 1A and 1B are two), chapter 45 three (:51, “fix rounds 1 to 3”). Call these ki∈{5,3,4,3}k_i \in \{5, 3, 4, 3\}. Chapter 42’s fixes 6 and 7 (:48) are not among the five: they are later fixes to a chapter already complete, and they are the subject of exercise 1.

The record is censored. Chapter 42’s fifth wave was cleared by an independent oracle and not by a review (:47), and chapters 43, 44 and 45 each end in a wave that no per-chapter review cleared, which the controller verified by reading the gate log (:49, :50) or the part-boundary reviews read (:51). Each kik_i is therefore a lower bound on the waves to a clean review, and what follows is an optimistic reading of how fast a loop clears.

For a chapter that took kk waves, the first k−1k-1 failed to clear and the last cleared, which has probability (1−p)k−1p(1-p)^{k-1}p. Over the four chapters the likelihood and its logarithm are

L(p)=∏i=1n(1−p)ki−1p,ℓ(p)=(∑iki−n)ln(1−p)+nlnp, L(p) = \prod_{i=1}^{n} (1-p)^{k_i - 1}\, p, \qquad \ell(p) = \Big(\sum_i k_i - n\Big)\ln(1-p) + n \ln p,

with n=4n = 4 and ∑iki=15\sum_i k_i = 15. Setting the derivative to zero,

ℓ′(p)=np−∑iki−n1−p=0⇒n(1−p)=p(∑iki−n)⇒p=n∑iki=415≈0.267. \ell'(p) = \frac{n}{p} - \frac{\sum_i k_i - n}{1-p} = 0 \;\Rightarrow\; n(1-p) = p\Big(\sum_i k_i - n\Big) \;\Rightarrow\; p = \frac{n}{\sum_i k_i} = \frac{4}{15} \approx 0.267.

The expected waves to clear are 1/p^=3.751/\hat p = 3.75. The geometric distribution’s median is the least mm with 1−(1−p^)m≥1/21 - (1-\hat p)^m \ge 1/2, that is (1−p^)m≤1/2(1-\hat p)^m \le 1/2, or mln(1−p^)≤ln0.5m \ln(1-\hat p) \le \ln 0.5. Dividing by ln(1−p^)\ln(1-\hat p), which is negative, reverses the inequality: m≥ln0.5/ln(1−p^)m \ge \ln 0.5 / \ln(1-\hat p), so m=⌈ln0.5/ln(1−p^)⌉=⌈2.235⌉=3m = \lceil \ln 0.5 / \ln(1 - \hat p) \rceil = \lceil 2.235 \rceil = 3. The sample median of {5,3,4,3}\{5, 3, 4, 3\} is 3.5; the book’s number is the geometric one, 3, and it says so. The probability of needing more than kk waves is (1−p^)k(1-\hat p)^k: 0.733, 0.538, 0.394 and 0.289 for k=1,…,4k = 1, \ldots, 4 (TestBudgetFromRecord prints the table; straylight).

The decision. One more wave costs cc, the tokens and seconds a round took in the capture, and clears with probability pp. It is worth taking when pV≥cpV \ge c, where VV is the value of landing now rather than handing the attempt to a person. With a constant pp this inequality is the same at every round, so a budget on rounds is a cost cap and nothing more, and that is what MaxRounds 3 is: the geometric median of the record, so that about half of the record’s chapters would have cleared inside it. Three fix rounds allow four reviews.

What makes a loop stop earlier than its cap is that pp is not constant. The part-level review sequences show findings above minor falling and then stalling: Part VII’s reviews found 16, 2, 3 and 0 critical and important findings (:45 for the cross-check, :186 for the three that followed), Part VIII’s 17, 5 and 2 (:52), Part IX’s 13, 2 and 0 (:56). The two breakers are the running evidence that pp has collapsed for this attempt.

// breakers are the two circuit breakers. Both read only the findings above
// minor, the synthetic acceptance findings included: a minor finding cannot
// hold the loop open, because the loop accepts a round that has none above
// minor. A round with none resets both.
//
//   - repeat_finding: a finding hash seen in RepeatFinding rounds running.
//     The reviews are independent sessions, so the same hash returning means
//     the fixer did not fix it (or the reviewer cannot be satisfied), and a
//     third round will not change that.
//   - no_progress: the count of findings above minor did not fall below the
//     previous round's for NoProgress rounds running. Round 1 (and the first
//     round after a clean one) has nothing to fall from and counts as the
//     first of the run; a round whose count fell ends the run, and is not
//     counted in the next one.
//
// observe is idempotent per round: asking again about the round last seen
// returns the same answer, so a resumed run that replays the ledger and then
// decides the last round again does not count it twice.
type breakers struct {
    b       Budget
    last    map[string]hashRun
    prev    int
    noProg  int
    seen    int // the last round observed
    verdict string
}

type hashRun struct{ round, run int }

func newBreakers(b Budget) *breakers {
    return &breakers{b: b.withDefaults(), last: map[string]hashRun{}}
}

// observe records round's findings and returns "" or the breaker that tripped,
// as the stop string ("stopped:repeat_finding" before "stopped:no_progress").
func (k *breakers) observe(round int, fs []Finding) (stop string) {
    if round <= k.seen {
        return k.verdict
    }
    k.seen = round
    k.verdict = ""
    n := aboveMinor(fs)
    if n == 0 {
        k.last, k.noProg, k.prev = map[string]hashRun{}, 0, 0
        return ""
    }
    tripped := false
    once := map[string]bool{}
    for _, f := range fs {
        if f.Severity == Minor || once[f.Hash] {
            continue
        }
        once[f.Hash] = true
        h := k.last[f.Hash]
        if h.round == round-1 && h.run > 0 {
            h.run++
        } else {
            h.run = 1
        }
        h.round = round
        k.last[f.Hash] = h
        if h.run >= k.b.RepeatFinding {
            tripped = true
        }
    }
    // prev is 0 at round 1 and after a clean round, so n (above 0 here) does
    // not fall below it.
    if n >= k.prev {
        k.noProg++
    } else {
        k.noProg = 0
    }
    k.prev = n
    switch {
    case tripped:
        k.verdict = "stopped:repeat_finding"
    case k.noProg >= k.b.NoProgress:
        k.verdict = "stopped:no_progress"
    }
    return k.verdict
}

// budgetStop says which budget, if any, is spent: rounds before a fix (fix
// rounds taken >= MaxRounds), tokens, and seconds. MaxRounds counts fix
// rounds after the first review, so MaxRounds 3 allows four reviews.
func budgetStop(b Budget, fixes int, beforeFix bool, tokens int, unmeasured string, elapsed time.Duration) string {
    b = b.withDefaults()
    switch {
    case unmeasured != "":
        return "stopped:max_tokens (" + unmeasured + " reported no usage)"
    case tokens >= b.MaxTokens:
        return "stopped:max_tokens"
    case elapsed >= b.MaxSeconds:
        return "stopped:max_seconds"
    case beforeFix && fixes >= b.MaxRounds:
        return "stopped:max_rounds"
    }
    return ""
}

NoProgress trips when the count above minor did not fall for two rounds running: the fix is not reaching the findings. RepeatFinding trips when the same finding, by hash over its folded text, appears in two reviews running; the reviews are independent sessions, so the same hash returning means the fixer did not fix it. A signal of this kind appears in RRSI (Further reading), where a window of rounds with no improvement redirects the search toward what has not been tried and does not stop it; here the same kind of signal ends the loop. MaxTokens and MaxSeconds are not derivable from the record, which holds no token counts of the book’s production. Their defaults, 400,000 tokens (prompt and completion over the run) and one hour of wall time, were chosen once when the budget was written, before any capture, and are stated as what they are: bounds on an attempt that is running away, not forecasts of what one costs. An attempt that runs past one is an attempt to look at, not a verdict. Both are checked between steps, from the usage a finished step reports, so a step that never finishes is not stopped by them; that is what the per-request cap above is for. The Walkthrough reads them against all three captures. A budget stop is stopped:, a verdict of its own: the loop ended with findings left.

Two ledgers

The driver’s ledger has five kinds of line.

// Event is one line of the round ledger, ledger.jsonl in the run
// directory, in chapter 40's discipline: validated against memory,
// appended, fsynced, then committed to memory; a torn last line is cut at
// open and counted. The kinds: "run" (the spec's hash, the repository, the
// branch, the budget), "step_begin" (round, step, session id), "step_end"
// (round, step, the daemon's TurnResult as JSON, the commit hash),
// "report" (round, the findings and the mutation report), "stop" (the
// verdict). A step that has a begin and no end is in flight; Resume
// re-sends it, and the daemon's own ledger decides what the half-done turn
// did (chapter 40: idempotent calls replay, the rest follow the policy).
type Event struct {
    Seq     int       `json:"seq"`
    At      time.Time `json:"at"`
    Kind    string    `json:"kind"`
    Round   int       `json:"round,omitempty"`
    Step    Step      `json:"step,omitempty"`
    Session string    `json:"session,omitempty"`
    Commit  string    `json:"commit,omitempty"`
    Spec    string    `json:"spec,omitempty"`
    Result  []byte    `json:"result,omitempty"` // daemon.TurnResult, JSON
    Report  []byte    `json:"report,omitempty"` // Round's findings and mutants, JSON
    Stop    string    `json:"stop,omitempty"`
}

// Ledger is the file. It is the Scratchpad's shape (chapter 31: a file
// outside the context, read back as data) with chapter 40's durability.
type Ledger struct {
    Path      string
    Dropped   int // bytes of a torn last line cut at open
    Truncated bool
    events    []Event
    f         *os.File
    lock      *os.File
    size      int64
    broken    error // set when a failed write could not be cut back: the ledger refuses every later append
}

// OpenLedger reads or creates the file.
func OpenLedger(path string) (*Ledger, error) { return openLedger(path) }

// Append validates e against the events so far (a step_end without its
// begin, a second run line, a seq out of order are refused), writes it and
// fsyncs before returning.
func (l *Ledger) Append(e Event) error { return l.append(e) }

// Events returns every event in order.
func (l *Ledger) Events() []Event { return append([]Event(nil), l.events...) }

// InFlight returns the step that began and did not end, if any.
func (l *Ledger) InFlight() (Event, bool) {
    for i := len(l.events) - 1; i >= 0; i-- {
        switch l.events[i].Kind {
        case "step_end":
            return Event{}, false
        case "step_begin":
            return l.events[i], true
        }
    }
    return Event{}, false
}

The order of durable writes is the design. The step_begin is appended before the turn is sent. A step’s own files (the acceptance trials, the mutation report, the reviewer’s text and findings) are written to a temporary name and renamed into place before its step_end; the report is appended after the review’s step_end, from the files. So whichever line is last tells Resume what is on disk.

// drive is the loop. Every pass replays the ledger, finds the last event and
// does what follows from it, so a live run and a resumed one take the same
// branches; a step in flight is re-sent first. The branch table:
//
//    open step_begin            re-send it (the daemon's rule has run at open)
//    run                        implement
//    step_end implement | fix   rejected if the turn failed or the tree is
//                               tampered with; else evaluate the commit, review
//    step_end review            append the report from the round's files
//    report                     accepted | stop | fix
//    stop                       return
func (d *driver) drive(ctx context.Context) (Result, error) {
    for {
        if err := ctx.Err(); err != nil {
            return Result{}, err
        }
        st, err := replay(d.led.Events())
        if err != nil {
            return Result{}, err
        }
        if st.stop != "" {
            d.closeSession(ctx, d.workID())
            st.info.Exclude = excludeFor(d.o.Dir, st.info.Exclude)
            return st.result(d.now()), nil
        }
        err = d.advance(ctx, st)
        var rj *rejectErr
        switch {
        case errors.As(err, &rj):
            if err := d.reject(rj.reason); err != nil {
                return Result{}, err
            }
        case err != nil:
            return Result{}, err
        }
    }
}

// reject appends the stop line of a rejected run.
func (d *driver) reject(reason string) error {
    body, err := json.Marshal(map[string]string{"reason": reason})
    if err != nil {
        return err
    }
    return d.append(Event{Kind: KindStop, Stop: "rejected", Report: body})
}

// budgetCheck appends a stop when a budget is spent before a step.
func (d *driver) budgetCheck(st *replayed, beforeFix bool) (stopped bool, err error) {
    reason := budgetStop(st.info.Budget, st.fixes, beforeFix, st.tokens, st.unmeasured, d.now().Sub(st.began))
    if reason == "" {
        return false, nil
    }
    return true, d.append(Event{Kind: KindStop, Stop: reason})
}

func (d *driver) advance(ctx context.Context, st *replayed) error {
    if st.open != nil {
        return d.resend(ctx, st)
    }
    last := st.last
    switch {
    case last.Kind == KindRun:
        if stopped, err := d.budgetCheck(st, false); stopped || err != nil {
            return err
        }
        return d.implement(ctx, st, nil, "")
    case last.Kind == KindStepEnd && (last.Step == Implement || last.Step == Fix):
        // The rejections come before the budget, in a live run and a resumed
        // one alike: a turn that did not complete, then a worktree that fails
        // the tamper check (Changes runs it, as Commit did).
        if reason := st.pendingReject(); reason != "" {
            return &rejectErr{reason: reason}
        }
        diff, err := d.changes(ctx, st)
        if err != nil {
            return err
        }
        if stopped, err := d.budgetCheck(st, false); stopped || err != nil {
            return err
        }
        n := last.Round + 1
        if err := d.evaluate(ctx, st, n, diff); err != nil {
            return err
        }
        return d.review(ctx, st, n, nil, "")
    case last.Kind == KindStepEnd && last.Step == Review:
        return d.report(st, last.Round)
    case last.Kind == KindReport:
        return d.afterReport(ctx, st, last.Round)
    }
    return fmt.Errorf("%w: no branch for %s after %s %s", ErrLedgerCorrupt, "the ledger", last.Kind, stepName(last.Round, last.Step))
}

The daemon has a ledger too (chapter 40), and the two are read together. When the driver dies in the middle of a send, the connection drops and the daemon cancels the turn as it would for any caller’s cancel; the session file then holds the user message, the assistant’s call and a cancelled tool result, Resolved is empty, and a second send is accepted at once. When the daemon dies in the middle of a turn, chapter 40’s rule decides each call in flight, and Resolved says what it did. In both cases the driver re-sends the step rather than re-running it. The model’s history is the daemon’s, so the re-sent prompt says what happened: the step was interrupted, continue from the session’s own history, here is what was in flight. Chapter 40’s idempotence analysis says which calls replay. A cancelled turn also ends the gate’s model check in flight: the daemon passes the turn’s context to chapter 47’s gate through Loop.PolicyContext, added for this loop; a delegate worker’s check still runs under the gate’s background bound (chapter 45).

One gap is inherent. A turn the crash cut off has its tokens in the daemon’s trace and not in the ledger, because the ledger records a turn’s usage at its step_end. After a crash the run’s token total is low by that turn. The comment on Result.Tokens says so; nothing in a run’s result marks a particular total as short.

The learn step and the placebo arms

Chapter 36 promised that an agent could write a skill from what it did. After an accepted attempt the driver can send one more turn to the work session, in which the model writes a skill through skill_write; the client approver allows that tool in this step and no other. Nothing the model writes is trusted.

// learnPrompt asks for one skill that would have shortened this run for the
// next spec of its kind.
const learnPrompt = `The change you made in this session was reviewed and accepted. Write one skill, through skill_write, that would have shortened this run for the next spec of this kind: what to check before writing, which acceptance tests to run, the one mistake the review caught. Name the skill after the practice, not the task. The skill's body must name no identifier of this repository's change: no function, file or package from it. Write the one skill and answer in one line.`

// Learn is the step after an accepted attempt: one more primary turn in the
// work session, under the client approver that allows skill_write for this
// step alone. It refuses a run whose ledger does not end in "stop accepted",
// and a learn turn that did not complete (refused, error, cancelled), whatever
// it wrote before it stopped.
//
// Model-written text never reaches the live skills directory unvetted. The
// daemon is configured with a staging directory as its skills directory; Learn
// empties it, copies the live directory into it, and runs the turn. Afterwards
// the staged set must differ from the live set by exactly one new skill
// directory (no existing file modified or deleted, no new file anywhere else),
// and vet, the caller's check, must report nothing over a private set (0700,
// beside the live directory): the live skills as they are plus the one new
// skill copied once from the stage, which is never read again. Only if the
// live directory is unchanged since it was copied is the new skill's private
// copy renamed into it, and learn.json records its hash. On any
// refusal or error the staging directory is emptied and the live directory is
// as it was.

A learned skill needs a measurement, because a skill that reads well and a skill that helps are different claims. Zhang et al.’s study of rule files for coding agents (arXiv 2604.11088) found that random rules improved a coding agent’s task performance as much as expert-curated ones, which points to a context-priming effect and not to what the rules say. A skill’s gain over no skill is therefore not evidence about its content; the control is a placebo of the same shape. The memory-extraction paper “Self-Evolving LLM Memory Extraction Across Heterogeneous Tasks” (arXiv 2604.11610) reports that no single static extraction prompt dominates across task categories and that existing self-evolving prompt optimisation, built for homogeneous task distributions, degrades when the training tasks are heterogeneous. It is about memory extraction, not coding agents, and it is the reason the arms include one with no skill at all. aec-work placebo builds three arms (the skill, a placebo skill of the same length and shape with unrelated content, and none), prints the three aecd eval command lines and the rule that is registered before the run, and -compare reads the three trial files through chapter 38’s statistics. The live run was not run for this book: the design is built and tested on the rig, and that is all the chapter claims for it.

What a sandboxed grade cannot see

Every graded go test ./... compiles and runs the attempt’s own code, and that fixes a limit the loop does not escape. The sandbox keeps an attempt from escaping. It does not keep the attempt from lying about its own tests. A grade computed by running untrusted code is evidence against honest mistakes, and only that. The defences against a dishonest attempt are not in the grader: the acceptance test file pinned by hash, so the attempt cannot rewrite what the tests assert; the reviewer reading a diff that shows everything that shaped the grade, which is why the grade is taken on the commit’s export, so that nothing the attempt left untracked can have shaped it; mutation testing, which asks the tests whether they can see bugs the attempt did not choose; and the person who reads the result. The approver is shape policy, bwrap the containment, and neither claims more.

The Walkthrough measures one case, because the claim is easy to read as a platitude: a .config/go/env file written by the attempt, holding GOFLAGS=-run=^$, makes go test select no test, and the grade on the commit’s export is what defeats that file.

What this chapter does not claim

Three captures of one spec with two models on one host: nothing here is a rate, and nothing here says what another run of the same spec would print. The reviewer’s independence is a design the chapter argues for and does not measure, and no capture demonstrates it live. The second model reported on none of the six reviews it was given: the two of the first attempt were cancelled, the four of the second were cut at the completion cap. The 35b reviewed its own model’s work nine times. In the first attempt’s run 2 it reported twice (two critical findings on an empty diff, then one minor on an equivalent mutant) and was cancelled once. In the third capture it reported once, wrote one block with a mangled marker, ended one review with no text, and was cut at the cap three times. That is one model reading its own attempts. What the rig shows instead is the plumbing the claim rests on: the review session’s model calls carry the role aux and the work session’s primary. No live run reached accepted; the rig’s runs, whose model is a script, do. The budget’s constants are a reading of a record that is censored. The learned skill and its placebo arms are built and tested on the rig and were not run live. The attempts in the lab are scripts, and the captures’ reviewer text is a fixture.

What the next chapters take

Chapter 54 takes Result (the branch, its head, the rounds and the sessions) as the attempt its gates read; whatever lands or removes the worktree builds its Git with GitFor, for the reason given under the loop as sessions. Chapter 55 reads the record quoted above, and the approval counts in the audit log the third capture left in its run directory, the richest of the three. And if a reviewer’s finding were that the spec is ambiguous, what the fixer would need is chapter 52’s ruling, which the loop does not write.

Walkthrough

Two kinds of run follow, all on straylight on 2026-11-09 UTC, from the flake’s dev shell. The first is the lab’s rig: a real aecd whose model is a script, so the loop’s mechanism can be watched reaching each of its verdicts. The second is three live captures of chapter 52’s median.md, each two runs through one daemon with real models, kept because what they found is why the loop looks as it does. Their files are in go/labs/ch53/testdata/capture, capture2 and capture3; each README.txt says what was rewritten in them (paths, the times in the ledgers, nothing else). Nothing re-runs any of them.

An accepted run, on the rig

TestLoopOnRig runs the loop over the fixture with the script testdata/scripts/loop.json answering every model call. Its implementer writes a Median that averages the middle pair in int; its first review reports that and one minor point; its fixer rewrites the average in float64; its second review is clean. Run alone (go test -count=1 -v -run '^TestLoopOnRig$' ./labs/ch53, go 1.27.0, 2026-11-09 19:14:46Z), it printed this, from which the runner’s === RUN lines and the first four log lines (the cache warm-up, the session’s open, the run line and the worktree’s temporary path) are cut:

...
    rig_test.go:283: ledger: step_begin 0/implement
    rig_test.go:283: turn 0/implement: final
    rig_test.go:283: ledger: step_end 0/implement
    rig_test.go:283: ledger: step_begin 1/review
    rig_test.go:283: turn 1/review: final
    rig_test.go:283: ledger: step_end 1/review
    rig_test.go:283: ledger: report 1
    rig_test.go:283: ledger: step_begin 1/fix
    rig_test.go:283: turn 1/fix: final
    rig_test.go:283: ledger: step_end 1/fix
    rig_test.go:283: ledger: step_begin 2/review
    rig_test.go:283: turn 2/review: final
    rig_test.go:283: ledger: step_end 2/review
    rig_test.go:283: ledger: report 2
    rig_test.go:283: ledger: stop accepted
    loop_test.go:44: loop.json to a verdict in 7.0 s
    loop_test.go:100: round 2: 4 mutants, 3 killed, 1 survived, 4.6 s
--- PASS: TestLoopOnRig (30.97s)

The test’s 30.97 s include 23.5 s of warming a Go build cache under bwrap, which every test of the package then shares. The two reviews, as the script’s reviewer returns them:

reviewed
---findings---
important | calc/median.go:18 | even n: the average of the two middle values is computed in int; use float64
minor | cmd/calc/main.go | the usage line names only mean
---end---
done
---findings---
none
---end---

Round 1 holds three findings: the reviewer’s two and one critical of the driver’s own, acceptance:median/vet-test, because the int average fails the even-length test. With a failing acceptance test the unmutated tree fails its own grade, so round 1’s mutation pass reports that and plants nothing; round 2’s planted four (the rig caps MaxMutants at 4) and killed three. The second review’s none parses to no findings, the acceptance tests pass, nothing is above minor, and the driver appends stop accepted: twelve ledger lines, the begin and end of each of four steps, two reports, the run line and the stop. The Result that Run returned is the one the listing above declares, and the test checks it field by field (loop_test.go): verdict accepted; two rounds, the first with three findings and Fixed true, the second with none; a Head on the run’s Branch, whose worktree holds the fixed median.go; Sessions the work session and the two review sessions; Tokens above zero. Status, reading the ledger with no daemon, returns the same Result, field for field. That equality is what makes the ledger the run’s record: whatever chapter 54 needs from a finished run, it reads without the daemon.

Three live captures

Each capture ran two runs of median.md through one aecd configured as the mechanism describes: the roles primary and aux, "sandbox": "local" with the limits of spec.SandboxLimits(), a policy block with three deny rules (curl, wget, git push), the audit log in the state directory, and max_turns 12. aecd status -tools printed the same line in all three:

tools: 7: execute_code read_file scratch_read scratch_write search_files terminal write_file

The sandbox is present, so the driver could grade, and -approve client was permitted. The implementer and the fixer were ornith-1.5-35b-a3b (“the 35b”) on straylight’s router; the reviewer was gemma4-26b-a4b-abliterated (“gemma”, a different family) in the first attempt’s run 1 and in both runs of the second, and the 35b otherwise. Every /v1/models reading was saved raw. In the first attempt only the 35b read loaded, every other model on the router unloaded; gemma was loaded by one POST /models/load, answered {"success":true}, and read loaded on the sixth of a background wait’s five-second re-reads, thirty seconds in. In the second both read sleeping and were woken by one minimal completion each (max_tokens 1, the status re-read immediately before), at 16:57:25Z and 16:57:47Z. In the third both read loaded and nothing was woken (models-before.txt):

2026-11-09 18:02:22Z /v1/models 200 16764 bytes -> v1-models.json
   gemma4-26b-a4b-abliterated loaded
   ornith-1.5-35b-a3b loaded
               total        used        free      shared  buff/cache   available
Mem:             125          68          13           0          43          56

Memory available before each first request was 58, 62 and 56 GB of 125, above the 8 GB each capture required; after each, both models still read loaded, with 88, 68 and 82 GB used (models-after.txt). Nothing was unloaded or evicted, gemma stays loaded, and nothing was sent to dixie. Each capture printed its bound before its first request (bound.txt); the third’s:

hard bound (the daemon's max_turns 12 per step): run 1 <= 8 steps x 12 = 96, run 2 <= 96 + 12 for the re-sent step = 108; at most 204 completions on straylight's router, ALL to ornith-1.5-35b-a3b (the reviewer role aux has the 35b as its chain: one model in both roles); no wake needed (the 35b reads loaded); nothing to gemma4-26b-a4b-abliterated, which stays loaded; nothing to dixie; nothing unloaded or evicted; expected (the index's reading): about 116; every request is capped at max_tokens 8192

The first two bound the reviewer’s model at 96 of the 204 and the second adds its two wakes. Only the hard numbers are a bound: the daemon caps a turn at 12 model calls, and nothing caps a review at 4 or a fix at 8, so the 116 is an expectation. The three captures, side by side (status.txt, status-resumed.txt, ledger-lines.txt, oversight.txt, audit-verify.txt, and the model calls from calls.txt, or for the first, which has none, its README.txt):

first attempt second attempt third capture
built from 08e098c 82345a9 82345a9
reviewer’s model gemma, then the 35b gemma the 35b
per-request cap, run 1 and run 2 none 8,192 and 16,384 8,192 and 16,384
verdicts repeat_finding, repeat_finding repeat_finding, repeat_finding repeat_finding, no_progress
reviews (of them parsed) 2 (0), 3 (2) 2 (0), 2 (0) 2 (0), 4 (1)
fix steps 1, 2 1, 1 1, 3
tokens in the ledger 74,308; 184,414 84,644; 152,767 87,925; 326,381
seconds 2,824.1; 4,414.6 347.6; 642.4 413.3; 1,728.6
ledger lines 12, 17 12, 12 12, 22
model calls (completed, cancelled) 61 (57, 4) 35 (34, 1) 76 (75, 1)
of them to gemma 2 5, and one wake none
approvals asked of the client (allowed) 21 (0) 18 (2) 32 (1)
aecd audit verify -traces ok, 11 traces ok, 9 traces ok, 13 traces

Every verdict above is a breaker’s. No live run reached accepted. Where the two runs of a capture agree, as the second’s do, it is a property of those runs and not of the loop: the model samples, so two live runs of one spec need not agree, and the first attempt’s agreed on the name of the stop and nothing else.

Read against the budget’s defaults, the largest run on the loop as fixed, the third capture’s run 2, used 326,381 tokens in 1,728.6 s, 82 and 48 per cent of 400,000 and 3,600. It stopped on no_progress at its fourth report, the same moment at which stopped:max_rounds was due: its three fix steps had used MaxRounds, and afterReport consults the breakers before the budget. The 73,619 tokens it had left were fewer than its third review alone had cost (77,774), so one more round of that size would have crossed the token cap too. The first attempt’s run 2 ran 4,414.6 s, past the hour, because without a completion cap its three reviews took 1,003, 1,438 and 1,473 s. The budget is checked between steps, the run crossed the hour inside its third review, and at that review’s report repeat_finding fired with max_seconds due behind it. Its 184,414 tokens are a floor, since the fix turn the kill cut recorded none. No run was stopped by a budget, and in the two longest a budget stop was due at the report where a breaker fired: the defaults bounded runaways, which is what they are for, and are not a forecast to tune against.

In each capture aecd audit verify -traces printed ok for the head and for every trace it read, and its last line had no edited, missing, unrecorded or unreadable trace (the third’s: traces: ok 13 edited 0 missing 0 unrecorded 0 unreadable 0). aecd shutdown closed the log, and no aecd process and no aecd.sock remained. The audit directories stay in the run directories.

The first attempt: what it found

Built from 08e098c, the first attempt found three defects in the loop.

  1. A runaway reviewer and a missing cap. The daemon sent no max_tokens. Gemma’s first review generated 96,844 tokens without ending, and the router went on generating after the operator cancelled it.
  2. The shape policy refused everything the model typed. The prompt said to run go -C repo test ./..., the model typed cd repo && go vet ./... && go test ./..., and all 21 approvals asked of the client were denied.
  3. A relative -dir. Resume used the directory as given where Run made it absolute, and the first grade after a resume failed in the sandbox before any Go ran.

Run 1’s command line was the second attempt’s (below) with the pattern then in force, go -C repo (build|vet|test)( [A-Za-z0-9_./=-]+)*. The 35b’s implement turn (aec-trace view of its trace, view-implement.txt) ran 45.6 s and stopped on max_turns: 12 model calls, 15 tool calls, 57,322 prompt tokens (50,686 of them cached) and 2,533 completion tokens. It wrote calc/calc.go and cmd/calc/main.go, and asked the terminal for six commands and execute_code for one. All seven were denied. The one it asked for most often was

cd repo && go vet ./... && go test ./...

The && is a byte the approver refuses before any pattern is read, and cd repo is not go -C repo, so the model never ran its tests. The attempt was sound all the same: its Median clones the slice, sorts it and averages the middle pair for an even length. Both acceptance commands passed on the export of its commit (trials.jsonl), and the mutation pass over the two changed files planted 40 mutants in 41.9 s and killed 28, K/T=0.70K/T = 0.70, with a Wilson interval at 95 per cent of 0.55 to 0.82 over this operator class. The twelve survivors are the twelve of the report shown under the third capture, with the lines of cmd/calc/main.go one higher.

Then gemma’s review did not end. The daemon set no max_tokens (the window’s reserve holds tokens back in the context budget and is not a request field), so nothing stopped a completion before the context did. The operator cancelled the turn with aecd cancel after 1,733 s, when the router counted 96,844 generated tokens (operator-cancels.txt). The round’s finding is the one a review that did not complete gets (rounds/1/findings.json, in the findings format):

important | report | the review did not complete: cancelled: context canceled

The fixer was sent it, ran 41.2 s and committed nothing, since there was nothing to change. The second review was cancelled after 883 s with the same finding, the same hash, and repeat_finding stopped the run. The breaker did its job on a case nobody designed it for: it cannot tell a reviewer that is stuck from a fixer that cannot fix, and in both it says that a third round would not change the result. The run’s tokens 74308 (status.txt) is the 59,855 of the implement turn and the 14,453 of the fix step, with nothing for the two reviews, which spent the most: a cancelled turn’s tokens are not in the ledger, which is the token gap of the ledgers section seen without a crash. The router’s log, read afterwards, shows the cancels did not stop the generation. The first review’s slot went on to 131,071 tokens and the second’s to 27,116, and both were released at 07:34 UTC, about 50 and 33 minutes after the cancels (operator-cancels.txt). Cancelling a request does not cancel its slot, and the daemon has no way to say it should.

Run 2 sent its reviews to the 35b (-reviewer primary), a decision taken after run 1 ended and printed as a second bound (bound2.txt). Its implementer wrote nothing: 12 turns, 124.9 s, five refused terminal commands, one of them go -C repo vet ./... && go -C repo test ./..., the prompt’s form with one && too many. The diff was empty, the mutation pass said so ("detail":"no Go file changed"), and the acceptance trials failed honestly. The reviewer read all of that and reported, in 8 turns and 1,003 s (rounds-resumed/1/review.txt, verbatim):

---findings---
critical | cmd/calc | vet-test: build of fixture/calc fails (go vet ./... cannot compile; got status 1, want 0) — median implementation absent
critical | cmd/calc | cli: "unknown subcommand median" — median subcommand not registered in the calc command
---end---

Its prose before the block says “the workspace contains no readable files”, which is the review session’s empty workspace; it worked from the diff and the reports, as designed. The driver’s kill came at the fix step (below), and the re-sent fix wrote the implementation in 8 turns and 212.7 s (commit 43adeeb8). Then the third defect. resume had been given -dir run2, and the grade after it failed with bwrap: Can't find source path run2/build/tree: No such file or directory, so rounds 2 and 3 hold that failure as two acceptance findings. The 35b’s review of round 2 (1,438 s) did not take them for the code’s: its block is one minor finding about an equivalent mutant, and its prose calls the failure “a sandbox/harness path fault, not a defect in the code”. The driver put the two critical lines in all the same, the same two lines came back in round 3, and repeat_finding stopped the run after a third review that the operator cancelled at 1,473 s. Resume now makes the directory absolute; TestResumeRelativeDir runs the rig with a relative directory and failed before that one-line fix.

The second attempt: a reasoning reviewer at two caps

Built from 82345a9, the loop with the three defects fixed: every request of a turn carries a max_tokens cap, a cut review is a failed review, the worktree is the session’s workspace so the model’s plain go test ./... runs on the module, and Resume makes its directory absolute. Run 1’s command line:

aec-work run -spec median.md -socket state/aecd.sock -repo fixture -dir run1 -sandbox local \
  -approve client -allow 'go (build|vet|test)( [A-Za-z0-9_./=-]+)*' -v

The cap was 8192, with each provider’s window reserve raised from 2048 to match. The window’s size is 32768 and its reserve is the part held back for the completion, so a reserve below the cap would let a prompt fill the room a completion at the cap needs. 8192 was chosen from the first attempt, where the 35b’s first finished review spent 8,697 completion tokens over eight calls; one request of 8192 looked ample. For a reasoning model the cap is the number that decides whether the review may think, and it was not ample for gemma. Run 2 therefore ran under max_tokens 16384 with the reserve at 16384 and the window unchanged, which left 16384 tokens for a prompt (the largest implement prompt was 7,799 tokens, and the re-sent fix turn of run 2 averaged 8,344 per call); the daemon was restarted between the runs.

Run 1’s implement turn (view-implement.txt) took 42.9 s and asked the terminal five times and execute_code once, and the client denied all six: cd "$(pwd)" && pwd && git branch && ls -la, pwd && git branch && ls -la, go vet ./... && go test ./... twice, and go version. The first four hold && (the first also $( and quotes), and go version is not build, vet or test. The prompt had given it the plain commands, and it chained them. The attempt was nevertheless sound: Median copies the slice, sorts it, takes sorted[mid] for an odd length and the mean of the two middle values for an even one. Both acceptance commands passed, and the mutation pass killed 28 of 40, the same twelve survivors by id as the third capture’s report below.

Gemma’s review was a single call that used its 8,192 completion tokens in 94.9 s and ended with finish_reason length. Its text was empty: the whole completion was reasoning_content, a reasoning model working through the mutation report mutant by mutant and not yet at its answer. The round’s one finding (rounds/1/findings.json):

important | report | the review was cut off at the completion cap (finish_reason length): it is not evidence

The fixer, sent it, answered in one call that the review “was cut off at the completion cap and is not evidence”, that both acceptance tests pass, and that “no changes are needed”. The second review was cut the same way (96.0 s), the finding had the same hash, and repeat_finding stopped the run. Against the first attempt, the cap stopped the same model after 94.9 and 96.0 s where the operator had cancelled it after 1,733 and 883 s, and the reviews’ tokens are in the ledger (tokens 84644 includes 2 × (2,197 + 8,192)) where the cancelled turns recorded none.

Run 2’s implementer (view-implement-2.txt, 75.7 s, 12 turns) was refused go vet ./... && echo "VET OK" && go test ./... and execute_code, then typed go vet ./... and go test ./... on their own, and the client allowed both, the first commands any capture ran. They ran in the sandbox, and the second printed

exit 0
ok      fixture/calc    0.001s
?       fixture/cmd/calc    [no test files]

Seven asks of the turn were denied in all: four && chains (two of them behind cd "$(pwd)"), execute_code, and go run ./cmd/calc median 3 1 2 twice, whose verb is not on the list. Its review was cut at 16,384 tokens after 195.5 s, with empty text. The driver was killed at the fix step and resumed (below); the re-sent fix, 4 calls and 17.4 s, answered that “both acceptance checks already pass” and changed nothing, so the step has no commit. The second review made one call of 2,563 completion tokens that ended in a refused terminal call and a second cut at 16,384, and repeat_finding stopped the run. The reasoning column of aec-trace cost reads 0 for every row, including these reviews whose completion was all reasoning: the server reports completion_tokens, and the loop has no separate count for the share that was reasoning. One review at the cap cost more completion tokens than the implementer’s whole turn, 16,384 against 2,983. Whether gemma finishes under some larger cap, or with a prompt that asks for the findings block first, was not tried.

The third capture: one model in both roles

Kyle’s call after the second attempt was a third run with the 35b in both roles. routes.json has one provider, and the roles primary and aux both have it as their chain; the driver, the loop, the approver and the budget are the second attempt’s, from the same commit. A finding here is the model reading its own work, with the spec, the diff and the two reports in front of it, in a session that has none of the implementer’s history. It does not show that another model reads differently, and it was not designed to. What the rig shows for independence is the plumbing it rests on: TestReviewerRoleIsAux checks that the review session’s model calls carry the role aux and the work session’s primary, so a route that sends aux elsewhere sends only the reviews there. This capture’s traces agree (cost.txt):

role     lines  prompt  cached  completion  reasoning  amount    unpriced
aux      38     108381  94436   108460      0          0.000000  0
primary  37     183130  148506  14335       0          0.000000  0
total 0.000000 USD (75 lines, 0 unpriced)

The reviews’ completion tokens were 7.6 times the implement and fix turns’, which is the review being the expensive step again.

Run 1, under 8192, went as the second attempt’s had. The implement turn (view-implement-a2938ca9.txt, 41.1 s, 12 model calls) had five asks denied and committed an attempt that passed both acceptance commands, with the same 28 of 40 killed. Its review was six calls and 126.0 s: two terminal commands denied, a read_file of calc/calc.go that found nothing in the review’s empty workspace, and a last call that generated 8,192 tokens in 117.8 s and ended with finish_reason length. The fixer changed nothing, the second review was cut on its last call too (137.7 s), and repeat_finding stopped the run. A model that reviews its own work at 8,192 tokens per request, with the instructions the driver gives it, returned no text before the cap in both rounds, as gemma had at 8,192 and at 16,384, so it is not one model’s quirk.

Run 2, under 16384, is the one the capture was for. The implement turn (view-implement-8b1355df.txt, 28.6 s, 12 turns) had seven asks denied and committed code that did not compile: sort.Float64s without the sort import. Both acceptance commands failed on the export of that commit, so round 1 held two critical findings of the driver’s own. The reviewer, in 9 calls and 117.0 s, found the cause, and the missing subcommand besides. Its closing lines (rounds-resumed/1/review.txt):

---

findings---
critical | calc/calc.go:38 | `sort.Float64s` is used but the `sort` package is never imported (the diff adds no import), so the `calc` package does not compile — this is why vet-test, cli, and mutation testing all fail with build/exit errors
important | cmd/calc/ | the diff never adds the `median` subcommand the spec requires ("Add a `median` subcommand to the `calc` command"); without it the cli acceptance (`calc median 3 1 2` → `2`) cannot pass
---end---

The opening marker is not ---findings---: the model wrote ---, a blank line and findings---. The parser found no complete block, the review was not evidence, and the driver added no findings block: the review is not evidence as an important finding of its own. The report was correct, and this is the near miss the report section argues about. Here it cost nothing measurable. The fixer was sent the driver’s finding and the two acceptance failures, both reading # fixture/calc, a compile error that says nothing of the subcommand; it added the import and the subcommand regardless (“The median subcommand is wired into the CLI in cmd/calc/main.go”). Parsed, the report would have made round 1’s count above minor four instead of three; round 2’s count was 1 either way, a fall, so no breaker would have read differently. A re-ask of the reviewer in its own session would have bought the same outcome for one more call. In a run whose acceptance tests did not fail on what the reviewer saw, the miss would have cost a round.

The driver was killed at the fix step and resumed (below). The re-sent fix ran 6 calls and 29.0 s and committed 48d6c676, and from then on the attempt compiled and both acceptance commands passed in every round. The run’s end (status-resumed.txt):

verdict stopped:no_progress
branch median-8b1355df head 7eba079675b6f9d9466ce45182d283fb0b3094b7
worktree state/sessions/median-8b1355df-work/workspace
round 1 findings 3 (above minor 3) mutants 0 killed 0 fixed true 
round 2 findings 2 (above minor 1) mutants 40 killed 28 fixed true 
round 3 findings 1 (above minor 1) mutants 40 killed 32 fixed true 
round 4 findings 1 (above minor 1) mutants 40 killed 32 fixed false stopped:no_progress
tokens 326381 seconds 1728.6 sessions median-8b1355df-work,median-8b1355df-review-1,median-8b1355df-review-2,median-8b1355df-review-3,median-8b1355df-review-4

Round 2’s reviewer read this mutation report, rendered from rounds-resumed/2/mutants.json as MutationReport.Text writes it:

<<<mutation
mutants 40, killed 28, survived 12, timeouts 0, 38.2 s
2b536cb1fcb1 calc/calc.go:25:10 const: 0 -> 1
ab828e9d9dfd calc/calc.go:39:10 const: 0 -> 1
742a225b719c cmd/calc/main.go:23:15 rel: < -> <=
d9b923135c38 cmd/calc/main.go:25:10 ret: 2 -> 0
47560bbf6f66 cmd/calc/main.go:27:36 arith: - -> +
63566d898b6e cmd/calc/main.go:27:37 const: 1 -> 0
8950400fe065 cmd/calc/main.go:32:11 ret: 2 -> 0
0cc9491a3a0a cmd/calc/main.go:46:64 const: 0 -> 1
31d422630580 cmd/calc/main.go:47:10 ret: 2 -> 0
e53b08051906 cmd/calc/main.go:51:10 const: 1 -> 0
3294b2b9f85f cmd/calc/main.go:53:42 const: -1 -> 0
d03c14f59a17 cmd/calc/main.go:54:9 const: 0 -> 1
mutation>>>

The two in calc.go are the 0 -> 1 on the value returned beside ErrEmpty, in Mean and in Median, which no caller reads once it has the error. The other ten are the exit statuses and argument handling of the command, which the acceptance tests reach with a single invocation. The review (rounds-resumed/2/review.txt, five calls, 263.5 s) is the one real report of the capture:

---findings---
important | cmd/calc/main.go:25 | spec requires `median` with no numbers to exit 2 "as mean does", but the CLI acceptance only runs `median 3 1 2`, so the exit-2 branch is untested and the `ret: 2 -> 0` mutant survives
minor | calc/calc.go:39 | the `0` in the empty-input return is masked by the non-nil `ErrEmpty`, so the `0 -> 1` mutant is equivalent (no input can distinguish it from the original)
---end---

It sorted survivors the way the evidence section asks: one a gap in the tests, with the line, one equivalent, with the reason. The fixer wrote tests (5 calls, 159.5 s, commit 7eba0796), and round 3’s pass killed 32 of 40: the three ret: 2 -> 0 and the 0 -> 1 at main.go:54:9 no longer survive. The kill count is the evidence that the fix did something.

Then the loop did not finish. The third review ended with no text at all (9 model calls, 687.8 s, 47,211 completion tokens), so its finding was no findings block; the fixer was sent it and changed nothing (11.4 s). The fourth review (3 model calls, 257.2 s) returned 24,536 bytes of working-out, a walk through the mutants that stops mid-sentence at the cap. The count above minor was 1 in rounds 2, 3 and 4: it fell from 3 to 1 and then did not fall for two rounds running, which is no_progress. The fix was not reaching the findings, because the findings were not about the code. The verdict names the right condition for the wrong reason, as repeat_finding did in the earlier captures, and it stopped a loop that was spending 117 to 688 seconds a review on reviews that did not report. The approver allowed one command in this capture, go test ./... in the second fix step, which printed exit 0 and ok fixture/calc; in the other 31 asks the model chained commands with &&, piped to head and began with cd "$(git rev-parse --show-toplevel)", and the shape policy refused each.

The kill and the resume

Every capture’s run 2 ran under the same script, which reads the driver’s stderr line by line and sends SIGKILL three seconds after the line ledger: step_begin 1/fix. The line is logged before the ledger append and the send, so the three seconds let both happen, and the kill lands with the fixer’s turn in flight. The third’s (killed.txt, status-killed.txt, sessions-killed.txt):

SIGKILL to the driver at 2026-11-09 18:13:25.332154Z, 3 s after the line: ledger: step_begin 1/fix
verdict in flight
in flight 1/fix
branch median-8b1355df head 90021e68eb0c75c7a2d1dd7f62914ead63fe210c
worktree state/sessions/median-8b1355df-work/workspace
round 1 findings 3 (above minor 3) mutants 0 killed 0 fixed false 
tokens 82925 seconds 188.9 sessions median-8b1355df-work,median-8b1355df-review-1
median-8b1355df-work turns=1 messages=28 busy=false

The daemon logged turn median-8b1355df-work/2: cancelled (daemon-cancel-lines.txt), and the session is not busy, so the next send is accepted at once. tokens 82925 is the implement turn’s 54,020 and the review’s 28,905, with nothing for the fixer’s turn the kill cut: the token gap after a crash, as the ledger shows it. Then aec-work resume -spec median.md -dir run2 -socket state/aecd.sock -v, with a relative directory, which logged resume: step 1/fix in flight and sent the step again behind this preamble, the second user message of the work session in all three captures:

<<<resume
This step was interrupted and is being sent again. Continue from this session's own history; do not start over and do not repeat work that is already done.
The turn was cancelled and nothing was in flight.
resume>>>

Resolved was empty, as it is when the driver dies and the daemon lives: the daemon cancelled the turn itself, and no call was left for its resume rule to decide. Each resumed ledger has one step_begin for 1/fix and its step_end after it, and the re-sent turn’s tokens are the step’s only. The relative directory broke the first attempt’s next grade and worked in the second and the third.

The other case, the daemon dying in the middle of a turn, was not captured live. TestResumeDaemonKilled holds the scripted implement turn at each of three points in chapter 40’s durable order, after its two write_file calls have run, kills the daemon there, restarts it on the same state directory and resumes. At before-record, run alone (2026-11-09 19:14Z, go 1.27.0, the runner’s lines and the same four log lines cut):

...
    rig_test.go:283: ledger: step_begin 0/implement
    kill_test.go:165: Run after the kill: EOF
    kill_test.go:178: before-record: resolved w1 write_file (lost): the call ended before the crash and its result was not kept
    kill_test.go:178: before-record: resolved w2 write_file (lost): the call ended before the crash and its result was not kept
    rig_test.go:283: resume: step 0/implement in flight
    rig_test.go:283: turn 0/implement: final
    rig_test.go:283: ledger: step_end 0/implement
    rig_test.go:283: ledger: step_begin 1/review
    rig_test.go:283: turn 1/review: final
    rig_test.go:283: ledger: step_end 1/review
    rig_test.go:283: ledger: report 1
    rig_test.go:283: ledger: stop accepted
    kill_test.go:181: ledger: 7 lines: run, step_begin 0/implement, step_end 0/implement, step_begin 1/review, step_end 1/review, report, stop
--- PASS: TestResumeDaemonKilled (0.00s)
    --- PASS: TestResumeDaemonKilled/before-record (29.98s)

The two resolved lines are what the restarted daemon’s session/open returned: chapter 40’s rule decided both calls in flight, and both were lost. Resume opens the same session and builds its preamble from those resolutions with resumePreamble (driver.go). The test does not print the preamble; rendered from the two lines above by that function, it is what the re-sent turn began with:

<<<resume
This step was interrupted and is being sent again. Continue from this session's own history; do not start over and do not repeat work that is already done.
A call was in flight when the daemon stopped: write_file (w1) was lost: the call ended before the crash and its result was not kept
A call was in flight when the daemon stopped: write_file (w2) was lost: the call ended before the crash and its result was not kept
resume>>>

Where the driver died, the model is told that nothing was in flight; where the daemon died, it is told which calls were, and what the daemon did with each. The scripted model writes both files again, and the test checks that the worktree holds the script’s bytes. At before-close the two calls are closed, because the turn’s messages were already in the session file and only the ledger’s close was lost. With the driver killed inside session/send (TestResumeDriverKilled) the work session’s messages went from suatta to suattaua, one letter per message (s system, u user, a assistant, t tool): the added u is the resumed turn’s user message with its resume note, and the a the answer. Every kill test, the both-killed one included, ends with the seven-line ledger of an unkilled run of the same script.

What the three captures show

The loop’s plumbing worked each time it was asked to: the cap bounded each call, a cut review was a failed review and not a pass, the client approver allowed the plain commands it was written to allow, Resume re-sent a killed step under a relative directory, and the breakers stopped what they were designed to stop. No live run reached accepted. The obstacle was not the approver or the driver. It was a reasoning model, of one family or the other, that did not reliably reach a findings block inside a cap of this size, and a strict format that treats a near miss as no block. Nothing here measures how often.

A grade the attempt writes for itself

The limit named in the mechanism section is a measurement, not an opinion. On straylight (go 1.26.7), in a scratch copy of the fixture under the scratchpad, an attempt that commits a Median ignoring its input is graded with the spec’s own acceptance command and HOME at the graded tree. First without anything else, then with the file the attempt writes, .config/go/env holding one line, GOFLAGS=-run=^$, which the fixture’s .gitignore ignores and which is therefore in no commit and no diff (dishonest.txt in the first attempt’s run directory):

== 1. no env file: the grade as the spec wrote it
.spec/median_test.go: OK
--- FAIL: TestMedianEmpty (0.00s)
    median_test.go:14: Median(nil) err = <nil>, want ErrEmpty
--- FAIL: TestMedianOdd (0.00s)
    median_test.go:21: Median(3 1 2) = 0, <nil>, want 2
--- FAIL: TestMedianEvenAveragesTheMiddlePair (0.00s)
    median_test.go:32: Median(4 1 3 2) = 0, <nil>, want 2.5
FAIL
FAIL    fixture/calc    0.001s
?       fixture/cmd/calc    [no test files]
FAIL
exit 1
== 2. the attempt writes .config/go/env (untracked, ignored by .gitignore)
GOFLAGS=-run=^$
...
.spec/median_test.go: OK
ok      fixture/calc    0.002s [no tests to run]
?       fixture/cmd/calc    [no test files]
exit 0

The hash pin passes in both, since the test file is untouched; with the file, go test ./... selects no test, prints ok ... [no tests to run], and the command exits 0. The third run grades a tracked-only export of the same commit (git archive HEAD), which does not contain .config, and it fails as the first did: three FAIL lines, exit 1. That is what the driver’s grading does (the file in the worktree never reaches the grade), and it is why the lab’s TestGradeIgnoresIgnoredFiles passes with an implementer that writes GOFLAGS=-exec=true there. It closes this channel. It does not close the class: a test the attempt’s own code can influence is a test run by the code under test, and an approved or graded go test runs whatever code the attempt wrote, and the one file measured here is only the cheapest way to make it say what the attempt wants. The defences are the ones named above, and the grade is read as evidence against honest mistakes.

Exercises

(1) Redo the geometric reading two more ways. First count the clean review that ends each chapter as a trial, so chapter ii has ki+1k_i + 1 trials; then count chapter 44’s “1A, 1B” as one wave. For each give p^\hat p, the geometric median and the probability of needing more than three waves. Say which definition of a trial the chapter’s default rests on and why, and what neither reading changes. Then do the 4/17 reading, in which chapter 42’s fixes 6 and 7 (:48) count as two more waves of chapter 42.

Answer

With the clean review counted the counts are {6,4,5,4}\{6, 4, 5, 4\}, so p^=4/19=0.2105\hat p = 4/19 = 0.2105, the geometric median is ⌈ln0.5/ln(15/19)⌉=⌈2.932⌉=3\lceil \ln 0.5 / \ln(15/19) \rceil = \lceil 2.932 \rceil = 3, and the probability of more than kk waves is 0.7895, 0.6233, 0.4921 and 0.3885 for k=1,…,4k = 1, \ldots, 4, so 0.492 at three against the default’s 0.394. With 1A and 1B as one wave the counts are {5,3,3,3}\{5, 3, 3, 3\}, p^=4/14=0.2857\hat p = 4/14 = 0.2857, the median is ⌈2.060⌉=3\lceil 2.060 \rceil = 3 and the tail at three is (10/14)3=0.364(10/14)^3 = 0.364. The 4/17 reading has counts {7,3,4,3}\{7, 3, 4, 3\}, p^=4/17=0.2353\hat p = 4/17 = 0.2353, median ⌈2.584⌉=3\lceil 2.584 \rceil = 3 and tail at three 0.447. All four readings come from one script on straylight.

The default counts a fix wave as the trial, cleared when the review after it finds nothing above minor. Counting the clean review as a trial adds a trial that succeeds by construction whenever a chapter ends, and so makes clearing look harder than it was; counting 1A and 1B as one is the only reading that moves the estimate up. None of the four moves the median off 3, and the median is the only number the default takes from the derivation. What the choice moves is the tail: a budget of three leaves between 36 and 49 per cent of attempts uncleared depending on the reading, and that range, not the point estimate, is what a reader sets the cap against.

(2) The enumerator has no operator for an index shifted by one. Design the class (s[i] to s[i+1] and to s[i-1]), apply it to the Median that run 1 of the second attempt committed, and say which test of the shipped file kills each mutant and which tests kill none. Then say what adding the class does to TT, to KK and to the reading of K/TK/T.

Answer

The class applies to the three index expressions of the capture’s Median (sorted[mid] in the odd branch, sorted[mid-1] and sorted[mid] in the even branch, with mid set to n/2) with ±1\pm 1 on each: six mutants. Run one at a time against the shipped test on straylight, all six fail it. The two on the odd branch fail TestMedianOdd on Median(3 1 2) (it returns 3 for the +1 and 1 for the -1, want 2). The four on the even branch fail TestMedianEvenAveragesTheMiddlePair on Median(4 1 3 2) (3, 2, 3 and 2, want 2.5). TestMedianEmpty, which returns before any index, and TestMedianLeavesItsInputInOrder, which does not read the value, kill none of them. Each of the six dies at its test’s first assertion, so this run does not show that the second assertions (Median(7) and Median(1 1 1 10)) matter.

The class adds 6 to TT and 6 to KK, and K/TK/T rises, because the new mutants are easy: an index shift in a function whose job is to pick two elements is caught by any test that checks a value. A score compares two passes only when they use the same operators, and adding cheap ones raises it without the tests having changed. The interval narrows with TT too, which overstates what was learned, because the six are not independent (they share three expressions).

(3) List the crash points between a fix step’s step_begin and its step_end: before the send; during the send; after the daemon’s reply and before the commit; after the commit and before the step_end. For each say what Resume re-sends and what the model’s history holds. Which can make a commit twice, and why is the second empty?

Answer

In all four the ledger’s last line is the open step_begin, so Resume takes its first branch: it opens the session and re-sends the step with a preamble. (1) Before the send, the history holds nothing of the step, and the preamble says the turn was cancelled and nothing was in flight. (2) During the send, the connection drops, the daemon cancels the turn, and the history holds the fix prompt, the assistant’s call and a cancelled tool result; the capture’s kill is this case. (3) After the daemon’s reply and before the commit, the history holds the complete turn and the worktree holds its edits uncommitted; the re-sent turn starts from all of it, and the commit that follows takes the edits once. (4) After the commit and before the step_end, the commit is on the branch and the re-sent turn adds nothing. This is the one that can commit twice: the second Commit finds the worktree equal to the head and has nothing to commit, and the driver records the head it did not find in any step_end, so Result.Head names the first commit.

(4) Construct a sequence of findings over two reviews in which NoProgress trips and RepeatFinding does not, and one in which the reverse holds. Say what each says about the fixer.

Answer

With the defaults (2 for both): the first review finds {A,B,C}\{A, B, C\} above minor and the second {D,E,F}\{D, E, F\}. The count does not fall, so NoProgress trips after the second round, and no hash appears twice, so RepeatFinding does not. The fixer fixed what it was told and the reviewer found as many new things: either the fixes introduce faults, or the review is not converging on a stable list. The reverse: {A,B,C}\{A, B, C\} then {A}\{A\}. The count fell from 3 to 1, so NoProgress resets, and AA is in two reviews running, so RepeatFinding trips. The fixer made progress on two findings and cannot fix the third, and a third round would not change that.

(5) The reviewer is another model than the implementer. State what the independence claim rests on, and design the two-arm measurement that would test it on the rig. What is the unit, what is paired, and what rule would you register first?

Answer

The claim rests on two things: another family has other priors about what a Go change should contain, and the reviewer reads evidence it did not write, the acceptance trials and the mutation report. It does not rest on the reviewer being better, which nothing here measures. The test is the same reviewer model given the same diff in two arms, one with the driver’s two reports in its prompt and one without. The unit is an attempt, a committed diff whose faults are known (seeded, or found afterwards). The pairing is the attempt: each diff is reviewed under both arms, each in a fresh session, and the outcome is the number of the attempt’s known faults each review names. Register the rule before any review runs: the arms, the fault list for each diff, the outcome, the margin that counts as an effect and the number of attempts. Register precision beside recall, since a reviewer that lists everything names every fault.

Lab

make lab CH=53 IMPL=mine runs go/labs/ch53 against your mine/mutants.go, which holds Mutants: the deterministic enumeration of the planted bugs of the Go files an attempt changed, from go/ast over the file’s bytes, in file and position order, at most max, with ids that are a function of the file’s bytes alone. IMPL=ref runs the reference’s. The driver, the ledger, the budget and breakers, the approver and the daemon are the reference’s in both cases, and so are the tests that run the mutation pass and the loop, which are properties of the deployed loop.

  • TestMutantsDeterministic checks that your enumeration lists the same mutants twice and the reference’s, ids included, over chapter 52’s fixture calc.go.
  • TestMutateKillsAndSurvives runs the mutation pass over that file with the fixture’s own tests, in a copy, under the host’s sandbox: 8 mutants, 7 killed and one survivor, the 0 -> 1 on the zero value Mean returns beside ErrEmpty (8.9 s for the pass on straylight).
  • TestLedgerDurability cuts a torn last line with and without its newline, refuses a bad line in the middle, a step_end without its begin and the rest of the ledger’s refusals, and round-trips the Result bytes.
  • TestLoopOnRig, TestBudgetStops, TestRejected and TestReviewerRoleIsAux run the loop on a running aecd whose model is a script, to an accepted attempt, to each of the budget’s stops, to rejected for a tampered worktree, and with the reviewer under aux. TestTruncatedReviewIsNotEvidence is the rule every capture hit most: a review cut at the cap is an important finding even when a closed none block precedes the cut, and the run is accepted only when the next review ends on its own.
  • TestToolchainFilesAreNotCommitted has an implementer write a build cache, a module cache and the scratchpad’s file at the worktree’s top, with the repository’s own .gitignore emptied, and checks that only the driver’s ignore file keeps them out of the commit. TestRunDirInsideRepoRefused refuses a run directory inside the main repository before anything is written, named directly, below a directory not yet made, or through a link. TestRepoInsideWorkspaceRefused names, through a link, a main repository inside the work session’s workspace, and checks that Run refuses it before the worktree is cut or a ledger line written.
  • TestLearnStep is the learn step’s refusals and its one promotion: after an accepted run only a clean vet of the staged set promotes the one new skill, and every refusal and error leaves the live directory byte-identical and the stage empty.
  • TestResumeDriverKilled, TestResumeDaemonKilled, TestResumeBothKilled, TestResumeAfterCommit, TestResumeAfterFailedStep, TestResumeRelativeDir and TestResumeRefusesOtherSpec are the kills and the resumes: the driver killed inside session/send, the daemon killed at each of its three points, both, a driver dead between the commit and the step_end, between a failed turn and its stop, a resume given a relative directory, and a ledger of another spec.
  • TestClientApproverAllowlist is the approver’s table; TestGradeIgnoresIgnoredFiles is the grade ignoring an env file the implementer wrote; TestRunsDoNotShare and the tests beside it are the run id’s.
  • TestBudgetFromRecord recomputes the chapter’s p^\hat p, the median and the tail from the record’s counts, and prints the table.
  • TestCaptureShape, TestResumedCaptureShape, TestCaptureConfigLimits, TestCaptureLines, the TestCapture2* and TestResumedCapture2Shape tests of the second attempt, the TestCapture3* and TestResumedCapture3Shape tests of the third capture (which also check that max_tokens is set and that each window reserves at least that many tokens), and TestNoSecretsInTestdata, read the committed captures as data: no torn line, the run line’s spec hash equal to the hash of the committed median.md, the number of reports and the verdicts, the step_begin for 1/fix once and its step_end after it, the limits in aecd.json equal to spec.SandboxLimits(), and no secret, and no path, socket or pid of a run, in the directory. Times are the exception by design: the .txt files keep the captures’ wall times, with a space where the clock had a T, which the detector’s typed form does not match, as each README.txt says.

make lab CH=53 IMPL=ref passed in 61.6 s on straylight (2026-11-09, in the dev shell at nice 19). Under go test -count=1 -v ./labs/ch53 (68.0 s) the tests ran in parallel: the first 23.6 s warmed one Go build cache under bwrap that the rest shared, and the slowest were the two that run a second loop on the same directory (TestRunsDoNotShare, 24.8 s, and TestSameDirReused, 25.0 s), then TestLoopOnRig (9.6 s) and TestMutateKillsAndSurvives (9.2 s). What the lab cannot see: the model. Every attempt in it is a script, so the reviewer’s text in the captures is a fixture and not a property, and whether a real reviewer finds a given fault is not something a test here can say. None of the three captures is re-run by anything.

Further reading

results matching ""

    No results matching ""