Objectives: LO-12.1, LO-12.2, LO-12.3
Prerequisites: the Module 12 reading
Time: about 2.5 hours
In this lab you trace an illustrative coding-agent session, write two task prompts, run the tests of a copy of the fictional shop package from Python, and review three proposed diffs against their task.
No cell runs a coding agent or calls a model. The session in data/agent/session.json and the
diffs in data/agent/diffs.json were written for this course, in a simplified format that
isn’t Claude Code’s own; they are illustrative, not model output. The package is the course’s
starter-repo/, and every test run uses a scratch copy, so the starter folder never changes.
Each exercise ends with a check cell that prints passed or fails with a message that says what
is wrong. Run the cells in order, from the top, in a fresh kernel. The checks fail until you
finish the exercise above them.
Setup¶
import sys
import hashlib
import pathlib
import shutil
import subprocess
from tempfile import TemporaryDirectory
from promptlab import data_path, load_json
task = load_json("agent/task.json")
session = load_json("agent/session.json")
diffs = load_json("agent/diffs.json")
starter = data_path("agent/task.json").parents[2] / "starter-repo"
print("Python", sys.version.split()[0])Identify information sources¶
Each turn has an event (user, model, or tool), an origin that says where its content
came from, and a short detail. Predict which turn tells the agent how underscores work, then
print the trace.
print(session["source"])
for turn in session["turns"]:
print(turn["event"], turn["origin"], turn["detail"], sep=" | ")Exercise L12.1 (LO-12.1, ★★, about 25 minutes)¶
Find a decision following evidence. Write decision_positions(turns). Return the zero-based
positions of the turns whose event is "model" and whose origin is "tool_result". If a turn
lacks either field, don’t count it. In your notes, say exactly what the tool output before each
of those turns supplied.
def decision_positions(turns):
raise NotImplementedError("L12.1")positions = decision_positions(session["turns"])
assert positions == [3, 5], \
("Return the positions of model turns whose origin is tool_result, counting from 0; "
f"got {positions}.")
assert decision_positions([{"event": "model"}]) == [], \
"A model turn with no origin field doesn't follow evidence: don't count it."
assert decision_positions([{"event": "tool", "origin": "tool_result"}]) == [], \
"Count only model turns: a tool turn is evidence, not a decision."
print("passed")Exercise L12.2 (LO-12.2, ★★, about 25 minutes)¶
Write a checkable agent task. Write task_prompt(task), where task is the dictionary in
data/agent/task.json. Return a prompt that contains the task’s goal word for word, both file
names in files, each sentence in constraints, and the verification command, and that asks
the agent to report what it did, with the word “Report”. Score your prompt with the
prompt rubric. In your notes, draft and score a second prompt, one that
prevents a pricing regression (a change that breaks prices that used to be right).
def task_prompt(task):
raise NotImplementedError("L12.2")prompt = task_prompt(task)
missing = [item for item in [task["goal"], task["verification"], *task["files"],
*task["constraints"]] if item not in prompt]
assert not missing, f"Include each of these in the prompt, exactly as the task gives it: {missing}"
assert "Report" in prompt, 'Ask the agent for a report, using the word "Report".'
print("passed")Exercise L12.3 (LO-12.3, ★★, about 25 minutes)¶
Supply a local check command. Write check_package(path). Run the current Python
(sys.executable) with -m unittest discover -v in the folder path, capture the output as
text, and return the process’s exit status: 0 when every test passes, and nonzero otherwise.
Pass the command to subprocess.run as a list of arguments, without a shell. The check copies
the starter to a scratch folder first, so your function never runs in the starter itself.
def check_package(path):
raise NotImplementedError("L12.3")with TemporaryDirectory() as scratch:
work = shutil.copytree(starter, scratch, dirs_exist_ok=True)
assert check_package(work) == 0, "The untouched starter's tests pass, so return 0."
shop = pathlib.Path(work, "repair_shop.py")
shop.write_text(shop.read_text().replace('name.replace("_", " ")', "name"))
assert check_package(work) != 0, \
"With service_label broken, a test fails: return the test run's nonzero code."
print("passed")Exercise L12.4 (LO-12.3, ★★, about 25 minutes)¶
Review three diffs. Write reviews(). Return a dictionary keyed by the diff IDs "A",
"B", and "C". Each value is a pair: the review, one of "accept", "regression" (it breaks
behavior the task said to keep), or "out_of_scope" (it changes something the task didn’t ask
for), and the changed line that supports it, copied from the diff without its leading + or -.
Compare each diff with the task’s goal and constraints, and run the tests on a scratch copy if
that helps. Don’t apply a draft to the starter folder itself.
def reviews():
raise NotImplementedError("L12.4")for draft in diffs:
print(draft["id"], draft["source"], draft["diff"], sep="\n")
# The expected reviews are stored as SHA-256 digests of "<ID>:<review>", so this cell doesn't
# show them.
EXPECTED = {"A": "80d1587141ec684552699bb6d9443402f5b16735563c964906201c6f005e0c7a",
"B": "768924fd3df4fc717aeb69af75179559d1a40c70dc64c555c4324e295b8c01af",
"C": "23a1b2064576d45e5c42cd61c41aa81e4a4050eaf1221daa4e8d762e1aadde50"}
answers = reviews()
assert sorted(answers) == ["A", "B", "C"], "Return a review for each of A, B, and C."
for draft in diffs:
review, line = answers[draft["id"]]
assert review in {"accept", "regression", "out_of_scope"}, \
f"{draft['id']}: use accept, regression, or out_of_scope; got {review!r}."
changed = {row[1:].strip() for row in draft["diff"].splitlines()
if row[:1] in ("+", "-") and not row.startswith(("+++", "---"))}
assert line.strip() in changed, \
f"{draft['id']}: copy one changed line from the diff as your evidence."
digest = hashlib.sha256(f"{draft['id']}:{review}".encode()).hexdigest()
assert digest == EXPECTED[draft["id"]], \
f"{draft['id']}: reread the diff against the task's constraints, and run the tests on a copy."
print("passed")Summary¶
A coding agent’s model turns rest on tool results, the task, or the conversation; the tool turns are the evidence, and a final summary is only a report.
A checkable task prompt states the goal, the files, the constraints, the verification command, and the report you expect.
A check reports through its exit status, and runs on a scratch copy, never on the original.
A review compares every changed line with the task: a passing suite can still hide a regression it doesn’t test, or a change outside the task’s scope.