Module: L3-M08 (capstone) · Duration: ~9 hours (estimate) · Previous: Milestone 1 · Next: Milestone 3
1. Introduction
The design from milestone 1 says what the framework will test. Milestone 2 builds the foundation for every later check: a harness that runs one scenario on one build with one seed, in a fresh sandbox, and returns a run record with the trace, the injected faults, the initial and final snapshots and the side-effect ledger. If the harness is wrong, every number of milestones 3 and 4 is wrong with it and nobody notices: a sandbox that accepts wrong arguments lets a "correct" check pass, a fault that never fires lets a reliability scenario pass without testing anything, a trace with a skewed clock makes the latency budget wrong.
You write five modules: scenario.py (reading and validating scenarios), sandbox.py (ten fake tools), trace.py (the Recorder, fault injection, lint), harness.py (running one scenario) and oracles.py
(end-state checks). The output is a working harness: the three example scenarios pass on stable on every seed, plus your first scenario.
2. Objectives
- Validate JSON scenarios with the error codes of
requirements.mdD1 and reject a bad spec instead of silently repairing it. - Implement an in-memory sandbox following the contract in
data/tools.json: argument checks, error codes as in the contract, no real side effects, idempotency keys, single-use approvals, an append-only side-effect ledger, snapshots that are deep copies. - Record each model step, tool call and wait as one event on a logical clock, and inject faults exactly as the scenario plans them.
- Run multi-session scenarios deterministically per (scenario, build, seed) and lint the record so that a broken harness or an edited file does not become evidence.
- Write end-state oracles that read the snapshots and the side-effect ledger, and write your first scenario.
3. Prerequisites
- Milestone 1 done:
deliverables/design.mdanddeliverables/explore-notes.md,tests/test_m1_design.pygreen. - Quick review: L3-M02-L01 and L3-M02-L03 (tool contracts, argument checks), L3-M02-L04 (fake tools, the effect log, idempotency keys), L3-M06-L02 (the side-effect ledger), L3-M01-L04 (traces, logical clock, trace lint), L3-M03-L04 (end state), L3-M06-L01 (fault injection), L3-M07-L04 (human approval).
requirements.mdsections D1 and D2 (the scenario schema, tool results, side-effect ledger, snapshots, fault injection, trace events, run record) and the docstring of each function instarter/agentqa/.- Two concepts reused from L3-M01-L04, in a different form: the logical clock (here the trace time is the sum of the
msof the earlier events, never the machine's clock) and trace lint (checking whether a finished record is consistent with itself). - Disambiguation. The capstone trace is a flat list of events, not the span tree of L3-M01-L04; it is close to the trajectory record of L3-M04-L01 and the conversation trace of L3-M07-L01. The side-effect ledger here has the meaning of L3-M06-L02 (only effects actually applied), unlike the effect log of L3-M02-L04, which records every call. The Recorder is the harness's
envobject: it records events and injects faults.
4. The parts of milestone 2
4.1 Scenarios are data: reject, do not repair
A scenario is a JSON file: who talks to the assistant (sessions), what the sandbox looks like at the start (setup), which faults fire (faults) and which checks decide pass or fail (checks). scenario.validate returns a list of error codes
and never repairs the spec: a scenario with duplicate claims must not have the duplicates dropped automatically, a count of True must not be treated as 1, an unknown patient must not be replaced with P01. The principle is the same as the
"reject, do not repair" rule for datasets in Level 2 (L2-M08-L02): every silent repair is an assumption nobody signed. Three rules that are easy to miss:
NO_WORLD_ORACLE: if every check only reads the reply (reply_contains,reply_not_contains), the scenario is rejected (R2). Theobservescolumn ofCHECK_SPECSinchecks.pysays what each check reads.BAD_CHECK:<j>also covers a check whosesessionorturnis outside the scenario's own range (sessioncounts from 0,turncounts from 1), and parameters of the wrong type or extra parameters according toCHECK_SPECS.load_dirrejects both files when two specs share an id (DUPLICATE_ID); keeping one of them is guessing which file is right.
A bad spec does not stop the pipeline: it goes into scenario_errors of results.json, and the milestone 4 gate HOLDs with the reason SCENARIO_ERRORS. A scenario that quietly disappears is a scenario nobody knows did not run.
4.2 A sandbox that follows the contract
World holds the clinic in memory and answers the ten tools according to data/tools.json. The contract is the source of every rule (L3-M02-L01): an unknown name is UNKNOWN_TOOL; a missing, extra or wrongly typed argument (strings only; True is not a string),
a value outside the enum or one that does not match the pattern over the whole string is BAD_ARGS; the other codes (NOT_FOUND, SLOT_TAKEN, ALREADY_CANCELLED, APPROVAL_REQUIRED, ...) are exactly those in the errors column of that tool.
Nothing leaves the process: send_sms only appends a line to outbox (R3, mandatory criterion M2 of the rubric).
Why must the sandbox be stricter than the demo environment of explore.py? Because if the sandbox still runs a call with wrong arguments, the scenario's result no longer says anything about the contract. OWASP advises checking permissions in the downstream system
instead of letting the LLM decide whether an action is allowed ("complete mediation") [R3]: in the capstone, that downstream system is your sandbox.
4.3 Idempotency, approvals, the side-effect ledger and copies
The four properties of R4, each of them a place a milestone 3 check will rely on:
- The idempotency key of
book_appointment: the same key with the same arguments returns exactly the previous result and books nothing more; the same key with different arguments isIDEMPOTENCY_CONFLICT(L3-M02-L04 §5.2, L3-M06-L02). - Single-use approval:
refund_depositonly runs with anapproval_idwhosestatusisgranted, for the right action, the right appointment, not yet used; after that it is markedused. Whenrequest_approvalmeets an approval that is granted and not yet used for the right appointment, it returns that approval and does not create a new request (L3-M07-L04). - The append-only side-effect ledger: each successful write that changes something appends an entry
{effect_id, tool, args, data, event}. An idempotent replay and arequest_approvalthat returns an existing approval append nothing.eventis the trace event index of the call: thanks to it, a check can go from an effect back to the call that caused it. - Deep copies:
snapshot(),ledger()and tool results are copies; a caller that edits them cannot change theWorld. Otherwise a check that accidentally edits a snapshot changes the result of the next check.
4.4 The Recorder: fault injection and the logical clock
The Recorder is the env object the assistant calls (product/README.md): call_tool, record_model, wait. Each call becomes an event {"i", "session", "turn", "kind", "t", "ms"} plus the fields specific
to each kind (requirements.md D2). The first event is at t = 0; each later event starts at t + ms of the previous event. There is no machine time anywhere in the trace, so the same (scenario, build, seed) gives the same record byte for byte (R20).
Faults are injected according to the scenario's plan: {"tool", "call", "kind"} means call number call (counting from 1, per tool name, over the whole run) of tool. Three kinds (L3-M06-L01):
| Kind | Reaches the sandbox? | The caller receives | The event's ms |
|---|---|---|---|
timeout |
no | {"ok": false, "error": "TIMEOUT"} |
timeout_ms (1000) |
unavailable |
no | UNAVAILABLE with retry_after_ms (300) |
unavailable_ms (20) |
timeout_after_commit |
yes, the write is applied | still TIMEOUT |
the contract's latency_ms plus timeout_ms |
The third kind is the most dangerous one for an agent: the work has happened but the caller thinks it has not. The Recorder records which fault fired at which event (fired) and which has not fired (unfired) (R5).
A fault that has not fired means the scenario does not test what it says: pipeline.run_record treats that record as a fail.
4.5 The harness and lint
harness.run_scenario(spec, version, seed, ctx) builds a fresh World from ctx["clinic"], applies setup, takes the initial snapshot, then creates the Recorder with the scenario's faults (and the policy's fault configuration), then creates one Assistant(version, seed) for the whole scenario, opens the sessions in the spec's order and sends the turns
in order. One assistant for the whole scenario is deliberate: it is how a multi-session scenario can test what happens between sessions (L3-M05-L04). Each turn has latency_ms (the sum of the ms of the turn's events),
cost (the sum of tokens_in + 3 × tokens_out over the model steps), model_steps, tool_calls. A product exception is recorded in error and makes the trial fail; it is never swallowed or skipped (R7).
trace.lint_trace checks the finished record and returns codes (requirements.md D2): event indices are consecutive (EVENT_INDEX), events have the right shape (BAD_EVENT; for tool events: result has an ok of type bool, args is an object, fault is null or a fault kind), the clock matches (CLOCK), sessions and turns exist (BAD_SESSION),
tools are in the contract (UNKNOWN_TOOL), every effect points back to a tool event with the same name (EFFECT_REF), every fired fault points to the right event and every event that carries a fault has a fired entry pointing at it (FAULT_REF), the numbers of each turn can be recomputed from the trace (TURN_TOTALS), and the two snapshots initial, final have the shape of D2 (SNAPSHOT).
Lint never raises: malformed input is NOT_A_RECORD. At milestone 4, the gate re-runs lint on each file, so a hand-edited file becomes TRACE_INVALID.
4.6 End-state oracles
oracles.py has five checks that read the world and two reply checks (R8). appointments counts a patient's booked appointments in the final snapshot that match every filter present (date, period, dentist) and compares with count;
appointment_status reads one appointment (missing is a fail); appointments_unchanged compares the initial and final snapshots; sms_count counts the messages in the outbox to the number in the patient's record; refund_count counts refunds.
Each check returns {"passed", "why", "evidence": {"events", "effects"}}: the evidence is event indices and effect ids, which milestone 4 will put into the report. A correct check with a vague why ("failed") still leaves the report's reader to go looking.
5. Hands-on: run a scenario and read the record
Create try_m2.py in the root of starter/, next to agentqa/:
import json
from agentqa import checks, harness, trace
from agentqa.util import context
ctx = context()
spec = json.load(open("scenarios/ex-01-book-morning.json", encoding="utf-8"))
rec = harness.run_scenario(spec, "stable", "s1", ctx)
for e in rec["trace"]:
extra = f"{e['tool']} ok={e['result']['ok']}" if e["kind"] == "tool" else (f"tokens {e['tokens_in']}+{e['tokens_out']}" if e["kind"] == "model" else "")
print(f"{e['i']:>2} t={e['t']:>4} +{e['ms']:>3} ms {e['kind']:5s} {extra}")
print("turn:", {k: v for k, v in rec["sessions"][0]["turns"][0].items() if k not in ("user", "reply")})
print("effects:", [(x["effect_id"], x["tool"], x["event"]) for x in rec["effects"]])
print("lint:", trace.lint_trace(rec, ctx["contracts"]))
for c in checks.evaluate(spec, rec, ctx):
print("check", c["index"], c["kind"], c["passed"], "|", c["why"], "|", c["evidence"])
Output (copied from a real run with the reference solution, 2026-11-05, Python 3.14.6 and 3.12.3 on Linux, identical):
0 t= 0 +301 ms model tokens 175+35
1 t= 301 + 40 ms tool get_patient ok=True
2 t= 341 +391 ms model tokens 205+35
3 t= 732 + 60 ms tool search_slots ok=True
4 t= 792 +314 ms model tokens 235+35
5 t=1106 +120 ms tool book_appointment ok=True
6 t=1226 +373 ms model tokens 265+35
7 t=1599 + 30 ms tool send_sms ok=True
8 t=1629 +346 ms model tokens 295+35
turn: {'latency_ms': 1975, 'cost': 1700, 'model_steps': 5, 'tool_calls': 4}
effects: [('E1', 'book_appointment', 5), ('E2', 'send_sms', 7)]
lint: []
check 0 appointments True | 1 booked appointment(s) of P02 match, expected 1 | {'events': [5], 'effects': ['E1']}
check 1 sms_count True | 1 SMS to P02, expected 1 | {'events': [7], 'effects': ['E2']}
check 2 reply_contains True | reply contains the text | {'events': [], 'effects': []}
Read it part by part. Clock: 0 + 301 = 301, 301 + 40 = 341, ... the last event starts at 1629 and lasts 346 ms, so the turn lasts 1975 ms. Cost: the sum of tokens_in is 175 + 205 + 235 + 265 + 295 = 1175, plus 3 × 35 × 5 = 525, giving 1700.
The ms of a tool event is the contract's latency_ms (40 ms for get_patient). Two effects, each pointing back to the event that caused it; get_patient and search_slots are reads, so they have no effect.
The reply check has no event evidence: it only reads text.
Then try four boundaries with try_m2b.py (same folder):
import json
from agentqa import harness, scenario
from agentqa.sandbox import World
from agentqa.util import context
ctx = context()
args = (ctx["policy"], ctx["clinic"], ctx["contracts"])
bad = {"id": "Demo_1", "title": "x", "suite": "end_state", "claims": ["C1", "C1"],
"sessions": [{"patient": "P09", "turns": ["xem lịch hẹn của tôi"]}],
"checks": [{"kind": "reply_contains", "session": 0, "turn": 1, "text": "A0001"}]}
print("validate:", scenario.validate(bad, *args))
w = World(ctx["clinic"], ctx["contracts"])
print("bad args:", w.call("search_slots", {"date": "2026-12-02", "period": "tối"}))
book = {"patient_id": "P02", "slot_id": "SL-1202-D1-0800", "idempotency_key": "k-1"}
first = w.call("book_appointment", book, event=5)
again = w.call("book_appointment", book, event=9)
print("book:", first["data"]["appointment_id"], "| replay:", again["data"]["appointment_id"], "| effects:", len(w.ledger()))
snap = w.snapshot()
snap["slots"]["SL-1202-D1-0800"] = "free"
print("slot after editing the snapshot:", w.snapshot()["slots"]["SL-1202-D1-0800"])
spec = json.load(open("scenarios/ex-03-search-unavailable.json", encoding="utf-8"))
rec = harness.run_scenario(spec, "stable", "s1", ctx)
print("faults:", json.dumps(rec["faults"], ensure_ascii=False))
for e in rec["trace"]:
if e["kind"] != "model":
print(e["i"], e["kind"], e.get("tool", ""), e["ms"], e.get("fault"), (e["result"].get("error") if e["kind"] == "tool" else ""))
Output (same run, same two Python versions):
validate: ['BAD_ID', 'BAD_CLAIMS', 'UNKNOWN_PATIENT', 'NO_WORLD_ORACLE']
bad args: {'ok': False, 'error': 'BAD_ARGS', 'detail': "period not in ['sáng', 'chiều']"}
book: A0006 | replay: A0006 | effects: 1
slot after editing the snapshot: booked
faults: {"planned": [{"tool": "search_slots", "call": 1, "kind": "unavailable"}], "fired": [{"fault": 0, "event": 3}], "unfired": []}
1 tool get_patient 40 None None
3 tool search_slots 20 unavailable UNAVAILABLE
4 wait 300 None
6 tool search_slots 60 None None
8 tool book_appointment 120 None None
10 tool send_sms 30 None None
The broken spec has four codes at once (upper case and an underscore in id, duplicate claims, an unknown patient, only a reply check): validate lists them all and does not stop at the first code. The replay with the same key returns the same A0006 and the ledger still has one effect.
Editing the snapshot cannot change the World. In ex-03, the unavailable fault fires at event 3 (20 ms), the assistant waits exactly the retry_after_ms of 300 ms and calls again, and unfired is empty.
Finally, run the milestone's tests:
python -m pytest tests/test_m2_scenario.py tests/test_m2_sandbox.py tests/test_m2_harness.py
With the reference solution, the last line is 77 passed in 0.22s (Python 3.14.6; 3.12.3 also 77 passed). The tests are part of the contract: when a test fails, read its body to learn the boundary it requires, then fix the code, not the test.
6. QA perspective
- What can go wrong: the sandbox accepts
Trueas a string or matchespatternpartially; the idempotency key is kept even when the first call failed; an effect is appended for a replay; a snapshot returns a reference instead of a copy; fault calls are counted per turn instead of over the whole run;time.time()is used in the trace; the harness catches the product's exception and returns a "clean" record; lint raises on malformed input. - What the harness does not simulate (level 3 of the rubric's
harness): no partial writes (a write either happens fully or not at all), no two concurrent requests, no real network latency, no real model. Write each limit into the design, with the reason it does not make the conclusions about the exercise's clauses C1-C11 wrong (and which clause it could make wrong if the product were real). - Your first scenario: pick a clause in the traceability table that the three examples do not touch yet (they touch C1, C3, C6, C10). Take the expectation from the clause and
data/clinic.json. Run it onstablewith all five seeds before trusting it.
7. Milestone 2 deliverable
- Code:
scenario.py,sandbox.py,trace.py,harness.py,oracles.py(the functions still markedTODO). - At least one scenario of your own in
scenarios/(the file name is the scenario id), next to the three examples, that passesscenario.validateand passes onstableon every seed. - Section 4 of the design updated if you changed your mind along the way (for example how error codes are assigned), and a paragraph "what the harness does not simulate".
Criteria: pass tests/test_m2_scenario.py, tests/test_m2_sandbox.py and tests/test_m2_harness.py (AC2.1-AC2.31), together with the no-network and no-key parts of tests/test_hygiene.py;
python try_m2.py gives an empty lint and every check of ex-01 passes.
8. Self-check questions
0/12 done · Results are kept in this browser only.
P02 · True or false
P03 · Fill in the blank
P04 · Select all that apply
P05 · Match
P07 · Put in order
P08 · Recall
Lesson: L3-M02-L04P09 · True or false
P10 · Essay
Level 3 of the rubric's harness: "you can state what the harness does not simulate and why that does not make the conclusions wrong". Write that paragraph (6-10 sentences) for your design.
P12 · Multiple choice
9. Summary
- Scenarios are data;
validatereturns error codes and repairs nothing; a bad spec shows up inscenario_errorsand does not disappear. - The sandbox follows the contract in
data/tools.json, keeps idempotency keys and single-use approvals, writes an append-only side-effect ledger and returns deep copies. - The Recorder injects faults per (tool, call) over the whole run, records the trace on a logical clock, and says which faults have not fired.
- The harness is deterministic per (scenario, build, seed); lint catches inconsistent records; end-state oracles return evidence as events and effects.
10. References
See this module's references.md.