Module: L3-M04 · Duration: ~120 minutes (estimate, including the independent exercise) · Previous: L3-M03-L04 (end-state verification in the environment) · Next: L02
1. Introduction
Module L3-M03 grades an agent by the end state and ignores the path. Two runs with the same end state can be very different: one checks the book before borrowing it, the other borrows blindly and is lucky. To grade the path you first have to record it, well enough for people and programs to read, and without keeping what must not be kept.
This lesson opens module L3-M04 with the data unit of the whole module: the trajectory record of one run. You will read the records of twelve simulated agents on six ThuVien Mini tasks (a fictional product), run a lint that separates errors of the record from things worth looking at in the record, and redact secrets before storing. The agents in the lab are simulated programs written by the lab author; no model, network or API is called.
2. Learning objectives
- Name the fields of a trajectory record in the lab and the reason each field is kept. Read: §4.1.
- Explain why the record is written by the harness, not told by the agent. Read: §4.1, §5.1.
- Run
lint_traceand tell apart an error (the record cannot be used as a record) from a warning (a correct record of something worth a look). Practice: §8.2 (parts B, C), §8.3 (lines 1 to 3). - Redact secrets and private arguments with
redactand state its blind spots. Practice: §8.2 (part D), §8.3 (line 7). - State what the lint cannot check, including that a forged but consistent record passes it. Practice: §8.3 (line 5). Read: §6.1.
- Predict the error codes of five records and the places that get redacted. Practice: §9.
3. Required knowledge and tools
- L3-M03-L01 (end state, oracle), L3-M02-L04 (the fake tool layer and the statuses
applied,failed,rejected,denied,blocked,duplicate,dry_run), L3-M01-L02 (stop reasons), L3-M01-L04 (trace, redaction). Code labcode-labs/l3-m04, onlypytestneeded. The lab copies the files it needs from the L3-M02 and L3-M03 labs and imports from neither. - Separating the meanings. A trajectory in this module is the ordered list of the steps of one run: each step has a thought, an action (a tool call or the final answer), the observation the tool layer returned, a status, a time and a cost. It differs from the trace of L3-M01-L04 (an OpenTelemetry-style span tree), from the call history that the L3-M03 oracle reads (calls only) and from the effect log of L3-M02-L04 (what the tool layer changed). Anthropic's article uses transcript, trace and trajectory as three names for the same thing: the complete record of a trial [R1]; the lab keeps one name, trajectory. The harness is the program that runs the agent and writes the record (
lab/runner.pyin the lab). - The old policy still stands: offline, fake tools in a temporary sandbox, no model call. The lint and the redaction only flag and fix a copy; a person decides whether a record may be used, stored or shared.
4. Concept explanations
4.1 What a trajectory record holds, and who writes it
The lab's record has the schema thuvien.trajectory/1. At the top level: run_id, task_id, agent (to join the record with the task and the agent), steps, stop_reason, final_answer and totals. Each step has eight fields: index, thought, action, observation, status, t_start, t_end, cost. The constant WHY in lab/trace.py gives the reason for keeping each field:
index: the order of the steps is part of the behaviour being graded (L02 compares order).thought: the agent's stated reason; useful to a step judge (L03) and to a reader, but a claim, not evidence.action.tool,action.arguments: what the agent asked for, kept as the exact JSON text the agent sent. A parsed copy would hide broken JSON.observation,status: what the tool layer did with the request. Arejectedcall never counts as done.t_start,t_end,cost: for efficiency (L04), in ticks and cu (made-up units).stop_reason,final_answer: a run stopped bymax_stepsdid not finish, whatever its last message says.
Who writes the record matters as much as what it holds. In the lab, runner.run calls agent.decide(copy_of_the_steps), passes the action to the tool layer, then itself records the status and observation the tool layer returned. The agent only sees a deep copy, so it cannot edit the record. The agent's own account ("I checked B001") sits in thought or final_answer: data to compare, not truth.
The sources read on 2026-11-04 point the same way. Anthropic's article defines a transcript as the complete record of a trial (outputs, tool calls, reasoning, intermediate results), calls the infrastructure that runs tasks, records all the steps and grades them the evaluation harness, and advises reading the transcripts of many trials, because without reading them you cannot know whether the graders work [R1]. τ-bench describes polishing the instructions for its simulated user by examining the trajectory of trial runs [R2].
4.2 Errors are not warnings, and what must not be kept
lint_trace(record) returns findings {code, where, level}. Level error means the record cannot be used as a record (a missing field, a wrong order, time running backwards, fields that contradict each other, a string that looks like a secret token). Level warn means the record is correct but records something worth a look: the agent sent an unknown tool or broken JSON and the record rightly says rejected (CALL_UNKNOWN_TOOL, CALL_BAD_ARGS), hidden characters (HIDDEN_CHARS), or a call with no thought (NO_THOUGHT).
The line between the two levels is the question "whose fault is it". Agent junk_calls sends broken JSON: that is the agent's fault, and the record tells it truthfully, so it is only a warning. If the same call were recorded as applied, the record would lie about the tool layer, so it is the error STATUS_MISMATCH. The L05 evaluator does not measure a record with an error: it raises TRACE_INVALID and stops there.
What must not be kept is the second job. redact(record) returns a new record (the input is deep-copied and never changed) in which token-shaped strings (tok_, sk_ or key_, then, right after the underscore, at least 8 contiguous letters or digits) become [SECRET] in thoughts, answer texts, observation contents, final_answer and every string inside the arguments (nested objects and lists included, with a place such as steps[0].action.arguments.meta.note), private arguments (in the lab, the message of send_notice, text addressed to a student) become [REDACTED], and observation contents longer than 200 characters are cut, with a redactions list of places and rules. Student ids are kept, because the evaluator needs them to know whether a loan went to the right person; a real system would replace them with keyed pseudonyms, which the lab does not do. The price: a redacted record cannot be replayed exactly. This redaction differs from the one of L3-M01-L04: a different pattern (there sk- with a hyphen, e-mail addresses and bearer tokens), here only the matching part becomes [SECRET] (there the whole string becomes [REDACTED]), and here there is no rule by key name (a key named password is not hidden by itself). A step that is not an object, or steps that is not a list, is left as it is for the lint to report; a record that is not an object makes redact raise ValueError.
5. Technical deep dive
5.1 lab/runner.py and lab/trace.py
runner.run(agent, layer, task_id=..., agent_name=..., max_steps=12) runs at most 12 steps. An invalid action or an agent that raises gives a policy_error step and stops; a final answer gives a final step and stops; a tool call goes through ToolLayer.call and the step gets exactly the tool layer's status, code, content, structured, cost. Time follows the TICKS table (get_book 1 tick, borrow_book 2 ticks); a call stopped before the tool body (rejected, denied, blocked) and the final answer take 1 tick. build_record follows the same rule: an applied, failed, duplicate or dry_run call takes the tool's ticks. After 12 steps without an answer, stop_reason is max_steps and final_answer is None.
lint_trace(tr, tool_names=None, require_redacted=False) never raises, even when tr is garbage (NOT_A_TRACE, or BAD_STEPS on an unexpected exception). The main checks: MISSING_FIELD, BAD_ID (an id that is not a non-empty string), BAD_ORDER (index other than 1, 2, 3...), BAD_TIME (time going down), STEP_AFTER_END, STATUS_MISMATCH (a step status that differs from the observation's, or a call to an unknown tool or with broken JSON recorded as anything but rejected and denied), BAD_COST, STOP_MISMATCH (stop_reason, the last step and final_answer disagree), TOTALS_MISMATCH and SECRET_IN_TRACE. With require_redacted=True, a private argument kept verbatim is UNREDACTED_PRIVATE.
build_record(run_id, task_id, agent, calls, final=None) builds a well-formed record by hand from a compact list, for tests and exercises. It runs nothing: the status of each call is what you declare. A hand-built record is test data, not evidence about an agent.
6. QA perspective
6.1 What the record, the lint and the redaction do not say
- The lint checks shape and internal consistency, not truth: change the student in the arguments while keeping every other field consistent and the lint stays clean (§8.3, line 5). Protecting records from edits is the job of the store.
thoughtis what the agent says about itself. Evidence that the agent checked is aget_bookcall with anavailableobservation, not the sentence "I checked". L03 shows that self-praise can push a judge's score up.- The redaction knows one shape of secret. "password hunter2" is not redacted (§8.3, line 7). Redacting before storing and reading back with the lint are two layers; neither is enough alone.
- An unfinished run (
max_steps) is still a valid record: the lint reports no error, because the record tells the truth. Flagging "not finished" is the evaluator's job (L05, flagUNFINISHED). - τ-bench notes that a reward of 1 (the right final database, an answer with all the needed information) can be a necessary but not sufficient condition: the agent might issue a return without explicit user confirmation, which violates the policy [R2]. A failure like that is only visible in a record of the steps.
7. Real-world scenarios
Scenario 1 (fictional): "A record nicer than the truth". A colleague changes the harness so that every tool-call step is recorded as applied, "to keep it tidy". The lint reports STATUS_MISMATCH for the three broken-JSON calls of junk_calls instead of the warning CALL_BAD_ARGS. Had the harness also replaced the broken text with {} and edited the observation, the lint would stay silent; so QA keeps the rule in WHY: store the text the agent sent, the status belongs to the tool layer.
Scenario 2 (fictional): "The desk code in a thought". A simulated agent writes the library desk's access code into thought on a task that sends a notice. The lint reports SECRET_IN_TRACE, and with require_redacted=True also UNREDACTED_PRIVATE. QA runs redact, checks again with the lint before putting the record in the shared store, and tells the owner, who decides whether to change that code.
8. Hands-on tutorial
8.1 Setup
cd academy-content/code-labs/l3-m04
python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest # 125 passed
8.2 Run the demo
python -m lab.demo l01
Output (copied from a real run on Python 3.14.6 and 3.12.3 (Linux), 2026-11-04; both versions give identical output). Every agent is simulated:
A. the record of t01/diligent: stop_reason=final totals={'steps': 4, 'cost': 5, 'ticks': 5}
1 [0-1] 1cu applied: get_book {"book_id": "B001"}
2 [1-3] 2cu applied: borrow_book {"book_id": "B001", "student_id": "S0042", "idempotency_key": "loan-s0042-b001"}
3 [3-4] 2cu applied: save_note {"name": "loan_s0042", "text": "B001"}
4 [4-5] 0cu final: final 'Done: lent B001 to S0042; note loan_s0042 saved.'
B. lint of the 72 recorded runs: errors=0 warnings={'CALL_BAD_ARGS': 18}
C. lint of broken copies of that record
observation removed: errors=['MISSING_FIELD', 'MISSING_OBSERVATION'] warnings=[]
two steps swapped: errors=['BAD_ORDER', 'BAD_TIME'] warnings=[]
unknown tool recorded as applied: errors=['STATUS_MISMATCH'] warnings=[]
non-JSON arguments recorded as applied: errors=['STATUS_MISMATCH'] warnings=[]
zero-width space in a thought: errors=[] warnings=['HIDDEN_CHARS']
token pasted into a thought: errors=['SECRET_IN_TRACE'] warnings=[]
stop reason edited: errors=['STOP_MISMATCH'] warnings=[]
cost total edited: errors=['TOTALS_MISMATCH'] warnings=[]
D. redaction of t05/diligent with a token pasted into a thought
before: ['SECRET_IN_TRACE', 'UNREDACTED_PRIVATE']
redactions=[('steps[1].thought', 'secret'), ('steps[3].action.arguments.message', 'private')]
after: [] notice arguments={"student_id": "S0042", "message": "[REDACTED]", "idempotency_key": "notice-s0042-b001"}
input unchanged: True
Reading the output: part A is the record of diligent on t01: three calls and a final answer, 5 cu, 5 ticks ([1-3]: from tick 1 to tick 3). Part B: 72 records (12 agents times 6 tasks) with no error; the 18 CALL_BAD_ARGS warnings are the three broken-JSON calls of junk_calls on each task, correctly recorded as rejected. Part C: each broken copy gives its own code; an unknown tool and broken JSON recorded as applied are the errors. Part D: before redaction there are two errors; after it, the thought of step 2 (steps[1]) loses the token and the notice message becomes [REDACTED], while the student id and the idempotency key are kept; the original record is unchanged.
8.3 Try it yourself
Save as try_l01.py in the lab's root folder (next to lab/, not inside lab/), run python try_l01.py, then delete the file:
import copy
from lab import data, evaluator as V, trace as T
task = data.load_tasks()[0]
junk = V.run_task(task, "junk_calls")["trajectory"]
print(junk["stop_reason"], junk["totals"], [s["status"] for s in junk["steps"]])
print(sorted({(f["code"], f["level"]) for f in T.lint_trace(junk)}), len(T.lint_trace(junk)))
loop = V.run_task(task, "looper")["trajectory"]
print(loop["stop_reason"], loop["final_answer"], loop["totals"]["steps"], T.errors(T.lint_trace(loop)))
hand = T.build_record("h1/hand", "t01", "hand", [
{"tool": "get_book", "args": {"book_id": "B001"}},
{"tool": "borrow_book", "args": {"book_id": "B001", "student_id": "S0042", "idempotency_key": "k-1"}, "cost": 2}], "Done.")
print(hand["totals"], T.lint_trace(hand))
forged = copy.deepcopy(hand)
forged["steps"][1]["action"]["arguments"] = '{"book_id": "B001", "student_id": "S0099", "idempotency_key": "k-1"}'
print(T.lint_trace(forged))
cheat = copy.deepcopy(hand)
cheat["steps"][1]["status"] = "failed"
print([f["code"] for f in T.lint_trace(cheat)])
leak = copy.deepcopy(hand)
leak["steps"][0]["thought"] = "Login: password hunter2, key_ABCD1234EFGH."
red = T.redact(leak)
print(red["steps"][0]["thought"], red["redactions"])
Output (Python 3.14.6 and 3.12.3, Linux, identical):
final {'steps': 4, 'cost': 3, 'ticks': 4} ['rejected', 'rejected', 'rejected', 'final']
[('CALL_BAD_ARGS', 'warn')] 3
max_steps None 12 []
{'steps': 3, 'cost': 3, 'ticks': 4} []
[]
['STATUS_MISMATCH']
Login: password hunter2, [SECRET]. [{'where': 'steps[0].thought', 'rule': 'secret'}]
Reading: line 1: junk_calls sends three calls, all rejected, then answers "Done"; stop_reason is final although nothing was done, and the three broken calls still cost 3 cu. Line 2: three warnings, no error. Line 3: looper runs all 12 steps, stop_reason is max_steps, there is no answer, and no lint error: the record truthfully tells an unfinished run. Line 4: the hand-built record has three steps (two calls and the final answer) and a clean lint. Line 5: the student changed to S0099 in the arguments, every other field unchanged: the lint stays clean (a forged but consistent record). Line 6: the step status changed without the observation: STATUS_MISMATCH. Line 7: the key_-shaped token is redacted, "password hunter2" is not.
8.4 Run the lesson tests
python -m pytest tests/test_l01_trace.py -v
Result: 37 passed. Read test_a_rejected_call_is_recorded_as_rejected_with_its_raw_text, test_a_consistent_forgery_passes_the_lint, test_redaction_keeps_ids_and_misses_other_secret_shapes and test_the_agent_cannot_rewrite_the_record. The tests run on values in memory and one temporary folder.
8.5 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
ModuleNotFoundError: lab when running try_l01.py |
The file is inside lab/ or run from another folder |
Put the file next to lab/ and run from the lab's root folder |
The lint reports STATUS_MISMATCH for a record you edited |
You changed the step status but not observation.status, or recorded a broken call as applied |
Change both fields, or rebuild with build_record |
redact misses a secret |
The secret is not shaped tok_, sk_, key_ plus at least 8 contiguous letters or digits right after the underscore |
That blind spot is pinned by a test; tell the owner, do not assume the record is clean |
9. Independent exercise
Problem: Five fictional records of task e1 (student S0077): one written by the harness, three edited, one built by hand. Read them like a reviewer: which are broken and how, and what redact will hide.
Requirements: complete exercises/test_l01_trace.py:
- TODO 1:
ERRORS: for each record, the sorted list of error codes (warnings left out) thatlint_tracereturns. Write your prediction before running. - TODO 2:
REDACTIONS: forr1/diligentandr4/hand, the list of(where, rule)pairs thatredactreports, in order.
Test data: exercises/ex_traces.json.
Deliverable: the two variables above, in the file exercises/test_l01_trace.py itself.
Acceptance criteria: python -m pytest exercises/test_l01_trace.py passes (2 tests), recomputed with lab.trace. The test does not check whether a record tells the truth.
Hints: TODO 1: walk the list of checks in §5.1; a warning is not an error. TODO 2: redact walks the steps in order, and within a step the thought, the action, the arguments, then the observation.
10. Knowledge check
0/8 done · Results are kept in this browser only.
P02 · True or false
P04 · Select all that apply
P05 · Spot the bug
A colleague writes their own redaction. After calling my_redact(record), the original record in the store has lost its token too, and nobody knows which places were redacted. Find the defect.
from lab import trace as T
def my_redact(tr):
for s in tr["steps"]:
if isinstance(s.get("thought"), str):
s["thought"] = T.SECRET.sub("[SECRET]", s["thought"])
return trP06 · Put in order
P08 · Recall
Lesson: L3-M01-L0411. Summary
- Concepts: a trajectory is the ordered record of the steps of one run, written by the harness [R1]; each field is kept for a reason (
WHY); an error of the record differs from an agent's mistake recorded truthfully. - Skills: read a record, run
lint_traceand separate errors from warnings, runredactand readredactions, build test records withbuild_record. - Pitfalls: trusting
thought; storing parsed arguments instead of the original text; taking a clean lint for a true record; taking the redaction as enough; forgetting that a right end state says nothing about the path [R2]. - You can now: take a run and ask: who recorded it, what each field is for, whether the record contradicts itself, and what must be redacted before storing.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | Demystifying evals for AI agents | Anthropic | https://www.anthropic.com/research/demystifying-evals-for-ai-agents (redirected from anthropic.com/engineering/demystifying-evals-for-ai-agents) | 2026-11-04 | Read the page text: a transcript (also called trace or trajectory) is the complete record of a trial; the harness records all the steps; the advice to read transcripts |
| R2 | τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains (arXiv 2406.12045) | arXiv (Yao et al.) | https://arxiv.org/abs/2406.12045 | 2026-11-04 | Read the abstract page and the HTML version of the reward section and the section on polishing instructions with trajectories; a reward of 1 is necessary, not sufficient; experiments not read |
Glossary (English ↔ Tiếng Việt)
| English | Tiếng Việt |
|---|---|
| Trajectory (record) | Bản ghi trajectory: các bước có thứ tự của một lần chạy, do harness viết |
| Harness | Chương trình chạy agent và ghi bản ghi |
| Thought / action / observation | Suy nghĩ (lời agent tự nêu) / hành động (lời gọi tool hoặc câu trả lời cuối) / quan sát (thứ lớp tool trả) |
| Trace lint error / warning | Lỗi (bản ghi không dùng được) / cảnh báo (bản ghi đúng của một điều đáng xem) |
| Redaction | Che: tạo bản sao đã thay bí mật và văn bản riêng tư, kèm danh sách vị trí bị che |