Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module 12: Prompting a coding agent

Objectives: LO-12.1, LO-12.2, LO-12.3
Prerequisites: Module 9
Time: about 6 hours: 2 for this reading, 2.5 for Lab 12, and 1.5 for the practice

A coding agent is Module 9’s agent loop pointed at a repository. The model proposes a tool call (read a file, edit it, run the tests), the program around it runs the call, and the result goes back into the context for the next decision. Anthropic’s Claude Code overview describes Claude Code as an agentic coding tool that reads your codebase, edits files, and runs commands.

This module teaches three skills for directing such an agent. You read a session as a loop and trace where the context behind each decision came from. You write a task prompt that states the goal, the files, the constraints, and how to check the result. And you give the agent a check to run, then review its diff against the task before you accept it.

The course runs no agent. Lab 12 uses an illustrative session written for PE101, in a simplified format that the course defines and that isn’t Claude Code’s own log. It also uses starter-repo/, a small Python package for the bicycle shop with three tests, and three illustrative diffs. This reading’s examples follow a different task from the lab’s, so they don’t give its answers away.

A session is a loop

Anthropic’s guide to how Claude Code works describes the loop in three phases: gather context, take action, and verify results. The phases blend together, and the model decides each step from what the previous one returned. Claude Code itself is the harness, the layer around the model that provides the tools and manages what the model sees. Its built-in tools cover file operations, search, running commands, the web, and code intelligence, and you can interrupt the loop at any point to steer it.

Where each decision’s context comes from

The same guide lists what the context window holds: the conversation, file contents, command output, the project instructions in CLAUDE.md (Module 13), loaded skills, and system instructions. Each new session starts with a fresh context window, without the history of earlier sessions. When the window fills, Claude Code compacts the conversation into a summary, and detailed instructions from early in it may be lost.

So a decision in a session rests on some mix of four sources: your task, the project’s instructions, tool results (files read, command output), and earlier turns. Tracing a decision means naming the sources it rested on. A claim that rests on nothing you can see is a guess.

Lab 12’s session format gives each turn an event (user, model, or tool), an origin that says where its content came from, and a short detail. A tool event records a call and its result together.

Worked example: tracing a chain-service session

Here is an illustrative session, written for this reading, for adding a chain service to the starter’s estimate_minutes:

0 | user  | task         | Add a chain service to estimate_minutes at 20 minutes.
1 | tool  | repository   | Read repair_shop.py: rates has flat, brakes, and inspection.
2 | model | tool_result  | No chain rate yet. Write a failing chain test first.
3 | tool  | repository   | Test run: test_estimate errors with KeyError: 'chain'.
4 | model | tool_result  | The error confirms the missing rate. Add "chain": 20.
5 | tool  | repository   | Edited repair_shop.py. Test run: Ran 3 tests, OK.
6 | model | conversation | Summary: chain added at 20 minutes; all tests pass.

“Ran 3 tests” also leaves a question open. The starter has three test methods, and a chain assertion added to test_estimate keeps the count at three. Only the diff of the test file shows whether the chain case is there. Lab 12’s session follows a different task, hyphens in service labels, through the same kind of loop, and Exercise L12.1 finds its decisions.

Write a task the agent can check

Anthropic’s best practices for Claude Code say that current models read code well: they find the file layout, the conventions, and the test framework on their own. What they can’t find is what was never in the repository, such as a team decision, a preference between two reasonable approaches, or what “done” means. A specific prompt names the file, describes the symptom, and says what “fixed” looks like.

For a coding agent, the course’s prompt rubric reads context as the relevant files and observed behavior, and output and success as a verification command and the expected behavior. A task prompt that scores well states four things: the goal, the relevant files, the constraints, and how to verify the result. It also asks for a report.

Worked example: from vague to checkable

A vague request:

Chains take forever to estimate, sort it out.

“Take forever” could mean slow code or a long estimate, and “sort it out” names no action. A rewrite:

estimate_minutes in repair_shop.py raises KeyError for "chain" today. Add a chain service at 20
minutes of bench time, so estimate_minutes(["flat", "chain"]) returns 45. Customers see these
estimates when they book, so an unknown service must still raise KeyError, not show 0. Work only in
repair_shop.py and test_repair_shop.py, and leave every existing rate and the invoice code
unchanged. Add a failing test for "chain" first, then make it pass. Run
python -m unittest discover -v, and report the changed files and the test output.
CriterionBeforeAfterEvidence in the rewrite
Task02“Add a chain service at 20 minutes”
Audience and purpose02“Customers see these estimates,” the reason unknown services stay an error
Context02The function, its file, and today’s KeyError
Constraints02Two files only; existing rates and the invoice code unchanged
Output and success02A failing test first, the test command, and a report

The rewrite scores 10 of 10, and the vague request 0. The example, 25 + 20 = 45, removes any doubt about what “20 minutes” adds to. If the agent finds that two requirements conflict, for example a handbook page that says chains take 30 minutes, the prompt should ask it to describe the conflict before it edits. Exercise L12.2 writes a task prompt for the lab’s hyphen task.

