52. Specs as the interface
Parts III to IX built a daemon that can change a repository. Nothing in them says what change. This chapter makes that statement a document the program parses, lints and compiles to a chapter 37 task, and then shows what an ambiguous sentence in it does to a model and what a written ruling does about it.
Why this layer exists
A tool spec is the interface between a model and a tool (chapter 27): a name, a schema, a description, and an error contract, read partly by the program that dispatches the call and partly by the model that decides to make it. A task spec is the same kind of document one level up. It sits between a human and an agent, one half read by the program (which repository, which paths the change may touch, how much budget, which commands decide whether the change is accepted) and one half read by the model (what to do, what not to do, the interface the result must have). The acceptance tests are the contract between the two readers: the human wrote them and the agent can run them, so “done” is a status code and not an opinion.
This book was produced that way, and its records show what a working form looks like. The design document is the binding spec; each part has a written plan that argues from it; a task brief is a plan section; and a decision that the plan did not settle is recorded as a ruling, one dated line in the form Ruling: <what> — <why> — <cost if wrong> (the book’s AGENTS.md fixes the form; the provenance page describes the plans and the reviews around it). What this chapter adds is a machine that reads such a document: the front matter is parsed, the body is linted for the sentences that defer a decision to the implementer, and the acceptance commands become the grader of a chapter 37 task. There is no primer here on writing requirements. The pages go to what one ambiguous sentence does to a model and how a written ruling settles it.
The lab spans two chapters. Here the spec runs through chapter 37’s harness, aec-eval run, with chapter 43’s exec graders as the acceptance runner: the daemon’s own aecd eval grades a daemon’s trajectory and does not run code acceptance, so it is not the runner for this. Chapter 53 is where aecd executes the same spec in a loop with reviewers.
Mechanism
The document
// Document is one spec file. Front matter (between --- lines, key: value,
// as chapter 36's SKILL.md) carries the machine-read fields; the body is
// Markdown with the sections Goal, Non-goals, Interface, Acceptance and
// Rulings in that order, each a ## heading; a missing or misordered section
// is a Problem from Lint, not a parse error, so a draft can be read and
// told what it lacks.
type Document struct {
ID string // front matter id: [a-z0-9-]+, the task id and the stem of the branch and session names (chapter 53 adds a run id)
Title string //
Repo string // "." for the repository the spec lives in, else a path or the fixture's name
Base string // the ref the change starts from; default "main"
Allow []string // path globs the change may touch; a file outside them fails the policy gate (chapter 54)
Acceptance []Acceptance // the tests the spec names; each an exec grader
Budget Budget //
Sandbox string // the backend the acceptance tests run under; "" skips them with the reason (chapter 37's rule)
Body string // the Markdown after the front matter, verbatim
Sections []Section // the ## sections in file order
Rulings []Ruling // parsed from the Rulings section
Modified time.Time // the file's mtime, for the ledger's spec hash line
Hash string // sha256 of the file's bytes; the ledger and the trial record carry it
raw []byte // the file as read, for AddRuling
lines []string // the file's lines, for Lint's line numbers
bodyLine int // the 1-based line the body starts at
dir string // the directory Repo is resolved from (ParseFile, Locate)
loose bool // ParseMarkdown: no front matter, the section rules off
headings map[string]int // section heading -> 1-based line
badRuling []int // Rulings lines that begin with Ruling and do not parse
}
// Acceptance is one named test: a command run by sh -c in the sandbox over
// the workspace after the run (eval.Exec), passing on ExpectStatus.
type Acceptance struct {
Name string `json:"name"`
Command string `json:"command"`
ExpectStatus int `json:"expect_status,omitempty"`
}
// Budget bounds what one attempt may spend; zero fields take chapter 26's
// and chapter 53's defaults.
type Budget struct {
MaxTurns int `json:"max_turns,omitempty"`
MaxToolCalls int `json:"max_tool_calls,omitempty"`
Timeout time.Duration `json:"timeout,omitempty"`
MaxRounds int `json:"max_rounds,omitempty"` // chapter 53: fix rounds
MaxTokens int `json:"max_tokens,omitempty"` // chapter 53: prompt + completion over the whole loop
}
// Section is one ## heading and its text.
type Section struct {
Heading string
Text string
}
// Ruling is one line of the Rulings section, in the ledger's form:
// "Ruling: <what> — <why> — <cost if wrong>", with the date the line carries.
type Ruling struct {
Date string
What string
Why string
CostIfWrong string
}
// Parse reads a Document. It refuses a file over MaxBytes, a front matter
// without id or acceptance, an id that is not a valid task and branch
// name, and an acceptance command that is empty; everything else is Lint's.
func Parse(r io.Reader) (*Document, error) { return parse(r, false) }
// MaxBytes bounds a spec file.
const MaxBytes = 256 << 10
// MaxMarkdownBytes bounds a file read by ParseMarkdown. It is larger than
// MaxBytes because it reads the book's own plans, which are working
// documents of up to a few hundred kilobytes, not specs an agent is given
// as its request; a spec's size matters because the model reads it, a
// plan's does not.
const MaxMarkdownBytes = 1 << 20
// Problem is one thing Lint found: the section, the line, and the text.
type Problem struct {
Section string
Line int
Kind string // missing_section, order, no_acceptance_for_goal, ambiguous, unnamed_test, path_outside_allow, ruling_form
Text string
}
// Lint reads a Document for the failures chapter 52 shows: a section
// missing or out of order; a Goal sentence with no acceptance test naming
// it; an acceptance test the body never names; an Allow glob that matches
// nothing in the repository (when repo is given); and the ambiguity markers
// (words that defer a decision to the implementer: "appropriate", "as
// needed", "etc.", "and so on", "robust", "properly", "handle" with no
// object) with their lines. It is a lint, not a judge: the chapter measures
// what it catches on the book's own specs and plans.
func Lint(d *Document, repo string) []Problem { return lint(d, repo) }
// Task compiles a Document to one chapter 37 task: Request is the body
// (goal, interface, acceptance by name, rulings; the front matter is not
// sent), Tools the file tools and execute_code, Stop from Budget, and
// Grade an "all" of one exec grader per Acceptance, so eval.Grade grades it
// and aec-eval run runs it under Suite.Sandbox (ruling X9-11: not aecd eval).
func (d *Document) Task() (eval.TaskSpec, error) { return d.task() }
// Suite wraps Task in a one-task suite naming the providers and candidates
// given, with Sandbox d.Sandbox, so the spec runs through aec-eval run as
// it stands.
func (d *Document) Suite(providers map[string]route.ProviderConfig, candidates []string) (*eval.Suite, error) {
return d.suite(providers, candidates)
}
// AddRuling appends a ruling to the Rulings section and returns the new
// file text; the caller writes it (a seat never edits a spec in place
// without the diff being visible).
func (d *Document) AddRuling(r Ruling) (string, error) { return d.addRuling(r) }
A spec is one Markdown file. Its front matter is the SKILL.md shape of chapter 36, key: value lines between two --- lines, re-implemented and not imported: a spec is not a skill, and the two formats will diverge (a skill’s header is read to decide whether to load it; a spec’s is read to decide what to run and what to accept). What carries over is chapter 36’s habit. The loader never guesses at a header, and neither does this parser. A file with no closing ---, a duplicate key, an unknown key, a tab, a sequence item (- a, where a flow list [a, b] is wanted; an item may sit in one matching pair of quotes, which is removed), an allow item that is empty or has an unmatched quote or bracket (a comma always separates items, so a glob’s character class cannot hold one), an id that is not a valid task and branch name, an acceptance command that is empty, a budget value that is not an integer or a duration, a sandbox that is not local, podman or ssh, a BOM, or more than MaxBytes (256 KiB) is refused with its line number, and nothing downstream sees a half-read document.
The fields divide by reader. The program reads id, repo, base, allow, acceptance, expect_status, budget and sandbox. The model reads the body: ## Goal, ## Non-goals, ## Interface, ## Acceptance and ## Rulings, in that order. The front matter is never sent. That is deliberate and it matters for the acceptance command: the SHA-256 that pins the shipped test lives in a field the model is never shown, so the hash is the spec’s and not the workspace’s. The body names the acceptance tests by their front-matter names in backticks, which is how the lint ties a goal to a test.
A missing or misordered section is a Problem from the lint and not a parse error, so a draft can be read and told what it lacks. The fixture the specs change is a small Go module (package calc with Add and Mean, the calc command, a short AGENTS.md, and the tests a spec ships under .spec/); it stands in for “one of your repositories”, and chapters 53 and 54 run their loop and pipeline on it.
The lint
// Markers are the words that defer a decision to the implementer. The
// expression is RE2, whose matching time is linear in the text whatever the
// pattern (the text is data the lint did not write), with disjoint
// alternatives so that each hit is one word; "handle" counts only with no
// object: followed by punctuation or the end of the line.
var Markers = regexp.MustCompile(`(?i)\b(?:appropriate(?:ly)?|as needed|as necessary|if necessary|robust(?:ly)?|properly|reasonabl[ey]|sensibl[ey]|tbd|todo)\b|(?i)\betc\.|(?i)\band so on\b|(?i)\bhandl(?:e|es|ed)\s*(?:[.,;:!?]|$)`)
// codeSpanRE is a backticked span on one line; fenced blocks are tracked
// line by line. Both are removed before the markers run: a word inside
// code is the program's, not the spec's.
var codeSpanRE = regexp.MustCompile("`[^`]*`")
// Kinds of Problem.
const (
MissingSection = "missing_section"
Order = "order"
NoAcceptanceForGoal = "no_acceptance_for_goal"
Ambiguous = "ambiguous"
UnnamedTest = "unnamed_test"
PathOutsideAllow = "path_outside_allow"
RulingForm = "ruling_form"
)
func lint(d *Document, repo string) []Problem {
var out []Problem
if !d.loose {
out = append(out, d.lintSections()...)
out = append(out, d.lintGoal()...)
out = append(out, d.lintUnnamed()...)
if repo != "" {
out = append(out, d.lintAllow(repo)...)
}
}
out = append(out, d.lintMarkers()...)
for _, n := range d.badRuling {
out = append(out, Problem{Section: "Rulings", Line: n, Kind: RulingForm, Text: "a Ruling line without its three parts (what — why — cost if wrong): " + strings.TrimSpace(d.lines[n-1])})
}
return out
}
// lintSections: every required heading present, in Headings' order.
func (d *Document) lintSections() []Problem {
var out []Problem
last := 0
for _, h := range Headings {
line, ok := d.headings[h]
if !ok {
out = append(out, Problem{Section: h, Line: 0, Kind: MissingSection, Text: "no ## " + h + " section"})
continue
}
if line < last {
out = append(out, Problem{Section: h, Line: line, Kind: Order, Text: "## " + h + " comes before a section that should precede it (the order is " + strings.Join(Headings, ", ") + ")"})
}
if line > last {
last = line
}
}
return out
}
// quoted returns the backticked spans of s, without their backticks.
func quoted(s string) []string {
var out []string
for _, m := range codeSpanRE.FindAllString(s, -1) {
out = append(out, strings.Trim(m, "`"))
}
return out
}
// namesTest reports whether any backticked span of s is an acceptance name.
func (d *Document) namesTest(s string) bool {
for _, q := range quoted(s) {
for _, a := range d.Acceptance {
if q == a.Name {
return true
}
}
}
return false
}
// settledBy returns the ruling whose What quotes, in backticks, a phrase
// that text contains and that contains needle (case-folded), or nil.
// A ruling that quotes the sentence settles the sentence; one that quotes
// only the marker word settles every sentence with that word.
func (d *Document) settledBy(text, needle string) *Ruling {
ltext, lneedle := strings.ToLower(text), strings.ToLower(needle)
for i := range d.Rulings {
for _, q := range quoted(d.Rulings[i].What) {
lq := strings.ToLower(q)
if lq != "" && strings.Contains(ltext, lq) && strings.Contains(lq, lneedle) {
return &d.Rulings[i]
}
}
}
return nil
}
// lintGoal: each line of the Goal section that says something (not blank,
// not a heading) names an acceptance test in backticks, or a ruling quotes
// it and names one.
func (d *Document) lintGoal() []Problem {
start, ok := d.headings["Goal"]
if !ok {
return nil
}
var out []Problem
for i := start; i < len(d.lines) && !headingRE.MatchString(d.lines[i]); i++ {
text := strings.TrimSpace(d.lines[i])
if text == "" || strings.HasPrefix(text, "#") {
continue
}
if d.namesTest(text) {
continue
}
item := strings.TrimLeft(text, "-*0123456789. ")
if r := d.settledBy(item, item); r != nil && d.namesTest(r.What) {
continue
}
out = append(out, Problem{Section: "Goal", Line: i + 1, Kind: NoAcceptanceForGoal, Text: "no acceptance test named for: " + item})
}
return out
}
// lintUnnamed: every acceptance test is named somewhere in the body.
func (d *Document) lintUnnamed() []Problem {
var out []Problem
for _, a := range d.Acceptance {
if !strings.Contains(d.Body, "`"+a.Name+"`") {
out = append(out, Problem{Section: "Acceptance", Line: d.headings["Acceptance"], Kind: UnnamedTest, Text: "acceptance test `" + a.Name + "` is in the front matter and nowhere in the body"})
}
}
return out
}
// lintAllow: every Allow glob matches at least one regular file under
// repo (.git excluded).
func (d *Document) lintAllow(repo string) []Problem {
if len(d.Allow) == 0 {
return nil
}
var files []string
_ = filepath.WalkDir(repo, func(p string, e fs.DirEntry, err error) error {
if err != nil {
return nil
}
if e.IsDir() && e.Name() == ".git" {
return filepath.SkipDir
}
if e.Type().IsRegular() {
if rel, err := filepath.Rel(repo, p); err == nil {
files = append(files, filepath.ToSlash(rel))
}
}
return nil
})
var out []Problem
for _, g := range d.Allow {
hit := false
for _, f := range files {
if MatchGlob(g, f) {
hit = true
break
}
}
if !hit {
out = append(out, Problem{Section: "front matter", Line: 0, Kind: PathOutsideAllow, Text: fmt.Sprintf("allow glob %q matches no file under %s", g, repo)})
}
}
return out
}
// lintMarkers runs Markers over the body's prose: fenced blocks and
// backticked spans removed, a hit settled when a ruling quotes it.
func (d *Document) lintMarkers() []Problem {
var out []Problem
fenced := false
section := ""
start := d.bodyLine - 1
if start < 0 {
start = 0
}
for i := start; i < len(d.lines); i++ {
line := d.lines[i]
if strings.HasPrefix(strings.TrimSpace(line), "```") {
fenced = !fenced
continue
}
if fenced {
continue
}
if m := headingRE.FindStringSubmatch(line); m != nil {
section = m[1]
continue
}
prose := codeSpanRE.ReplaceAllString(line, "")
for _, loc := range Markers.FindAllStringIndex(prose, -1) {
word := strings.TrimSpace(prose[loc[0]:loc[1]])
if !strings.EqualFold(word, "etc.") {
word = strings.TrimRight(word, ".,;:!?")
}
if d.settledBy(prose, word) != nil {
continue
}
out = append(out, Problem{Section: section, Line: i + 1, Kind: Ambiguous, Text: fmt.Sprintf("%q defers a decision to the implementer: %s", word, strings.TrimSpace(prose))})
}
}
return out
}
// MatchGlob matches a slash-separated path against a glob whose segments
// are path.Match patterns and whose "**" segment matches any number of
// segments, including none. Chapter 54's policy gate uses the same rule
// over a diff.
func MatchGlob(pattern, name string) bool {
return matchSegs(strings.Split(strings.Trim(pattern, "/"), "/"), strings.Split(strings.Trim(name, "/"), "/"))
}
func matchSegs(pat, segs []string) bool {
for len(pat) > 0 {
if pat[0] == "**" {
if len(pat) == 1 {
return true
}
for i := 0; i <= len(segs); i++ {
if matchSegs(pat[1:], segs[i:]) {
return true
}
}
return false
}
if len(segs) == 0 {
return false
}
if ok, err := path.Match(pat[0], segs[0]); err != nil || !ok {
return false
}
pat, segs = pat[1:], segs[1:]
}
return len(segs) == 0
}
Seven kinds of problem, each with a section and a 1-based file line (front matter counted): missing_section and order; no_acceptance_for_goal, a line of the Goal that names no acceptance test; unnamed_test, a test in the front matter that the body never names; path_outside_allow, an allow glob that matches no file of the repository; ambiguous; and ruling_form, a line that begins Ruling and does not have its three parts.
ambiguous is the marker vocabulary, printed in full above: appropriate and appropriately, as needed, as necessary, if necessary, robust and robustly, properly, reasonable and reasonably, sensible and sensibly, tbd, todo, etc. (kept with its dot), and so on, and handle, handles or handled with no object, meaning followed by punctuation or the end of the line. Fenced blocks and backticked spans are removed first: a word inside code is the program’s, not the spec’s. The expression is RE2, whose matching time is linear in the text however the pattern is written, which matters because the text is data the lint did not write (a test bounds ten thousand adversarial characters at one second; on straylight the lint of that text, 385 hits, took 3.9 to 5.2 ms over five runs). The alternatives are disjoint so that each hit is one word. Each word defers a decision: appropriately to whoever reads it, handle to whatever the implementer thinks handling is.
A ruling settles a hit when its what quotes, in backticks, a phrase that contains the marker word and that the flagged sentence contains. A ruling that quotes the sentence settles the sentence. For a Goal line the ruling must also name an acceptance test, so the settled line still has one. This is the formalisation of what the book’s ledgers did by hand: Ruling: <what> — <why> — <cost if wrong>, with the date, one ruling per line. Its ancestor is Nygard’s architecture decision record (context, decision, status, consequences), cut down to the three parts a reviewer needs to reopen the decision.
The lint is not a judge, and the book’s own documents show it. At commit 50a0906 on straylight (2026-11-08), aec-work spec check -markdown over docs/superpowers/specs/ (2 files, 754 lines) and docs/superpowers/plans/ (40 files, 145,068 lines; the largest is 397,089 bytes, under the -markdown cap of 1 MiB, which is larger than a spec’s because a plan is a working document the model never takes as its request) read every file and refused none:
| specs | plans | |
|---|---|---|
ambiguous |
2 | 48 |
ruling_form |
0 | 0 |
lines that begin Ruling |
0 | 3 (all well-formed; all inside the plan for this chapter, as fixture text: a Go test’s string and the two fixture specs; the book’s own rulings live in the ledgers under .superpowers/, which the lint was not run over) |
By word, the plans’ 48: appropriate 10, robust 9 (three capitalised), reasonable 9, etc. 5, handle 4, as needed 3, and so on 2, appropriately 2, and one each of sensible, reasonably, TODO and handled; the specs’ two are robust and etc.. The 48 hits were each read in their sentence at 50a0906 and sorted by hand; the classes are that one reading and not a second reviewer’s.
| class | hits |
|---|---|
| another document’s words, quoted in a plan: paper and RFC titles (Efficient and robust approximate nearest neighbor search, Maintaining Robust Protocols, Is mutation an appropriate tool for testing experiments?), sentences of RFC 9110, the MCP and JSON Schema specifications, a vendor’s cache page and the LoRA and tail-latency papers, and three times Kyle’s own “some appropriate MCP” | 26 |
handle as a noun or in another sense (kills by handle,, verified by a handle,, stopped by handle,, a request was being handled) |
5 |
| the writer’s own idiom with the expectation spelled out in the same sentence (A reasonable person expects … five times in one list, could reasonably keep) | 6 |
| the writer’s own word with the decision pinned in the same clause (Mutation-robust tests: run your own mutation pass of at least 25…, the robust fix does not depend on the answer: send every generation upstream as a stream, and so on for every row after the rule that says what the row is, a list’s etc. after a listing marker) | 6 |
text about the lint or the fixture (TODO inside a fixture’s description, the lint’s own rule list, this chapter’s ambiguous sentence quoted) |
3 |
| a real deferral to the implementer (Modify … as needed; a sensible description in an exercise) | 2 |
So two of the 48 are the failure the rule exists for, and the other 46 are not. The lint cannot tell quoted text from the writer’s own, and the plans quote their sources heavily; its no-object rule for handle fires on the noun when a comma follows it, not only on the verb with nothing to act on (the phrase “handle the case” would not fire: it has an object). The value of the rule is the sentence it makes a writer re-read, and the cost is that the re-read is mostly of text that was never the writer’s. These were documents written for agents and read by them; the count is what a lint finds in them, not a verdict on them, and it says nothing about how often an agent went wrong on one of the sentences.
The compilation
// Tools are the task's tools: chapter 27's file tools over the workspace and
// chapter 43's execute_code (sh), which is how a model runs the project's
// commands under chapter 37's runner. The registry never offers terminal
// (eval.KnownTools); the daemon's terminal is chapter 53's, where aecd
// executes the same spec.
var Tools = []string{"read_file", "write_file", "search_files", "execute_code"}
// System is the one system line a compiled task sends: what the workspace
// is and how the attempt ends. Everything else the model is told is the
// spec's body.
const System = "You are changing a repository checked out in your workspace. Read AGENTS.md first and follow it. " +
"Use read_file, write_file and search_files on the workspace, and execute_code with language sh to run the project's commands. " +
"When the change is complete and its tests pass, reply with the word done."
// SandboxMemory is the address-space limit the acceptance tests run under
// when the spec names a sandbox: the Go toolchain does not start under
// sandbox.DefaultLimits' 512 MiB (the runtime cannot reserve its page
// summaries) and the compiler runs out of memory under 1 GiB; a cold go vet
// and go test of the fixture passed at 2 GiB on straylight, and 4 GiB is
// that with room. The same number sizes each of bwrap's three tmpfs mounts
// and the scope's MemoryMax, so it is a real cost, not a formality.
const SandboxMemory = 4 << 30
// SandboxLimits is DefaultLimits with MemoryBytes raised to SandboxMemory:
// what Suite sets, and what chapter 53's workflow configures its acceptance
// and mutation backend with, so the two chapters run the same tests under
// the same limits. This package owns the number; nothing else repeats it.
func SandboxLimits() sandbox.Limits {
lim := sandbox.DefaultLimits()
lim.MemoryBytes = SandboxMemory
return lim
}
func (d *Document) task() (eval.TaskSpec, error) {
dir, err := d.RepoDir()
if err != nil {
return eval.TaskSpec{}, err
}
before, err := filesUnder(dir)
if err != nil {
return eval.TaskSpec{}, err
}
if len(before) == 0 {
return eval.TaskSpec{}, fmt.Errorf("spec: no files under %s", dir)
}
if len(d.Acceptance) == 0 {
return eval.TaskSpec{}, errors.New("spec: no acceptance tests to grade by")
}
grade := eval.GraderSpec{Kind: "all"}
for _, a := range d.Acceptance {
grade.All = append(grade.All, eval.GraderSpec{Kind: "exec", Command: a.Command, ExpectStatus: a.ExpectStatus})
}
return eval.TaskSpec{
ID: d.ID,
System: System,
Request: d.Body,
Tools: append([]string(nil), Tools...),
Env: &eval.Files{Before: before},
Stop: eval.StopRule{MaxTurns: d.Budget.MaxTurns, MaxToolCalls: d.Budget.MaxToolCalls, Timeout: d.Budget.Timeout},
Grade: grade,
Cluster: d.ID,
}, nil
}
func (d *Document) suite(providers map[string]route.ProviderConfig, candidates []string) (*eval.Suite, error) {
t, err := d.task()
if err != nil {
return nil, err
}
if len(candidates) == 0 {
return nil, errors.New("spec: a suite needs at least one candidate")
}
s := &eval.Suite{Name: d.ID, Providers: providers, Tasks: []eval.TaskSpec{t}, Sandbox: d.Sandbox}
for _, c := range candidates {
if _, ok := providers[c]; !ok {
return nil, fmt.Errorf("spec: candidate %q is not a provider given", c)
}
s.Candidates = append(s.Candidates, eval.Candidate{Provider: c})
}
if d.Sandbox != "" {
lim := SandboxLimits()
s.SandboxLimits = &lim
}
return s, nil
}
Task produces one chapter 37 TaskSpec from five places, and the figure shows where each comes from. The request is the body, verbatim. The environment, Env.Before, is every regular file of the repository (no .git; a symlink or a file that is not UTF-8 is refused, as repo.Init refuses one). The tools are read_file, write_file, search_files and execute_code: the registry offers no terminal to a chapter 37 run (eval.KnownTools), and the daemon’s terminal is chapter 53’s, where aecd executes the same spec. The stop rule is the budget. The grade is an all of one exec grader per acceptance test.
The exec grader is chapter 43’s, and what makes it the acceptance test is where it runs. After the loop ends, eval.Grade runs each command with sh -c over the trial’s workspace under Suite.Sandbox. A model’s own go test through execute_code during the loop and the grader’s afterwards run in the same sandbox over the same files, so the model can run what the grader runs, and the grade is the grader’s. One gap: go test ./... skips a directory whose name begins with a dot, so the shipped .spec/median_test.go is compiled only when it is copied into calc/, which is the acceptance command’s cp. A model that runs go test ./... sees only the tests of calc/; to run the shipped test it has to reproduce the cp (or read the file).
The hash pin is the one piece of the contract that is not just a command. The shipped test sits in .spec/median_test.go, in the workspace, where the model can read it and write to it. The acceptance command is
echo "<sha256> .spec/median_test.go" | sha256sum -c - && cp .spec/median_test.go calc/ && go vet ./... && go test ./...
so an attempt that rewrites the test fails at sha256sum -c before any Go runs; the lab’s TestTamperedTestFails quotes the detail it earns, below. The pin does not stop a model from writing a Median that special-cases the test’s inputs. The test checks outputs; nothing here checks that the code is general. Chapter 53’s mutation pass is for that. Nor does the pin survive an attempt that sets out to lie about its own grade. The grader runs with HOME at the workspace, and the go command reads $HOME/.config/go/env; a model-written file there holding GOFLAGS=-run=^$ makes go test ./... select no test, so a Median that returns 0 passes with sha256sum -c still printing OK. On straylight (go 1.26.7) the scratch run printed ok fixture/calc 0.002s [no tests to run] and exit 0 for it, against three FAIL lines and exit 1 for the same Median without the file. The defences are not in this chapter; chapter 53 measures the case and says what stands in for them.
The sandbox and its limits
The local backend (chapter 43) runs a command in bwrap under systemd-run, with RLIMIT_AS set from Limits.MemoryBytes, 512 MiB by default. The Go toolchain does not start there. On straylight on 2026-11-08, with Limits{}, the vet-test command exited with status 2 in 0.05 s and the message failed to reserve page summary memory: the Go runtime reserves address space for its page summaries at start-up, and RLIMIT_AS counts reserved, not touched, pages. At 1 GiB the runtime started and the compiler ran out of memory. At 2 GiB vet-test passed in 25.00 s, and at 4 GiB in 25.16 s (a second sweep, by Task 0’s reviewer on the same host and day, gave 24.73 s at 2 GiB and 24.34 s at 4 GiB; the time did not move with the limit once the toolchain started). spec.SandboxMemory is 4 GiB, which is the 2 GiB that passed with room.
The number is not free. MemoryBytes also sizes chapter 43’s three tmpfs mounts and the scope’s MemoryMax, so raising it raises what a command may hold in memory-backed files. To carry the number from a spec to the harness, the suite format gained one field, Suite.SandboxLimits, a pointer. Nil means sandbox.Limits{}, which Configure reads as DefaultLimits, so every suite of Parts VI to IX behaves as before; a set value decodes onto DefaultLimits, so a hand-written {"memory_bytes": N} keeps read_only true and only a field the object gives is changed, "read_only": false included. It is additive in the JSON and the durations in it are nanoseconds. aec-eval check and run configure the backend with s.Limits(), and a test pins that the call appears exactly where it should.
The git joint
// Git is the binary and the identity every command of this package uses.
// Identity is "aec <aec@localhost>" unless set; it is what the fixture's
// commits carry, so two checkouts of one fixture are byte-identical.
type Git struct {
Binary string // absolute path; Find resolves it from the daemon's PATH
Identity string // "Name <email>"
Timeout time.Duration // per command; default 60 s
// Exclude, when set, is the absolute path of a file of ignore patterns
// every command reads as core.excludesFile (otherwise /dev/null). It is
// the caller's, kept outside every worktree (a command refuses one that
// lies inside the worktree it runs in): a way to keep what a tool writes
// into the top of a worktree (a Go build cache, a scratch file) out of
// the staging of Changes and Commit. A worktree's own .gitignore still
// outranks it, and a file already tracked is not affected.
Exclude string
}
// Find resolves git through the absolute elements of path (chapter 43's
// PathOutside rule): a relative element is dropped, a missing git is an
// error, never a fallback to the host's PATH at call time. A git older than
// 2.40 is refused: it ignores GIT_ATTR_SOURCE, the variable that keeps a
// worktree's .gitattributes from selecting a filter or diff driver.
func Find(path string) (*Git, error) {
for _, dir := range filepath.SplitList(tool.PathOutside(path, "")) {
p := filepath.Join(dir, "git")
if st, err := os.Stat(p); err == nil && st.Mode().IsRegular() && st.Mode()&0o111 != 0 {
if err := checkVersion(p); err != nil {
return nil, err
}
return &Git{Binary: p, Identity: DefaultIdentity, Timeout: DefaultTimeout}, nil
}
}
return nil, errors.New("repo: no git in an absolute PATH element")
}
// checkVersion runs binary --version in an empty environment and refuses a
// git older than 2.40.
func checkVersion(binary string) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, binary, "--version")
cmd.Env = []string{"PATH=" + filepath.Dir(binary)}
out, err := cmd.Output()
if err != nil {
return fmt.Errorf("repo: %s --version: %w", binary, err)
}
major, minor, ok := parseGitVersion(string(out))
if !ok {
return fmt.Errorf("repo: cannot read a version from %s --version: %q", binary, strings.TrimSpace(string(out)))
}
if major < 2 || (major == 2 && minor < 40) {
return fmt.Errorf("repo: %s is git %d.%d; 2.40 or later is required (GIT_ATTR_SOURCE)", binary, major, minor)
}
return nil
}
// parseGitVersion reads "git version MAJOR.MINOR[.…][ suffix]".
func parseGitVersion(s string) (major, minor int, ok bool) {
rest, found := strings.CutPrefix(strings.TrimSpace(s), "git version ")
if !found {
return 0, 0, false
}
parts := strings.SplitN(strings.Fields(rest + " ")[0], ".", 3)
if len(parts) < 2 {
return 0, 0, false
}
var err1, err2 error
major, err1 = strconv.Atoi(parts[0])
minor, err2 = strconv.Atoi(parts[1])
return major, minor, err1 == nil && err2 == nil
}
// Init copies the fixture at src into dst (regular files and directories
// only; a symlink in src is refused), runs git init with the main branch
// named "main", adds everything and commits once with Identity and a fixed
// date, and returns the commit hash. dst must be empty.
func (g *Git) Init(ctx context.Context, src, dst string) (head string, err error) {
if err := copyTree(src, dst); err != nil {
return "", err
}
c, err := mainCtx(dst)
if err != nil {
return "", err
}
if _, err := g.run(ctx, c, nil, "init", "-q", "--initial-branch=main"); err != nil {
return "", err
}
if err := writeAttributes(c); err != nil {
return "", err
}
if _, err := g.run(ctx, c, nil, "add", "-A"); err != nil {
return "", err
}
date := []string{"GIT_AUTHOR_DATE=" + FixtureDate, "GIT_COMMITTER_DATE=" + FixtureDate}
if _, err := g.run(ctx, c, date, "commit", "-q", "-m", "fixture"); err != nil {
return "", err
}
return g.Head(ctx, dst)
}
// Worktree adds a worktree of repo at dir on a new branch named branch off
// base (a ref or hash). It is the isolation chapter 54 lands or discards:
// the agent's tools see dir and nothing of repo's checkout.
func (g *Git) Worktree(ctx context.Context, repo, dir, branch, base string) error {
c, err := mainCtx(repo)
if err != nil {
return err
}
if dir, err = filepath.Abs(dir); err != nil {
return fmt.Errorf("repo: %w", err)
}
_, err = g.run(ctx, c, nil, "worktree", "add", "-q", "-b", branch, dir, base)
return err
}
// Remove removes the worktree at dir and deletes its branch when keep is
// false. Unless force is set it first checks, pinned to the worktree's
// administrative directory, that the worktree has no uncommitted changes
// (ErrDirty) and that its .git is the gitfile git wrote (ErrTampered); git's
// own clean check never runs, because the removal is always --force and
// runs in the main repository. With force, nothing runs inside the
// worktree at all: the directory is deleted from the main repository's side.
func (g *Git) Remove(ctx context.Context, repo, dir, branch string, force, keep bool) error {
mc, err := mainCtx(repo)
if err != nil {
return err
}
if dir, err = filepath.Abs(dir); err != nil {
return fmt.Errorf("repo: %w", err)
}
if !force {
wc, err := worktreeCtx(repo, dir)
if err != nil {
return err
}
status, err := g.run(ctx, wc, nil, "status", "--porcelain", "--ignore-submodules=all")
if err != nil {
return err
}
if strings.TrimSpace(status) != "" {
return ErrDirty
}
}
if _, err := g.run(ctx, mc, nil, "worktree", "remove", "--force", dir); err != nil {
return err
}
if keep {
return nil
}
_, err = g.run(ctx, mc, nil, "branch", "-q", "-D", branch)
return err
}
// Diff is what an attempt changed relative to base: the files touched, with
// insertions and deletions per file, and the unified patch text capped at
// MaxPatch bytes (Truncated says it was cut).
type Diff struct {
Base string
Head string
Files []FileChange
Patch string
Truncated bool
}
// FileChange is one file of a Diff.
type FileChange struct {
Path string
Status string // A, M, D, R
Insertions int
Deletions int
}
// MaxPatch bounds the patch text a Diff keeps.
const MaxPatch = 1 << 20
// Changes reads the diff of dir's working tree against base. dir is a
// worktree of repo (or repo itself); the worktree is refused with
// ErrTampered unless its .git is the gitfile git wrote for it.
func (g *Git) Changes(ctx context.Context, repo, dir, base string) (Diff, error) {
d := Diff{Base: base}
c, err := worktreeCtx(repo, dir)
if err != nil {
return d, err
}
head, err := g.head(ctx, c)
if err != nil {
return d, err
}
d.Head = head
// Everything in the working tree is staged into a temporary index, so
// untracked files are in the diff and the real index is untouched.
idx, err := os.CreateTemp("", "aec-repo-index-")
if err != nil {
return d, fmt.Errorf("repo: %w", err)
}
idx.Close()
defer os.Remove(idx.Name())
env := []string{"GIT_INDEX_FILE=" + idx.Name()}
if _, err := g.run(ctx, c, env, "read-tree", "HEAD"); err != nil {
return d, err
}
if _, err := g.run(ctx, c, env, "add", "-A"); err != nil {
return d, err
}
if err := g.noGitlinks(ctx, c, env); err != nil {
return d, err
}
status, err := g.run(ctx, c, env, "diff", "--cached", "--no-ext-diff", "--no-textconv", "--ignore-submodules=all", "-z", "-M", "--name-status", base)
if err != nil {
return d, err
}
numstat, err := g.run(ctx, c, env, "diff", "--cached", "--no-ext-diff", "--no-textconv", "--ignore-submodules=all", "-z", "-M", "--numstat", base)
if err != nil {
return d, err
}
if d.Files, err = parseChanges(status, numstat); err != nil {
return d, err
}
patch, err := g.run(ctx, c, env, "diff", "--cached", "--no-ext-diff", "--no-textconv", "--ignore-submodules=all", "-M", base)
if err != nil {
return d, err
}
if len(patch) > MaxPatch {
patch, d.Truncated = patch[:MaxPatch], true
}
d.Patch = patch
return d, nil
}
// Commit stages every change under dir (a worktree of repo, or repo itself)
// and commits with message under Identity; it returns the new hash. An empty
// tree is an error, not an empty commit; a tampered worktree is ErrTampered.
func (g *Git) Commit(ctx context.Context, repo, dir, message string) (string, error) {
c, err := worktreeCtx(repo, dir)
if err != nil {
return "", err
}
if _, err := g.run(ctx, c, nil, "add", "-A"); err != nil {
return "", err
}
if err := g.noGitlinks(ctx, c, nil); err != nil {
g.run(ctx, c, nil, "reset", "-q") // best effort: leave nothing staged
return "", err
}
if _, err := g.run(ctx, c, nil, "diff", "--cached", "--no-ext-diff", "--no-textconv", "--ignore-submodules=all", "--quiet"); err == nil {
return "", ErrNothingToCommit
} else if exitCode(err) != 1 {
return "", err
}
if _, err := g.run(ctx, c, nil, "commit", "-q", "-m", message); err != nil {
return "", err
}
return g.head(ctx, c)
}
// FastForward moves repo's branch onto head when head descends from it
// (git merge --ff-only in repo's checkout); otherwise ErrNotFastForward.
// It never pushes: the factory's "never pushes by default" is that there
// is no push in this package.
func (g *Git) FastForward(ctx context.Context, repo, branch, head string) error {
c, err := mainCtx(repo)
if err != nil {
return err
}
current, err := g.run(ctx, c, nil, "symbolic-ref", "--short", "HEAD")
if err != nil {
return err
}
if strings.TrimSpace(current) != branch {
return fmt.Errorf("repo: %s has %s checked out, not %s", repo, strings.TrimSpace(current), branch)
}
if _, err := g.run(ctx, c, nil, "merge-base", "--is-ancestor", branch, head); err != nil {
if exitCode(err) == 1 {
return ErrNotFastForward
}
return err
}
_, err = g.run(ctx, c, nil, "merge", "-q", "--ff-only", head)
return err
}
Chapters 53 and 54 end in a change to a repository, so one package, internal/repo, shells out to git, and both cite it. The binary is an absolute path, resolved once from the absolute elements of PATH (chapter 43’s rule: a relative element is dropped) and refused if it is older than git 2.40. The environment is the driver’s, never the daemon’s: no system or global configuration (GIT_CONFIG_NOSYSTEM, GIT_CONFIG_GLOBAL=/dev/null), a HOME and XDG_CONFIG_HOME that are an empty directory made for the call, UTF-8 and UTC. The identity is fixed (aec <aec@localhost>), so Init of the fixture is deterministic: two checkouts of one fixture have one hash, because the commit date is fixed too. Changes stages everything into a temporary index so that untracked files are in the diff and the real index is untouched. FastForward moves a branch only if the new head descends from it. There is no push, fetch, pull or clone in the package, and a test greps for the words.
The reason the package is careful is X9-10: no model-chosen code runs on the host. A worktree’s files are the model’s, and git run over a directory reads configuration out of it unless told not to: a .git file that points elsewhere, hooks, fsmonitor, a pager, an external diff, a textconv, a filter driver named in .gitattributes, a nested repository or a gitlink. So git never discovers a repository from a worktree. Every call names --git-dir and --work-tree, and the worktree’s administrative directory is read from the main repository, never from the worktree’s own .git. A worktree whose .git is not exactly the gitfile git wrote for it is refused (ErrTampered) before any command. A .git below the top level, a top-level .gitmodules and any gitlink that staging would create are refused the same way. Every command line sets the configuration keys that name a program to harmless values (they outrank every file and pass to git’s children), every filter driver the repository configures is blanked by name, GIT_ATTR_SOURCE points at the empty tree so a worktree’s .gitattributes selects nothing, and the one info/attributes file that unspecifies filter, diff, merge and text is written only by Init, for a repository the driver created (an existing user’s file there is never rewritten). One key a caller may set is Git.Exclude: an absolute path, refused if it lies inside the worktree the command runs in, to a file of ignore patterns that every command reads as core.excludesFile (otherwise the null device). Chapter 53’s driver uses it to keep what the toolchain and the daemon write at the top of a worktree, a build cache and a scratch file, out of what Changes and Commit stage; a worktree’s own .gitignore outranks it, and a file that is already tracked is not affected. The repository’s own configuration, and the .git directory, belong to the driver or the user and are trusted. The worktree’s contents are not.
The command
// run is main without the process.
func run(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 {
fmt.Fprintln(stderr, usage)
return 2
}
switch args[0] {
case "spec":
return cmdSpec(args[1:], stdout, stderr)
case "run":
return cmdRun(args[1:], stdout, stderr)
case "resume":
return cmdResume(args[1:], stdout, stderr)
case "status":
return cmdStatus(args[1:], stdout, stderr)
case "mutants":
return cmdMutants(args[1:], stdout, stderr)
case "learn":
return cmdLearn(args[1:], stdout, stderr)
case "placebo":
return cmdPlacebo(args[1:], stdout, stderr)
case "land":
return cmdLand(args[1:], stdout, stderr)
case "paired":
return cmdPaired(args[1:], stdout, stderr)
case "production":
return cmdProduction(args[1:], stdout, stderr)
}
fmt.Fprintln(stderr, usage)
return 2
}
func cmdSpec(args []string, stdout, stderr io.Writer) int {
if len(args) < 2 {
fmt.Fprintln(stderr, usage)
return 2
}
switch args[0] {
case "check":
return specCheck(args[1:], stdout, stderr)
case "task":
return specTask(args[1:], stdout, stderr)
}
fmt.Fprintln(stderr, usage)
return 2
}
// specCheck parses the spec and prints every Problem as
// "kind section:line text", one per line; exit 1 when there is one.
// -markdown reads a document without front matter (the book's own specs
// and plans): the section rules are off, the markers on. -count prints,
// after the problems, one "count kind N" line per kind found. A file that
// cannot be read or is over its size cap (spec.MaxBytes, or
// spec.MaxMarkdownBytes with -markdown) is reported on stderr and the rest
// are still checked; the exit status is 1 if any file was refused or had a
// problem.
func specCheck(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("aec-work spec check", flag.ContinueOnError)
fs.SetOutput(stderr)
repo := fs.String("repo", "", "the repository the allow globs are checked against (default: none)")
markdown := fs.Bool("markdown", false, "read a Markdown document without front matter: the ambiguity markers and the ruling form only")
count := fs.Bool("count", false, "after the problems, print one line per problem kind with its count")
if err := fs.Parse(reorder(args)); err != nil {
return 2
}
if fs.NArg() == 0 {
fmt.Fprintln(stderr, usage)
return 2
}
var all []spec.Problem
refused := 0
for _, path := range fs.Args() {
d, err := parseOne(path, *markdown)
if err != nil {
// A file that cannot be read is reported and the rest are
// still checked; it counts toward the exit status.
fmt.Fprintln(stderr, "aec-work:", err)
refused++
continue
}
for _, p := range spec.Lint(d, *repo) {
all = append(all, p)
fmt.Fprintf(stdout, "%s %s:%d %s\n", p.Kind, p.Section, p.Line, p.Text)
}
}
if *count {
counts := spec.Count(all)
kinds := make([]string, 0, len(counts))
for k := range counts {
kinds = append(kinds, k)
}
sort.Strings(kinds)
for _, k := range kinds {
fmt.Fprintf(stdout, "count %s %d\n", k, counts[k])
}
}
if len(all) > 0 || refused > 0 {
return 1
}
return 0
}
func parseOne(path string, markdown bool) (*spec.Document, error) {
if !markdown {
return spec.ParseFile(path)
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
d, err := spec.ParseMarkdown(f)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
return d, nil
}
// specTask compiles the spec to a one-task suite for aec-eval run: the
// providers come from a routes.json (chapter 28's shape), the candidates
// are the provider names given, the sandbox is the spec's unless -sandbox
// overrides it.
func specTask(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("aec-work spec task", flag.ContinueOnError)
fs.SetOutput(stderr)
out := fs.String("out", "", "the suite file to write")
routes := fs.String("routes", "", "routes.json whose providers the suite names")
provider := fs.String("provider", "", "comma-separated provider names, the suite's candidates")
sb := fs.String("sandbox", "", "override the spec's sandbox (local, podman, ssh)")
if err := fs.Parse(reorder(args)); err != nil {
return 2
}
if fs.NArg() != 1 || *out == "" || *routes == "" || *provider == "" {
fmt.Fprintln(stderr, usage)
return 2
}
d, err := spec.ParseFile(fs.Arg(0))
if err != nil {
fmt.Fprintln(stderr, "aec-work:", err)
return 1
}
if *sb != "" {
d.Sandbox = *sb
}
cfg, err := route.LoadConfig(*routes)
if err != nil {
fmt.Fprintln(stderr, "aec-work:", err)
return 1
}
names := strings.Split(*provider, ",")
providers := map[string]route.ProviderConfig{}
for _, n := range names {
pc, ok := cfg.Providers[n]
if !ok {
fmt.Fprintf(stderr, "aec-work: %s names no provider %q\n", *routes, n)
return 1
}
providers[n] = pc
}
s, err := d.Suite(providers, names)
if err != nil {
fmt.Fprintln(stderr, "aec-work:", err)
return 1
}
b, err := json.MarshalIndent(s, "", " ")
if err != nil {
fmt.Fprintln(stderr, "aec-work:", err)
return 1
}
if err := os.WriteFile(*out, append(b, '\n'), 0o600); err != nil {
fmt.Fprintln(stderr, "aec-work:", err)
return 1
}
fmt.Fprintf(stdout, "%s: task %s, %d acceptance tests, sandbox %q, candidates %s\n", *out, d.ID, len(d.Acceptance), d.Sandbox, strings.Join(names, ","))
return 0
}
aec-work is Part X’s driver, one subcommand per chapter. aec-work spec check FILE... prints each problem as kind section:line text and exits 1 if there was one; -markdown reads a plan or any Markdown file with the front-matter rules off and the markers and the ruling form on, under the 1 MiB cap, and a file it refuses is reported while the rest are still read; -count adds a count per kind. aec-work spec task FILE -out suite.json -routes routes.json -provider NAME writes the suite that aec-eval reads, with the providers from a routes.json of chapter 28’s shape. The switch also dispatches chapter 53’s run, resume, status, mutants, learn and placebo, chapter 54’s land and chapter 55’s paired and production. A name the switch does not know exits 2 with the usage; usage opens and contacts nothing.
What a capture can show
Take reps of a spec where the model picks, with probability per rep, a reading the test rejects. The failure shows at least once with probability
since the complement, no failure in independent reps, has probability . At and that is . Asking for at least 0.95 needs , so , which is at (8.399 from the unrounded logarithms): nine reps, since and . This chapter’s capture has two reps per spec. It is a report of what happened, not a measurement of : at even chapter 38’s default interval (Wilson) for no failures in two reps runs from 0 to 0.66, most of the range.
Walkthrough
Everything below ran on straylight, from the repository root in the flake’s dev shell, against ornith-1.5-35b-a3b on straylight’s router. Kyle authorised waking the sleeping model with -allow-wake for this capture. The bound was printed before the first request:
BOUND: 3 suites x -n 2 x max_turns 12 = at most 72 completions, plus /v1/models reads (one per trial, one per check) and at most one wake
aec-work spec task compiles each spec into a suite (routes.json names one provider, straylight-35b, and the harness’s gate is disabled: the gate is not this chapter’s):
median.json: task median, 2 acceptance tests, sandbox "local", candidates straylight-35b
median-ambiguous.json: task median-ambiguous, 1 acceptance tests, sandbox "local", candidates straylight-35b
median-ruled.json: task median-ruled, 1 acceptance tests, sandbox "local", candidates straylight-35b
(The tool prints the full path before each file name; the run directory is outside the repository.) aec-eval check reads /v1/models once:
suite median: 1 tasks, 1 candidates
sandbox: local+bwrap+systemd-run
straylight-35b@default provider=straylight-35b model=ornith-1.5-35b-a3b effort= extra=none
straylight-35b: ornith-1.5-35b-a3b is sleeping on straylight
/v1/models read, as saved in the run directory, 2026-11-08 23:36:22Z (the capture began that evening, UTC; the extra run below is dated 2026-11-09 UTC) and ornith-1.5-35b-a3b sleeping (the rest of that read: every other model unloaded), so the first run took -allow-wake, the only wake of the capture. Nothing was unloaded or evicted and nothing was sent to any other host. The reads that followed (the model loaded with the first trial under way, and again after the last trial) were printed by the capture’s polling script and not saved, so the chapter does not quote them; the extra run below saved its reads raw.
Each aec-eval run was -n 2 -seed 1 -traces over one suite. The runner starts a fresh copy of the fixture per trial, lets the model work through the loop of chapter 37 with the four tools, then runs the acceptance commands under bwrap at 4 GiB. The tail of each run’s stderr, with its request count (47 completions in all, under the bound of 72):
aec-eval: straylight-35b@default median rep 0: pass oracle pass: nothing expected; exec pass: status 0; exec pass: status 0
aec-eval: straylight-35b@default median rep 1: pass oracle pass: nothing expected; exec pass: status 0; exec pass: status 0
aec-eval: requests: straylight-35b 15
aec-eval: straylight-35b@default median-ambiguous rep 0: pass oracle pass: nothing expected; exec pass: status 0
aec-eval: straylight-35b@default median-ambiguous rep 1: pass oracle pass: nothing expected; exec pass: status 0
aec-eval: requests: straylight-35b 17
aec-eval: straylight-35b@default median-ruled rep 0: pass oracle pass: nothing expected; exec pass: status 0
aec-eval: straylight-35b@default median-ruled rep 1: pass oracle pass: nothing expected; exec pass: status 0
aec-eval: requests: straylight-35b 15
aec-eval report on each run directory printed a two-line table, and all three read the same shape:
straylight-35b@default * 2/2
straylight-35b@default median 2/2
(with median-ambiguous and median-ruled in the second line of their own tables). The six trial records of the three runs, which are committed (trials.jsonl beside each table), say:
| spec | rep | status | turns | calls | wall seconds |
|---|---|---|---|---|---|
median |
0 | pass | 7 | 11 | 173.6 |
median |
1 | pass | 8 | 11 | 162.0 |
median-ambiguous |
0 | pass | 10 | 12 | 134.2 |
median-ambiguous |
1 | pass | 7 | 10 | 123.2 |
median-ruled |
0 | pass | 7 | 11 | 207.9 |
median-ruled |
1 | pass | 8 | 11 | 198.6 |
Six trials, six passes, 47 completions. That is what happened and it is all these runs say: it is not a pass rate for this model, and not evidence about any other. A seventh trial, a separate run of the ambiguous spec with -sessions that follows the trace view, is described with it and brings the total to 54 completions.
The reviewer’s first read of a run is aec-trace view. This is the first trial of the clean spec, as it printed, durations included:
1 run median/straylight-35b@default/0 ok 173606ms prompt=19533 cached=15245 completion=1757 reasoning=0 stop=final turns=7 calls=11
2 turn 1 ok 21927ms
3 model_call - ok 21927ms prompt=1189 cached=0 completion=44 reasoning=0 request_hash=43a1b2619ba1 model=ornith-1.5-35b-a3b finish_reason=tool_calls
4 tool_call read_file ok 0ms tool=read_file call_hash=1919b85e5da1 result_kind=ok
5 turn 2 ok 5877ms
6 model_call - ok 5804ms prompt=1359 cached=1185 completion=86 reasoning=0 request_hash=1899ae952bbe model=ornith-1.5-35b-a3b finish_reason=tool_calls
7 tool_call execute_code ok 71ms tool=execute_code call_hash=dadeeaf2b9f7 result_kind=ok
8 approval execute_code ok 0ms decision=allow
9 turn 3 ok 10048ms
10 model_call - ok 10046ms prompt=1534 cached=1355 completion=152 reasoning=0 request_hash=814636e09316 model=ornith-1.5-35b-a3b finish_reason=tool_calls
11 tool_call read_file ok 0ms tool=read_file call_hash=0804c4285d64 result_kind=ok
12 tool_call read_file ok 0ms tool=read_file call_hash=ef54711e40c1 result_kind=ok
13 tool_call read_file ok 0ms tool=read_file call_hash=46a48005a5c2 result_kind=ok
14 tool_call read_file ok 0ms tool=read_file call_hash=d1bc90d7868c result_kind=ok
15 tool_call read_file ok 0ms tool=read_file call_hash=cc29d4058c81 result_kind=ok
16 turn 4 ok 74273ms
17 model_call - ok 74272ms prompt=3072 cached=1530 completion=975 reasoning=0 request_hash=169d01b936b3 model=ornith-1.5-35b-a3b finish_reason=tool_calls
18 tool_call write_file ok 0ms tool=write_file call_hash=fd488c1da621 result_kind=ok
19 tool_call write_file ok 0ms tool=write_file call_hash=1a6ee0ae2f82 result_kind=ok
20 turn 5 ok 41498ms
21 model_call - ok 17400ms prompt=4010 cached=3068 completion=200 reasoning=0 request_hash=6503d291eeed model=ornith-1.5-35b-a3b finish_reason=tool_calls
22 tool_call execute_code ok 24097ms tool=execute_code call_hash=5833f3c88345 result_kind=ok
23 approval execute_code ok 0ms decision=allow
24 turn 6 ok 8350ms
25 model_call - ok 7817ms prompt=4105 cached=4006 completion=123 reasoning=0 request_hash=1b2f1a1ac800 model=ornith-1.5-35b-a3b finish_reason=tool_calls
26 tool_call execute_code ok 532ms tool=execute_code call_hash=aec316998e21 result_kind=ok
27 approval execute_code ok 0ms decision=allow
28 turn 7 ok 11630ms
29 model_call - ok 11629ms prompt=4264 cached=4101 completion=177 reasoning=0 request_hash=7ff965a4be26 model=ornith-1.5-35b-a3b finish_reason=stop
totals: status ok stop final turns 7 model_calls 7 tool_calls 11 rejected 0 workers 0
usage: prompt 19533 cached 15245 completion 1757 reasoning 0 (distinct request_hash, model)
provider -: prompt 19533 cached 15245 completion 1757 reasoning 0
approval: allow=3
duration approval: n 3 total 0ms max 0ms
duration model_call: n 7 total 148898ms max 74272ms
duration run: n 1 total 173606ms max 173606ms
duration tool_call: n 11 total 24706ms max 24097ms
duration turn: n 7 total 173606ms max 74273ms
Seven model calls over seven turns and eleven tool calls. Turn 1 reads one file; turn 2 runs a command through execute_code (71 ms; each execute_code call has an approval row with decision=allow, three in all); turn 3 reads five files; turn 4 is the long one, 74 s for a 975-token completion, and it writes two files; turn 5 makes a 24 s execute_code call; turn 7 stops with a final message. Every result_kind is ok. The tree shows what the model did and how long it waited; it does not show the arguments of a call (a trace records call_hash, not the call), so which file turn 4 wrote is not in it.
The ambiguous spec. The expectation going in was that the model might read “handle even-length input appropriately” as the lower middle value and fail vet-test. In both reps it did not: both passed vet-test, whose shipped test asserts the mean of the two middle values for an even-length input, so both reps wrote a Median that returns the mean there. Rep 1’s final message says so (even length returns the average of the two middle values); rep 0’s final message is the single word Done., and its pass is the evidence. The two traces carry hashes, not arguments, so they cannot show the code. A third run of the same spec, aec-eval run -n 1 -seed 1 -traces -sessions, was made afterwards for exactly that (ruling P10-15; -sessions keeps the messages beside the trace). It ran without a wake, after /v1/models read the 35b loaded at 00:15:03Z on 2026-11-09 (UTC), with the raw response saved. It made 7 completions, so the capture’s total is 54 of the 72, and it passed too (7 turns, 10 calls, 153.5 s). It is a separate run of the same spec, counted below as a third rep, with the caveat that -seed 1 sends the same sampler seed as the first run’s rep 0 (the seed plus the rep number), so it is not a designed-independent draw even though its trajectory differs from rep 0’s; its record is committed beside the others. The session shows what the model did. It read AGENTS.md, listed the files, and in one turn read calc/calc.go, .spec/median_test.go, calc/calc_test.go, cmd/calc/main.go and go.mod. It then wrote calc/calc.go with this Median (apart from a sort import added to the import block, the rest of the file is the fixture’s):
// Median returns the middle value of xs sorted; an empty input returns
// ErrEmpty. When xs has even length, it returns the average of the two
// middle values. The input slice is not modified.
func Median(xs []float64) (float64, error) {
if len(xs) == 0 {
return 0, ErrEmpty
}
sorted := make([]float64, len(xs))
copy(sorted, xs)
sort.Float64s(sorted)
n := len(sorted)
mid := n / 2
if n%2 == 1 {
return sorted[mid], nil
}
return (sorted[mid-1] + sorted[mid]) / 2, nil
}
and ran the acceptance flow by hand, cp .spec/median_test.go calc/median_test.go && go vet ./... && go test ./..., then removed the copy. The model read the shipped test before it wrote a line. That is one run and cannot be generalised to the other two, whose traces do not say. It does show what the hash pin leaves open. The pin protects the grade and leaves the assertion readable: go test ./... does not compile a .spec/ directory, so the test’s assertion is in front of a model only if it reads the file or reproduces the cp, and this one read the file (the test’s name, TestMedianEvenAveragesTheMiddlePair, gives the answer to any read or search of .spec/). The spec was ambiguous, and the model was not reading the spec alone. Two reps cannot separate this from a model that prefers the textbook median: with the chapter’s derivation, a model that picks the lower median with probability passes twice with probability , the most likely of the three outcomes (0.49, against 0.42 for one failure and 0.09 for two).
The ruled spec. Both reps passed. The ambiguous spec passed too, so the capture shows no effect of the ruling. Rep 1 reports in its final message that it also added a median subcommand to cmd/calc/main.go, which the spec’s Non-goals rule out (No change outside calc/). The model did not simply ignore a non-goal: the fixture’s AGENTS.md, which the compiled task’s system line tells it to read first and follow, says “Change only files under calc/ and cmd/calc/”. The rule file and the spec disagree, and a spec has no precedence over the rule file in this format. The graders passed the change, because vet-test checks behaviour and not the diff. The one machine-read statement of the diff the spec accepts is allow: [calc/**], and what enforces it is chapter 54’s policy gate, which refuses a diff outside allow whatever AGENTS.md says; reconciling the two files is the human’s job.
The lab’s deterministic outcomes, from go test on straylight with scripted attempts, are the model-independent version of the same grading. The correct answer passes both graders of the clean spec:
oracle pass: nothing expected; exec pass: status 0; exec pass: status 0
The same attempt plus a rewrite of .spec/median_test.go fails on the hash line, and go never runs, while the cli grader still runs and passes:
oracle pass: nothing expected; exec fail: status 1: sha256sum: WARNING: 1 computed checksum did NOT match, want 0; exec pass: status 0
And the lower median, the reading the ambiguous spec allows, fails the ambiguous spec’s only test:
oracle pass: nothing expected; exec fail: status 1, want 0
The ruled spec passes the averaging answer. The model chose the mean in all three reps of the ambiguous spec; the script that chooses the lower median fails every time. The ambiguity is in the document, and the lint reports it either way. On this model, in these reps, it did not turn into a failure.
Exercises
(a) Add a marker class for “should” sentences to the lint’s vocabulary, and show one true positive and one false positive it produces on the book’s own specs and plans.
Answer
Add a disjoint alternative |(?i)\bshould\b to Markers (RE2 matches in linear time however the alternatives overlap; this one starts with the same letter as sensibl[ey] and is disjoint from it as a word). The three specs of the lab say nothing of the kind, so run it over the book’s own documents (grep -iw should finds it on 3 lines of the 2 specs and 163 lines of the 40 plans). A true positive is in the plan for this chapter: “neither should carry /tmp, but the detectors decide” (a trial detail and a path), a requirement phrased as a hope and handed to a second mechanism; a spec that said this would leave the model to guess whether a path in the output is a failure. A false positive is in the design document: “where a decision model should run”, the title of a discussion, not a requirement; the word asks a question the section then answers. The lint stays a lint because it sees a word and not the sentence’s work. A false positive costs a writer a re-read and a true one costs a model a guess, and that asymmetry is the case for flagging both.
(b) The reader’s repository with repo: .: the spec file is in the workspace the model edits. Say what the model can and cannot change about its own grading, and name what chapter 54’s protected globs must cover.
Answer
The suite is compiled before the run from the file the driver read: the request, the grader commands and their hashes are in the suite’s data, which the model never sees as a file. The workspace copy of the spec is data, and an edit to it changes nothing the run uses. The acceptance command’s hash is in the suite, not the workspace, so rewriting the shipped test fails the pin. What the model can change is every file that is not pinned and that the commands read: the other tests, a go.mod replace, a test helper the shipped test imports, or the command a Makefile target runs if an acceptance command calls one. The thing the protected globs must cover is therefore the files the acceptance commands read and the spec itself, so that a change touching them goes to the human whatever the tests say: the spec, .spec/**, and any build file an acceptance command executes.
(c) With the chance per rep that the model picks the lower median, give for a 99 % chance of seeing it once at , and say what this chapter’s two-rep capture can and cannot say about .
Answer
, so : and . Two reps see the lower median with probability if , so a clean pair is the likeliest of the three outcomes (0.64 clean, 0.32 one failure, 0.04 two) and says almost nothing: with no failures in two reps, the Wilson interval for (chapter 38’s default) runs from 0 to 0.66 and the Clopper–Pearson interval from 0 to 0.84. The capture’s ambiguous spec had a clean pair, and the session run of the same spec a clean third rep (with the same sampler seed as rep 0, so not an independent draw): zero failures in three reps gives upper limits of 0.56 (Wilson) and 0.71 (Clopper–Pearson). Nothing in this chapter shows that the model can pick the lower reading, and nothing shows that it cannot. A pair that did show the failure would show that the model can pick that reading, and still give no rate.
(d) Explain from chapter 43’s Limits why a C program that does nothing runs under RLIMIT_AS 512 MiB and go version does not, and what raising MemoryBytes to 4 GiB changes about the three tmpfs mounts and the scope’s MemoryMax.
Answer
RLIMIT_AS bounds the process’s virtual address space: mapped pages whether or not they were touched. A static C program maps a few hundred kilobytes. The Go runtime at start-up reserves address space for the page allocator’s summaries (arenas and their index) before it runs any Go, so the reservation alone needs more than the 512 MiB default allows, which is the message failed to reserve page summary memory and status 2 in 0.05 s. A tmpfs is limited by its own size, not by RLIMIT_AS, and chapter 43 sets that size from MemoryBytes: at 4 GiB each of the three mounts (/tmp, /var/tmp, /dev/shm) may hold 4 GiB of pages that the address-space limit does not count, 12 GiB in all. The scope’s MemoryMax is the same 4 GiB for the whole run, so under systemd-run it is the cgroup, not the tmpfs sizes, that stops a command filling all three. Raising one number moved the process limit, three tmpfs sizes and the cgroup cap together.
(e) Rewrite the ambiguous spec’s second Goal line so that no ruling is needed and the lint passes. Say what the ruled spec records that the rewrite loses.
Answer
“Add Median so that an even-length input returns the mean of the two middle values (vet-test).” It has no marker and names a test, so the lint finds nothing. The ruled spec keeps the original sentence and adds a line that records the date (2026-11-08), the why (it is the textbook median and what the shipped test asserts) and the cost if wrong (an attempt that returns the lower middle value fails vet-test): the ledger’s three parts. The rewrite keeps the decision and drops the history, so a later reader sees what the spec says and not that a sentence once said something else and was settled. The rewrite is the better spec; the ruling is the better record, and a spec that has been used accumulates both.
Lab
make lab CH=52 IMPL=mine runs go/labs/ch52 against your mine/task.go, which holds Task, a parsed spec compiled to one eval.TaskSpec; IMPL=ref runs it against spec.Document.Task. The parser, the lint, the fixture and chapter 37’s runner are the reference’s in both cases. The tests:
TestParseSpecs: the three specs parse;median.mdlints clean;median-ambiguous.mdgives exactly two problems, both on its second Goal line;median-ruled.md, which is the ambiguous one plus one Rulings line, gives none.TestTaskCompiles: the task’s grade is anallof the acceptanceexecgraders, its environment holds every fixture file and no.git, and its request has no front matter.TestFixtureInit: the fixture initialised twice gives one hash; a copy with a symlink is refused.TestSpecHashesCurrent: the hash in each spec’svet-testcommand is the SHA-256 of the committed.spec/median_test.go.TestAcceptanceRunsUnderSandbox,TestTamperedTestFailsandTestAmbiguousSpecFailsAsWritten: three scripted attempts, each a model that writes files withwrite_fileand saysdone, through chapter 37’s runner under this host’s sandbox. Where the backend does not isolate filesystem and network they skip, with the reason (the local backend here (...) does not isolate both filesystem and network; the acceptance tests do not run on the host), and never run on the host.
On straylight (2026-11-08, nice 19, in the dev shell) the package ran in 25.3 s: TestAcceptanceRunsUnderSandbox 25.25 s, TestAmbiguousSpecFailsAsWritten/lower 24.95 s and /ruled 24.49 s, and TestTamperedTestFails 13.08 s (go vet and go test never start on the pinned-hash failure; the 13 s is the cli grader’s build). The three run in parallel, so the package takes about as long as its slowest test; the rest of the tests take under 0.1 s.
The lab cannot see the model, since every attempt is a script, and it cannot see whether the spec is good, since the lint is a lint. The spec’s lab sentence says “one of the reader’s repos”. The fixture stands in for it; the reader’s own repository is the repo: . case of exercise (b), with chapter 54’s Allow and protected globs, a step to take after chapter 54.
Further reading
- C. A. R. Hoare, An axiomatic basis for computer programming, Communications of the ACM 12(10), October 1969. A specification as what a program must satisfy, stated before the program: the acceptance test is the same idea with an executable postcondition.
- Bertrand Meyer, Applying “design by contract”, Computer 25(10), October 1992. The contract as preconditions and postconditions that the client and the supplier both read. The acceptance test is the postcondition the agent can run.
- D. L. Parnas, On the criteria to be used in decomposing systems into modules, Communications of the ACM 15(12), December 1972. The interface as what a module hides, which is what the spec’s Interface section is for.
- David L. Parnas and Paul C. Clements, A rational design process: How and why to fake it, IEEE Transactions on Software Engineering SE-12(2), February 1986. Documentation written as if the design had been rational, which is what a spec with its rulings is.
- Frederick P. Brooks, No silver bullet: essence and accidents of software engineering, Computer 20(4), April 1987. Specification as the hard part of building software.
- Michael Nygard, Documenting architecture decisions, Cognitect blog, 15 November 2011. The decision record (context, decision, status, consequences); the ledger’s ruling line is one such record per line.
- AGENTS.md. The open format for a rule file read by coding agents; the fixture carries one.
- Xing Zhang et al., Guardrails Beat Guidance: A Large-Scale Study of Rules, Skills, and Persistent Configuration for Coding Agents, arXiv 2604.11088 (v2, 2026). Their finding is that every individually beneficial rule in their data is a negative constraint and every individually harmful one a positive directive; three of the fixture’s five
AGENTS.mdlines are prohibitions or restrictions, which is their finding applied and not a test of it here. - github/spec-kit at commit
c43849408ac0de2ca6a52f14eaae71449776057b. A spec-driven toolkit for coding agents, a contemporary of this chapter’s format and not a source of it.