A verifier that only checks that the output exists passes all 5 of our agent’s attempts. Only 2 are correct. Most of building a task is building its verifier.
Switch checks on and off. Watch the red rings, which mark wrong verdicts, and the agent’s pass rate below them. Then we build the rest piece by piece: the task folder, Docker, runs, trajectories, difficulty, fidelity and the five attempts.
You need some Python and a terminal. We build the rest from zero. Each chapter ends in a workbook block of exercises.
A lesson and workbook for Assignment 2 of Stanford CS 329Z: Engineering AI Agents (Fall 2026). John Yang designed and built the assignment, with feedback from Michael Ryan, Diyi Yang, Shreyas Sharma and Anantharaman Iyer. Starter repo: cs329z/assignment2-evals (MIT licence), with the handout inside. The toy task and every exercise here are our own. Nothing on this page solves a problem from the handout.
paid-totals and its seven candidate scripts are a toy made for this page. Each check runs the candidates for real in your browser. A filled letter marks a correct script.
Chapter 0
See the parts of a task, follow one run through them, and meet the toy task we use on every page
You build one task that a coding agent fails for a good reason. A task is a folder with four parts: a problem statement, a starting environment, a verifier that scores the agent’s work, and a reference solution. Harbor is the framework that runs it, Docker holds the environment, and the agent under test is mini-SWE-agent with Gemini 3.8 Flash.
| Part | File | Who reads it | Chapter |
|---|---|---|---|
| Instruction | instruction.md | The agent | 1, 6 |
| Environment | environment/Dockerfile | Docker, before the run | 2 |
| Run settings | task.toml | Harbor | 3 |
| Verifier | tests/test.sh | Harbor, after the agent stops | 7 |
| Solution | solution/solve.sh | The oracle run only | 4 |
The files never call each other. Harbor uses each one at a fixed stage of a run. Pick who runs the task and step through the five stages.
The lit line shows which file feeds the current stage. Try the hard-coder: it looks fine until stage 4.
An illustrative toy of a Harbor run on paid-totals. Stage 4 runs each script for real in your browser on a fresh CSV.
Every example and exercise here uses one small task of our own, paid-totals. It is too easy to use as a real benchmark, which is the point: it shows each idea in a few lines.
instructionWrite /app/totals.py. Run it as: python /app/totals.py <csv path>.
Print a JSON object that maps every customer to the total cents of their paid orders.
A customer with no paid orders maps to 0. Your script must work on any file in this format.
orders.csvcustomer,cents,status ana,1200,paid ben,500,refunded ana,300,paid cy,800,pending ben,700,paid # correct output: {"ana": 1500, "ben": 700, "cy": 0}
The common failure: the verifier reads the sample file the agent can see. Then a script that prints the sample answer as a constant scores 1. In the toy above, agent E does that, and only the fresh CSV at stage 4 catches it.
Chapter 1
Split a task into its four parts and see what breaks when one is missing
An agent gets one paragraph: total the paid orders. It lists files, reads the CSV, writes a script and runs it. Then it stops. Did it succeed? You need a fixed request, a fixed world and a fixed judge, or you cannot say.
| Part | In paid-totals | Its job |
|---|---|---|
| Instruction | The paragraph in Chapter 0 | Say what done means |
| Environment | A container with orders.csv and a stub totals.py | Give every attempt the same start |
| Verifier | Runs the script on a fresh CSV and compares totals | Turn the end state into a reward in [0, 1] |
| Solution | A correct reference script | Prove the task is solvable through that verifier |
The run that uses the reference solution in place of an agent is the oracle. Remove a part below and read what you lose.
The agent reads the instruction, acts in the environment, and the verifier scores the end state. The oracle path runs the solution through the same verifier.
This match is called task-verifier fidelity: the instruction states every behaviour the verifier checks, and the verifier checks every stated rule. List both sides for paid-totals.
Now add a check that keys come out sorted. The instruction never asks for that. A correct script that prints keys in file order now scores 0.
The failure: correct-looking attempts score 0. To measure it, list every check and find the sentence that states it. To fix it, state the rule in the instruction or delete the check.
stated lists what the instruction says. checked lists what the verifier tests. Return {unstated, unchecked} in that key order: unstated holds checks the instruction never states, unchecked holds stated rules that no check tests. Keep the input order.javascriptfunction fidelityGaps(stated, checked) {
const unstated = checked.filter(c => !stated.includes(c));
const unchecked = stated.filter(s => !checked.includes(s));
return { unstated, unchecked };
}
pythonunstated = [c for c in checked if c not in stated]
unchecked = [s for s in stated if s not in checked]
out = json.loads(run_script(fresh_csv))want = reference_totals(fresh_csv)assert isinstance(out, dict)assert list(out) == sorted(out)assert out == want
Chapter 2
Pin the environment so that your laptop, a friend and a CI server see the same world
Your oracle scores 1 on your MacBook. A friend runs the same folder and gets 0. Maybe their Python is newer, a library moved, or a file lived only in your home folder. Docker fixes this: each attempt runs inside a container, a closed workspace with a set operating system, set packages and set starting files.
| Term | What it is | Analogy |
|---|---|---|
| Dockerfile | The text recipe for the environment | A recipe card |
| Image | The built result; once built, it never changes | A frozen meal |
| Container | One running copy of an image; its changes stay inside it | One plate, heated up |
Each column builds the task on a different day. Switch on the pins and watch the oracle’s reward on each machine.
An illustrative toy. The three failure causes are the ones the handout names: a different OS, different versions, a missing file.
The example task’s Dockerfile pins its base image by digest, a hash of the exact image. Docker’s docs say a tag can move to a new image, but a digest always gives the same one.
dockerfileFROM python:3.12.16-slim-bookworm@sha256:e697c818... # tag + digest WORKDIR /app COPY humaneval_0.py /app/humaneval_0.py
The second pin is a real failure. The repo’s notes say Harbor installs mini-SWE-agent without pinning its dependencies. So each run could get a different litellm, and litellm 1.106.x crashes on import without mcp. So pinned_agent.py installs exact versions: mini-swe-agent 2.4.6 and litellm 1.105.7.
Two commands on our toy:
shelldocker build -t paid-totals environment/ # -t names the image docker run --rm -it paid-totals python --version # --rm deletes the container on exit # -i keeps input open, -t gives a terminal
The failure: the oracle passes for you and fails on a CI server. To measure it, build from a clean checkout on a second machine. To fix it, pin the base by digest and every package by version, and copy every asset in the Dockerfile.
FROM python:3.12.16-slim-bookworm@sha256:<digest>WORKDIR /appCOPY data/orders.csv /app/data/orders.csvCOPY totals.py /app/totals.pyRUN pip install pandas
pandas==X.Y.Z). Line 1 is pinned by digest.--rm, Docker removes the container when it exits.Chapter 3
Open each file of the example task and learn what it is for
Harbor gives the four parts a fixed layout on disk. Once your task has that layout, Harbor can start an agent attempt, run the verifier, and save the reward and the artifacts. The starter repo ships one example, tasks/humaneval-0/, a local port of a HumanEval problem.
Each file has the colour of its part. Tap a file, or step through with the arrows.
The roles are the handout’s own labels (section 3.1). The example notes describe the starter repo.
The example’s task.toml sets these run settings. Your task can change any of them.
| Table and key | Example value | Meaning |
|---|---|---|
[verifier] timeout_sec | 60.0 | Time the verifier may run |
[agent] timeout_sec | 600.0 | Time the agent may work: 10 minutes |
[environment] network_mode | "public" | The container’s network setting |
[environment] build_timeout_sec | 600.0 | Time the image build may take |
A Harbor task folder needs instruction.md, task.toml, tests/test.sh, solution/solve.sh and environment/Dockerfile. The Dockerfile can be left out if task.toml names a docker_image.
The failure: an attempt passes in two steps. To measure it, list what the image contains and read the trajectory for a file the agent should not have. To fix it, keep reference code with the solution or the tests, never in environment/.
timeout_sec = 60.0 under [verifier].FROM python:3.12.16-slim-bookworm@sha256:<digest>WORKDIR /appCOPY data/orders.csv /app/data/orders.csvCOPY totals.py /app/totals.pyCOPY reference_totals.py /app/reference_totals.py
instruction.md, task.toml, tests/test.sh, solution/solve.sh and environment/Dockerfile. The Dockerfile is optional when task.toml names a docker_image. Return the missing paths in that order, joined by commas, or "" if none.javascriptfunction missingFiles(paths, tomlText) {
const need = ["instruction.md", "task.toml", "tests/test.sh", "solution/solve.sh"];
if (!tomlText.includes("docker_image")) need.push("environment/Dockerfile");
return need.filter(p => !paths.includes(p)).join(",");
}
pythonneed = ["instruction.md", "task.toml", "tests/test.sh", "solution/solve.sh"]
if "docker_image" not in toml_text:
need.append("environment/Dockerfile")
missing = [p for p in need if not (task / p).is_file()]
Chapter 4
Run the oracle and an agent, read the job folder, and compare three benchmarks
Two runs come before any claim about your task. The oracle must score 1. An agent that does nothing must score 0. Then the real agent runs, and its reward means something.
shelluv run harbor run --path tasks/paid-totals --agent oracle \ --n-attempts 1 --n-concurrent 1 --job-name paid-totals-oracle \ --jobs-dir tasks/paid-totals/artifacts --yes uv run harbor view tasks/paid-totals/artifacts # browse the results
For a model run, swap --agent oracle for --agent-import-path pinned_agent:MiniSweAgent --model <MODEL> --env-file .env.
Pick who works, then press Run. The dot moves through the four stages of each attempt.
Toy runs on paid-totals with a faithful verifier. The five agent attempts are the hero’s five.
These files are a good map of a job:
<job-name>/result.json: present only if the job finished.result.json.verifier/reward.txt in each attempt: the reward.agent/trajectory.json in each model attempt: every step.| Benchmark | The agent gets | Checked by |
|---|---|---|
| HumanEval (2021) | One self-contained function to write | Unit tests on that function |
| SWE-bench Verified | A real GitHub issue and a snapshot of the repo | The project’s tests, run on the patch |
| Terminal-Bench 2.1 | Any job done in a terminal: admin, security, ML, data, science | Hidden tests on the container |
Harbor rates the Terminal-Bench example task as hard: about eight hours for an expert. The SWE-bench image is x86_64 only, so Apple Silicon needs export DOCKER_DEFAULT_PLATFORM=linux/amd64 first.
The failure: an attempt has no reward. The checker marks it, or warns that an attempt ended with an error. To measure it, open the attempt in harbor view. To fix it, make sure the cause is the agent, not your setup.
{reward}, where reward is a number or null when the verifier did not run. Return [attempts, passes, missing]: the trial count, the trials with reward 1 or more, and the trials with a null reward.javascriptfunction summarize(trials) {
const passes = trials.filter(t => t.reward !== null && t.reward >= 1).length;
const missing = trials.filter(t => t.reward === null).length;
return [trials.length, passes, missing];
}
pythonrewards = [trial_reward(t) for t in trials] # None when reward.txt is absent
summary = [len(rewards),
sum(r is not None and r >= 1 for r in rewards),
sum(r is None for r in rewards)]
Chapter 5
Label each step of an agent run and count where the effort went
A reward is one number. A trajectory is the full record of the run: each action and what came back. The agent, mini-SWE-agent, has a single bash tool, so every action is one shell command. Read the commands and you see how the agent worked.
Each block is one step, coloured by its label. Drag through the run and watch the counts.
A toy run of our own on paid-totals, not an assignment trajectory.
Label each step with four rules, in this order. A write to a file is an edit. A python command is a run. A look such as ls or grep is an inspect. The rest is other.
| Label | Steps | Count |
|---|---|---|
| inspect | 1, 2, 3, 7 | 4 |
| edit | 5, 8, 10 | 3 |
| run | 4, 6, 9, 11 | 4 |
| other | 12 | 1 |
The first edit, step 5, marks the switch from exploring to building. Step 6 prints a wrong total for ben. Step 7 looks at the data again, and step 8 fixes the filter. That run, look, fix loop is the multi-turn work a good task asks for.
Make three figures. For each, say what you measured, how you computed it and what you conclude. Your labels are a choice, so the rule goes in the caption.
The failure: a figure nobody can read without the raw files. To measure it, show the figure alone to a classmate. To fix it, name the unit, the rule and the run on each axis.
printf ... > /tmp/t.csv. Under our four rules, which label does that step get?sed -i or has a > that starts a word; (2) run if it starts with python; (3) inspect if its first word is ls, cat, head, tail, wc, grep or find; (4) other. Return the counts as [inspect, edit, run, other].javascriptfunction effort(cmds) {
const look = ["ls", "cat", "head", "tail", "wc", "grep", "find"];
const n = [0, 0, 0, 0];
for (const c of cmds) {
if (c.startsWith("sed -i") || /(^|\s)>/.test(c)) n[1]++;
else if (c.startsWith("python")) n[2]++;
else if (look.includes(c.split(" ")[0])) n[0]++;
else n[3]++;
}
return n;
}
pythonLOOK = {"ls", "cat", "head", "tail", "wc", "grep", "find"}
def label(cmd):
if cmd.startswith("sed -i") or re.search(r"(^|\s)>", cmd): return "edit"
if cmd.startswith("python"): return "run"
if cmd.split(" ")[0] in LOOK: return "inspect"
return "other"
grep python requirements.txt a run. Click the line at fault.function category(cmd) { if (cmd.startsWith('sed -i') || /(^|\s)>/.test(cmd)) return 'edit'; if (cmd.includes('python')) return 'run'; if (LOOK.includes(cmd.split(' ')[0])) return 'inspect'; return 'other';}
cmd.startsWith('python').Chapter 6
Tell a failure that measures a skill from a failure that measures a defect
Five attempts fail. That is good news only if each one failed for lack of the skill you meant to test. The handout counts a failure as evidence of difficulty only when the task is well specified, solvable, and failed for a reason tied to the capability.
The requirements, in short:
Read each report from a paid-totals run. Decide: did the agent lack the skill, or is the task at fault?
We invented the six reports for this page. The handout warns against ambiguity, hidden assumptions, contrived constraints and fragile infrastructure.
| Version | Why the agent fails | Verdict |
|---|---|---|
| v1: “Sum each customer’s orders.” | Counts refunds, because nothing says not to | Defect: ambiguous |
| v2: orders spread over monthly files, a README defines each status | Reads one file, or never opens the README | Capability: exploration |
Both versions fail often. Only v2 fails for the right reason, so only v2 tells you something about the agent.
The failure: all five attempts stall on the same unclear sentence. To measure it, mark where each trajectory first leaves the path you meant. To fix it, rewrite that sentence and keep the hard part.
# Paid totalsWrite /app/totals.py. Run it as: python /app/totals.py <csv path>.Print a JSON object that maps every customer to the total cents of their paid orders.A customer with no paid orders maps to 0.The tests use /tests/fresh.csv; its answer is {"gus": 500, "hal": 50}.Your script must work on any file in this format.
head away. That is the skill the task tests, so the failure counts.Chapter 7
Feed your verifier wrong and right answers on purpose, and count its two kinds of error
A verifier can be wrong in two ways. A false pass gives reward 1 to a wrong answer. A false fail gives 0 to a right one. The handout asks you to test incorrect and incomplete solutions, and correct ones that differ from your oracle.
Write each shortcut as a small script, then run it through the verifier. Each such wrong script is a mutant. A test input that makes a mutant fail kills it.
Rows are the seven candidates; columns are test inputs. Add inputs until every wrong row fails, then try exact text.
Every verdict comes from running the toy candidates on the four CSV files in your browser.
In the hero, a verifier that checks only that output exists passes all 5 attempts. Two are correct. So the overstatement is (5 − 2) ⁄ 2 = 1.5: the score is 150% too high. Switch on the fresh-file check and it falls to 0.
pythondef verify(stdout, want): # want: the totals for a CSV made at verify time try: out = json.loads(stdout) except json.JSONDecodeError: return 0 # a crash is a fail, not an error in the verifier return int(isinstance(out, dict) and out == want) # dict equality ignores key order
The failure: a correct script fails because its spaces differ from the oracle’s. To measure it, write a second correct solution in another style. To fix it, compare the parsed values, not the text.
stdout parses as a JSON object with exactly the keys of want and the same values, else 0. Key order and spaces must not matter. Text that is not JSON returns 0 and must not throw.javascriptfunction verify(stdout, want) {
let out;
try { out = JSON.parse(stdout); } catch (e) { return 0; }
if (out === null || typeof out !== "object" || Array.isArray(out)) return 0;
const a = Object.keys(out), b = Object.keys(want);
if (a.length !== b.length) return 0;
return b.every(k => out[k] === want[k]) ? 1 : 0;
}
pythondef verify(stdout, want):
try:
out = json.loads(stdout)
except json.JSONDecodeError:
return 0
return int(isinstance(out, dict) and out == want) # dict equality ignores key order
truth[i] says whether candidate i is correct. verdict[i] says whether the verifier passed it. Return [falsePasses, falseFails].javascriptfunction errors(truth, verdict) {
let fp = 0, ff = 0;
truth.forEach((t, i) => {
if (!t && verdict[i]) fp++;
if (t && !verdict[i]) ff++;
});
return [fp, ff];
}
#!/bin/bashset -uo pipefailcd /testspython check.pyecho 1 > "$REWARD_FILE"
if python check.py; then echo 1; else echo 0; fi.{} scores 1. Click the line at fault.def check(out, want): if not isinstance(out, dict): return 0 for name in out: if out[name] != want.get(name): return 0 return 1
want, or compare the two dicts.Chapter 8
Read two passes in five as a wide range, and see how luck moves the count
You run five attempts together and keep every artifact, not only the good ones. Anyone who reruns five fresh attempts with the same agent, model and settings should see a similar count.
A common target for a hard task is at most two passes in five. But five is a small sample. Pick a true pass rate and see how often luck lands on each count.
Bars show the chance of each pass count. The shaded bars meet the “at most two” target. The ruler shows the interval for the count you observed.
Binomial chances and the 95% Wilson interval, computed live. The model treats attempts as independent.
The Wilson interval gives a range of true pass rates that fit an observed count. It behaves well for small n and for counts near 0 or n.
So two in five fits an agent that solves the task one time in eight, or three times in four. It shows the task is not easy. It cannot give a precise rate, and it never says why attempts failed. The trajectories say that.
The failure: you rerun until you see two passes. To measure it, count every run you made. To fix it, run all five together once and report all five, as the handout asks.
[lo, hi], the 95% Wilson interval for k passes in n attempts, with z = 1.96. Use the form in the equation above.javascriptfunction wilson(k, n) {
const z = 1.96, d = n + z * z;
const c = (k + z * z / 2) / d;
const h = (z / d) * Math.sqrt(k * (n - k) / n + z * z / 4);
return [c - h, c + h];
}
pythondef wilson(k, n, z=1.96):
d = n + z * z
c = (k + z * z / 2) / d
h = z / d * math.sqrt(k * (n - k) / n + z * z / 4)
return c - h, c + h
Chapter 9
Audit a verifier with the sanity suite, run the checklist, and keep the numbers on one page
Before you trust a task, audit it. That holds for your own task and for one from a public benchmark. The audit is a sanity suite: a list of scripts, each with the reward the verifier must give it.
Pick a verifier. Each row runs one script for real and compares the reward with the one it must get. Find the verifier with no red row.
The seven scripts are the toy candidates from the hero, run in your browser. Each verifier adds checks to the one before it.
.env, and .env is never committed.| Term or number | Meaning |
|---|---|
| Oracle | The run that uses the reference solution; it must score 1. |
| Verifier | The code that turns the end state into a reward in [0, 1]. |
| False pass, false fail | A wrong answer scored 1; a right answer scored 0. |
| Fidelity | Instruction and verifier describe the same task. |
| Trajectory | Every action of a run and what came back. |
| Digest | A hash that names one exact image. |
| At most 2 of 5 | The hard-task target: the agent passes at most two of five attempts. |
| 11.8% to 76.9% | The 95% Wilson interval for 2 passes in 5. |
pythondef sanity(run_task): # run_task(agent) -> reward in [0, 1] assert run_task("oracle") == 1 # solvable through the same verifier assert run_task("do-nothing") == 0 # the starting state earns nothing for shortcut in ["hard-code", "drop-edge-case", "skip-rule"]: assert run_task(shortcut) == 0 # every mutant dies assert run_task("other-correct-style") == 1 # no false fail def wilson(k, n, z=1.96): # k passes in n attempts d = n + z * z c = (k + z * z / 2) / d h = z / d * math.sqrt(k * (n - k) / n + z * z / 4) return c - h, c + h # wilson(2, 5) = (0.118, 0.769)
Summary: tests whether an agent can total paid orders from a CSV it must inspect.Fidelity gap: tests/test_outputs.py never runs the script on a new file.Evidence: attempt 4 prints the sample totals as a constant and still scores 1.Strongest aspect: the sample file shows every status code.Improvement: make the task better and harder.
Now press Present or Teach. Explain from memory: the four parts of a task, why Docker pins, the oracle and do-nothing pair, the two verifier errors, and what two in five can say. Then go back to the hero and find the smallest set of checks with no red ring.
This page teaches the skills behind Assignment 2 of Stanford CS 329Z, Engineering AI Agents (Fall 2026), taught by Diyi Yang, Michael Ryan and John Yang. John Yang designed and built the assignment, with feedback from Michael Ryan, Diyi Yang, Shreyas Sharma and Anantharaman Iyer. It uses the MIT licence and lives in cs329z/assignment2-evals, which holds the handout. The benchmarks are from Chen et al. (HumanEval), Jimenez, Yang et al. (SWE-bench) and Merrill, Shaw et al. (Terminal-Bench). The toy task, the devices and the exercises are ours. The assignment is still open, so this page holds no solution and no write-up answer.