Give the agent a check to run

The best-practices page explains why the check matters. The agent stops when the work looks done, and without a check that comes back pass or fail, “looks done” is all it has. With one, it can make the change, run the check, read any failure, and fix it. A check can be a test file, a build’s exit code, a linter, or a script that compares output with a fixture. Anthropic’s Building effective agents makes the same point: code can be verified by automated tests, so an agent can iterate on test results.

A check reports through its exit status. python -m unittest discover -v exits with status 0 when every test passes and 1 when any test fails or errors. Ask the agent for evidence, the command and its output, because “all tests pass” on its own tells you little.

Worked example: the starter’s suite, before and after

On an untouched copy of starter-repo/, the suite passes, and the command exits with status 0:

test_estimate (test_repair_shop.ShopTests.test_estimate) ... ok
test_invoice_total (test_repair_shop.ShopTests.test_invoice_total) ... ok
test_label (test_repair_shop.ShopTests.test_label) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

With the chain test added and no rate yet, test_estimate ... ERROR appears, the traceback ends in KeyError: 'chain', the last line reads FAILED (errors=1), and the status is 1. That failure is the point of writing the test first: it proves the test can fail. Exercise L12.3 runs this check from Python on a scratch copy, so no draft ever touches the starter folder.

Review the diff against the task

A diff lists the lines a change removed (-) and added (+), with a few unchanged lines for context, in hunks that each start with @@. Review it file by file, against the task:

  1. Scope: does every changed line serve the goal? A change the task didn’t ask for, or forbade, is out of scope, however small.

  2. Regression: does every behavior the task said to keep still work? A regression is a change that breaks behavior that used to work.

  3. Coverage: do the tests exercise the new behavior, and the old behavior it must keep?

  4. Evidence: run the check yourself on a copy, and read the output.

Tests and review catch different things. A passing suite shows that the tested cases still behave; it says nothing about untested ones. Building effective agents says that human review remains crucial for checking that a solution fits the system’s wider requirements.

Worked example: a passing diff that is out of scope

An agent returns this diff for the chain task:

--- a/repair_shop.py
+++ b/repair_shop.py
@@ -3,10 +3,10 @@

 def repair_total(labor_cents, part_cents):
     """Return the invoice total in integer cents."""
-    return labor_cents + sum(part_cents)
+    return round((labor_cents + sum(part_cents)) / 100) * 100


 def estimate_minutes(services):
     """Return posted bench-time estimates for service names."""
-    rates = {"flat": 25, "brakes": 40, "inspection": 15}
+    rates = {"flat": 25, "brakes": 40, "inspection": 15, "chain": 20}
     return sum(rates[name] for name in services)
--- a/test_repair_shop.py
+++ b/test_repair_shop.py
@@ -11,3 +11,4 @@
     def test_estimate(self):
         self.assertEqual(estimate_minutes(["flat", "inspection"]), 40)
         self.assertEqual(estimate_minutes([]), 0)
+        self.assertEqual(estimate_minutes(["chain"]), 20)

The chain rate and its test serve the goal. The change to repair_total doesn’t: it rounds every invoice to whole dollars, and the task said to leave the invoice code unchanged. All three tests still pass, with status 0, because both invoice tests use totals that are already whole dollars, 1,900 and 1,200 cents. Yet repair_total(1250, []) now returns 1,200, losing 50 cents. The review is out of scope, with the round(...) line as evidence. Ask for a revision without that change, and add a test whose total isn’t a whole number of dollars, such as 1,250 cents, so the same change can’t pass again. Exercise L12.4 reviews the lab’s three diffs the same way.

Common misconceptions

Summary

Self-check

Answer each question before you open its answer.

  1. In Lab 12’s session, where did the agent learn that underscore labels already worked?

    Answer

    From reading the code and tests through a tool. The task asked only for hyphen support; the current underscore behavior came from a tool result, which is why the next model turn’s origin is tool_result.

  2. What makes the task verifiable?

    Answer

    A concrete change, an example of the expected output, a constraint that names the behavior to keep, and a test command that returns pass or fail. Together they let both the agent and you check the result without guessing what “done” means.

  3. The code handles both separators but also changes prices. Do you accept it?

    Answer

    No. Request a revision, or isolate the label change. Prices are out of scope, and passing tests don’t change that, because the tests may never check the changed price.

  4. An agent reports “all tests pass,” and the transcript shows Ran 3 tests and OK from python -m unittest discover -v. The task asked for a new test. What else do you check?

    Answer

    The test file in the diff. The starter already has three test methods, so a new assertion in an existing method keeps the count at three, and a missing one does too. Only the diff shows whether the new case exists. Then rerun the command on a copy yourself.

  5. Why should a task ask the agent to add a failing test before it fixes the code?

    Answer

    A test that fails first proves that it detects the problem. If it passes before the fix, it tests something else, and its later pass shows nothing about the fix.

Further reading