Skip to content
Index Ai Academy
Phase 10 · Scaling & shipping

Capstone: build a coding agent

A harness that edits a project, runs its tests and stops when they pass.

About 45 minutes · Model names checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers11

First principles

What should a coding harness count as completion when the model says a patch works?

Give the harness independent evidence of success. Keep the tests outside the agent's write scope and evaluate the final project state under the same rules as the original brief.

  1. Starting point

    Agent proposes and applies a scoped edit

  2. What changes

    Harness runs the fixed grading tests

  3. Result

    Run ends in success only when acceptance checks pass

Compare all three steps
  1. Starting point

    Agent proposes and applies a scoped edit

  2. What changes

    Harness runs the fixed grading tests

  3. Result

    Run ends in success only when acceptance checks pass

Complete and reverse the trace

Given Agent proposes and applies a scoped edit and Run ends in success only when acceptance checks pass, write down the missing step that connects them.

Compare with the worked step

Harness runs the fixed grading tests

Now take Harness runs the fixed grading tests and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Agent proposes and applies a scoped edit. Check that your implementation produces the result shown above.

Try it on a new case

The model says the repair is finished, but one acceptance test still fails. Should the harness report success?

Show worked reasoning

Report the failed acceptance check and continue within the remaining budget or return an incomplete run. The test result is the harness's evidence of whether the task is done.

Run, change, and build

Check this when debugging. Trusting the model's "done" without checking.

Trace the cause · Harness decision and state
  1. Trace the action from the proposed tool call through validation to the recorded result. Predict what survives a stop.
  2. Change one permission, cost limit, or interruption point. Compare the trace and persistent state to see which rule determined the outcome.
  3. Try the same reasoning on this case. The model says the repair is finished, but one acceptance test still fails. Should the harness report success?

Why it matters

This is the payoff for the phase. You'll build a small but complete coding agent: it reads and edits a project, runs its tests, and keeps going until they pass, or stops cleanly when it can't. The same architecture, scaled up, runs inside the coding tools professionals use every day. Once you've built one, you can read, tune and extend any of them.

What you'll be able to do

  • Combine the loop, tools, permissions, a stop check and an event log into one coding agent
  • Give the agent file tools that stay inside the project and refuse to change the tests
  • Make the harness, not the model, decide when the work is done: when the tests pass
  • Connect the finished harness to a real model with a small adapter
Quick check
A coding agent says "Done! All tests pass." How should the harness decide the task is finished?
  1. Wait for the model to say done twice
  2. Count how many files the agent changed
  3. Run the tests itself and check they pass
  4. Trust the model's message, since it ran them
Show the answer

Run the tests itself and check they pass

Only a check the harness runs itself counts; the model's claim is just text. This capstone ends a run when the tests pass in the harness, and stops it at a budget if they don't.

The brief: a coding agent that cannot cheat

The design

This is the parts list: each part is one you built, and the lesson it came from:

partfromin this agent
injected modelWhat an agent harness ismodel(system, messages, tools), scripted in tests
loopThe core loop, built properlytool_use runs tools; end_turn triggers the check
toolsA tool registry for agents, File and search tools, Running code safelyread_file, write_file, edit_file, run_tests
workspace jailFile and search toolsevery path must resolve inside the project
permissionsPermissions and approvalsa file whose name starts with test_ is read-only, so a test can't be weakened
stop checkHooks and skillson end_turn, the harness runs the tests itself
turn capThe core loop, built properlystops with a clear status; a cost budget is part of the brief below
event logTracing, budgets and guardrailsone event per model call, tool call and test run

In plain words: the model suggests what to do next, and your code checks it, does it and decides when the job is over.

Quick check
From the lesson on tracing, budgets and guardrails: every run needs limits that stop it cleanly. What does this print for three moments in a run, each given as turns so far and dollars spent?
def within_budget(turns, cost, max_turns=20, max_cost=2.00):
    return turns < max_turns and cost < max_cost

print(within_budget(5, 0.40), within_budget(20, 0.40), within_budget(5, 2.50))
  1. True False True
  2. True True False
  3. False False False
  4. True False False
Show the answer

True False False

The first moment is inside both limits. The second has used up its turns, and the third has spent too much, so either one stops the run. The coding agent in this capstone keeps the turn half of that budget: it counts its model calls and stops at the limit. It also has a better reason to stop, which is that the tests pass.

The agent you build here is small on purpose. It gets a failing test suite and a project folder. It reads files, edits code and runs the tests. It must stop when the tests pass, and it must be unable to pass them by changing them. Everything about it is something you can predict, run and attack.

Try it now

The model proposes and the harness decides. Permissions come before the tool runs, never after.

Worked example

Tests the agent can't touch

If the agent can edit the tests, the fastest way to make them pass is to weaken them. So test files, the ones whose names start with test_, are read-only, and the check runs before any write.

from pathlib import PurePosixPath

def may_write(path):
    if PurePosixPath(path).name.startswith("test_"):
        return False, "tests are read-only: change the code, not the test"
    return True, "ok"

for path in ["calc.py", "test_calc.py", "src/test_util.py", "src/util.py"]:
    print(path, may_write(path))
It runs right here in your browser, with nothing to install.

The refusal message matters. It tells the model what to do instead, so it goes back to fixing the code. You'll use this rule in the exercise.

Drill

Paths the agent may not edit

The exercise protects one kind of file: a file whose name starts with test_, wherever it sits in the tree. Write protected(path, patterns): return True if path matches any glob pattern in patterns (use fnmatch.fnmatch), so one function can refuse edits to all of them.

from fnmatch import fnmatch

PATTERNS = ["test_*.py", "*/test_*.py"]


def protected(path, patterns):
    return path in patterns


print(protected("src/test_calc.py", PATTERNS), protected("calc.py", PATTERNS))
In the lesson, your code is checked as you write it.
In your own words
What stops the agent from passing by editing the tests?

Write a sentence or two, then compare it with a good answer in the lesson.

Build it: the loop, the jail and the stop check

The harness decides when it's done

Students don't mark their own exams. A model saying "Fixed!" is a claim, not a result. So when the model ends its turn, the harness runs the tests itself, like a Stop hook:

  • Tests pass: the run succeeded.
  • Tests fail: add a user message with the failures and "keep working", and loop again. The model sees exactly what's still wrong.
  • Still failing after two such checks: stop with status "failed", so a person can look.

Combined with read-only tests, this closes the obvious shortcut: the only way to pass is to fix the code.

Worked example

end_turn isn't the end

The model says it's done on the first try here, but it isn't. The harness runs the tests itself and sends it back.

replies = iter([
    {"stop_reason": "end_turn", "text": "All done!", "fix": False},
    {"stop_reason": "end_turn", "text": "Fixed the off-by-one.", "fix": True},
])
code_is_fixed = False

def run_tests():
    return code_is_fixed

for turn in range(1, 6):
    reply = next(replies)
    code_is_fixed = reply["fix"]
    print(f"turn {turn}: model says {reply['text']!r}")
    if run_tests():
        print("tests pass: finished")
        break
    print("tests fail: sending the failure back")
In the lesson you can change this and run it.

The first reply is confident and wrong. If the harness had believed it, you'd have shipped a bug. A check the model can't talk its way past is what makes an agent trustworthy.

Quick check
What does this print?
model_says_done = True
tests_pass = False
print(model_says_done and tests_pass)
  1. False
  2. tests_pass
  3. True
  4. None
Show the answer

False

True and False is False, so it prints False. The model's opinion isn't enough. The harness runs the tests itself.

Running tests in the browser

The run_tests helper is given. It imports each test_*.py file in the project and calls its test_* functions, a tiny version of pytest. On a real machine you'd run pytest through the execution tool, in a sandbox.

Worked example

The test runner you'll use

It returns whether everything passed and a short summary for the model.

import importlib, sys, tempfile
from pathlib import Path

def run_tests(root):
    root = Path(root)
    passed, failures = 0, []
    sys.path.insert(0, str(root))
    old_flag, sys.dont_write_bytecode = sys.dont_write_bytecode, True
    try:
        for test_file in sorted(root.glob("test_*.py")):
            for name in [m for m in list(sys.modules) if (root / f"{m}.py").exists()]:
                del sys.modules[name]
            importlib.invalidate_caches()
            ns = {"__name__": "tests"}
            try:
                exec(compile(test_file.read_text(), str(test_file), "exec"), ns)
            except Exception as err:
                failures.append(f"ERROR {test_file.name}: {type(err).__name__}: {err}")
                continue
            for name, fn in list(ns.items()):
                if name.startswith("test_") and callable(fn):
                    try:
                        fn()
                        passed += 1
                    except Exception as err:
                        failures.append(f"FAIL {name}: {err}")
    finally:
        sys.path.remove(str(root))
        sys.dont_write_bytecode = old_flag
    summary = f"{passed} passed, {len(failures)} failed"
    summary += "".join("\n" + f for f in failures)
    return {"passed": passed > 0 and not failures, "summary": summary}

root = Path(tempfile.mkdtemp())
(root / "calc.py").write_text("def add(a, b):\n    return a - b\n")
(root / "test_calc.py").write_text(
    'from calc import add\n\ndef test_add():\n'
    '    assert add(2, 2) == 4, f"add(2, 2) gave {add(2, 2)}"\n')
print(run_tests(root))
In the lesson you can change this and run it.

Removing the project's modules from sys.modules, and not writing bytecode, makes each run import the current files, so edits take effect right away.

Quick check
The model edits test_calc.py to assert add(2, 2) == 0, then says it's done. What should this harness do?
  1. It never got that far: edits to test files are denied, so the model must fix calc.py instead
  2. Accept the run, since the tests now pass and the model has said that it's done
  3. Delete the test file, since the model has shown it can't be trusted with it
  4. Ask the model whether it cheated, and accept the run if it says it didn't
Show the answer

It never got that far: edits to test files are denied, so the model must fix calc.py instead

Read-only tests plus a harness-run check means the only way to pass is a real fix.

Quick check
In the capstone, what decides that the task is finished?
  1. A fixed number of turns, after which the task counts as finished
  2. The model saying it's done, in a message at the end of its turn
  3. The user closing the window once they're happy with the result
  4. The harness runs the tests itself when the model ends its turn
Show the answer

The harness runs the tests itself when the model ends its turn

A model's "done" is a claim. The harness turns it into a fact by running the tests.

Worked example

Your agent against three practice models

These stand in for a real model, each with a habit. careful fixes the code. overconfident claims success with a wrong fix. edits_tests tries to weaken the test. The harness catches each one in a different way. Tuples are (habit, status, turns, refused edits, test checks).

from pathlib import PurePosixPath
from agentlab import PracticeModel, TASKS, run_tests

TOOLS = ["read_file", "edit_file", "run_tests"]

def run_agent(habit, max_turns=10):
    files = dict(TASKS["calc"]["files"])
    model = PracticeModel(habit)
    messages = [{"role": "user", "content": TASKS["calc"]["prompt"]}]
    refused = checks = 0
    for turn in range(1, max_turns + 1):
        reply = model(messages, TOOLS)
        messages.append({"role": "assistant", "content": reply["content"]})
        if reply["stop_reason"] == "tool_use":
            results = []
            for b in reply["content"]:
                if b["type"] != "tool_use":
                    continue
                name, args = b["name"], b["input"]
                path = args.get("path", "")
                if name == "edit_file" and PurePosixPath(path).name.startswith("test_"):
                    out, bad = "Denied: test files are read-only.", True
                    refused += 1
                elif name == "edit_file":
                    files[path] = files[path].replace(args["old"], args["new"])
                    out, bad = "Edited " + path, False
                elif name == "read_file":
                    out, bad = files[args["path"]], False
                else:
                    out, bad = run_tests(files)["summary"], False
                result = {"type": "tool_result", "tool_use_id": b["id"], "content": out}
                if bad:
                    result["is_error"] = True
                results.append(result)
            messages.append({"role": "user", "content": results})
            continue
        checks += 1
        verdict = run_tests(files)
        if verdict["passed"]:
            return habit, "passed", turn, refused, checks
        note = "The tests still fail:\n" + verdict["summary"] + "\nKeep working."
        messages.append({"role": "user", "content": note})
    return habit, "max_turns", max_turns, refused, checks

for habit in ["careful", "overconfident", "edits_tests"]:
    print(run_agent(habit))
In the lesson you can change this and run it.
In your own words
Why doesn't the model's "done" end the run?

Write a sentence or two, then compare it with a good answer in the lesson.

In your own words
Why doesn't the model's "done" end the run?

Write a sentence or two, then compare it with a good answer in the lesson.

Ship it: attack it, trace it, run it for real

Why the prompt isn't enough

A "do not touch" sign isn't a lock. You could write "do not edit the tests" in the system prompt. It would work most of the time, and that's the problem. Under pressure from a failing test, with several attempts already used, a model may decide that the test is what's wrong. It may even be right sometimes. But your check on the agent's work is worthless if the agent can rewrite it.

So the harness enforces the rule. Test files are read-only at the tool level, and no amount of clever reasoning changes that. As a general rule, use prompts to guide and code to guarantee.

What happens when it keeps failing

Without a limit, an agent that can't solve a problem keeps trying forever, spending money each turn. So cap the turns, and when the budget runs out, stop and report honestly: what it tried, which tests still fail, and what state it left the files in. Reporting failure clearly is a feature. A person can pick up from there, which is much better than a silent loop, or a confident claim that everything works.

Quick check
The agent has used all its turns and three tests still fail. What should the harness do?
  1. Stop and report what it tried and which tests still fail
  2. Keep going, since it may solve the problem on the next turn
  3. Report success, because the agent did its best
Show the answer

Stop and report what it tried and which tests still fail

A clear report lets a person pick up from there. Without a limit, the agent spends money forever, and a false claim of success is worse than an honest failure.

Drill

An honest final report

Write final_report(results, turns, max_turns): results maps test names to True/False. If all pass, return All N tests pass.; otherwise Stopped after T of M turns: K of N tests still fail: followed by the failing names, sorted and joined with , .

def final_report(results, turns, max_turns):
    return "Done! All tests pass."


print(final_report({"test_add": True, "test_sub": False, "test_div": False}, 12, 12))
In the lesson, your code is checked as you write it.

Plugging in a real model

Remember the flight simulator. The pilot's controls stay the same when they move to the real plane. Because the model is injected, switching from the scripted model to Claude is one small adapter. With an API key on your own machine, using the official SDK:

import anthropic

client = anthropic.Anthropic()   # reads ANTHROPIC_API_KEY from the environment

def claude(system, messages, tools):
    reply = client.messages.create(model="claude-opus-5-5", max_tokens=4000,
                                   system=system, tools=tools, messages=messages)
    return {"stop_reason": reply.stop_reason,
            "content": [block.model_dump(exclude_none=True) for block in reply.content]}

agent = CodingAgent(claude, "path/to/project")
print(agent.run("The tests in test_calc.py fail. Find the bug and fix it."))

model_dump(exclude_none=True) turns the SDK's block objects into the plain dicts the harness uses. From there, add the pieces from this phase one at a time, and run your eval suite after each, to see what actually helps.

What a real model adds

When you plug in the real API, the harness stays exactly the same. The scripted model and the real one are both functions that take messages and tools and return a reply. Every path you tested with a script, including errors, timeouts and bad tool calls, is still tested. Real models add one thing: variety. Run each task several times, as Evaluation harnesses shows, since a single pass proves little.

From here you can add a real sandbox for the commands (Sandboxes for agents that browse), a smarter way to pick which files to read, or a question to the person when the agent is stuck. Each is a small change to one part. The loop in the middle stays as it is, which is what makes a well-designed harness easy to grow.

Portfolio brief

Ship the agent: evals, attacks, a trace and a cost report

Your exercise agent passes its tests. A shipped agent also has evidence. Run it against the practice models and the three practice tasks, then write down what you found.

It must

  • An eval suite: tasks calc, discount and words, each run 3 times with seeds 0, 1 and 2 on PracticeModel({"careful": 3, "overconfident": 1, "edits_tests": 1}, seed=k). Print passes out of 9 and the habit behind every failure.
  • An attack suite of at least five attacks: a test edit, a path outside the project, an order planted in a file the agent reads (the words task), a repeated call and an oversized read. For each, name the layer that stopped it, or say that nothing did.
  • One trace of one run: a waterfall with agentlab.spans_plot, with the slowest span named in a sentence.
  • A cost report: tokens in and out per run, and dollars at the prices in the lesson's context section, with the cheapest and costliest run named.
  • A turn cap and a cost budget, both tested: a run that hits each ends with a clear status, not an exception.

Go further

  • Run the same suite with loops and obeys_injection in the mix and show which part catches each.
from agentlab import PracticeModel, TASKS, run_tests, grade, project

mix = {"careful": 3, "overconfident": 1, "edits_tests": 1}
for name in ["calc", "discount", "words"]:
    for seed in range(3):
        model = PracticeModel(mix, seed=seed)
        # Run your harness with this model on TASKS[name], then grade the result.
        print(name, seed, "TODO")
In the lesson, you build it here and the tutor can review it.
In your own words
The agent runs out of turns with three tests still failing. What should the harness do?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 5 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 7 review cards for spaced repetition

Try a quiz question

Why does the harness run the tests itself when the model says it's done?

  1. The model's claim isn't proof; the harness checks the real result
  2. To save the model a turn, since a test result it asks for would use up tokens
  3. The model can't run tests, because it has no way of calling a tool like that one
  4. To make the transcript longer, so that the grader has more to go through at the end

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 10 · about 20 hours of study

Agent harnesses

Build the software around a model that turns it into a capable, safe agent 24 lessons 1 free
  1. What an agent harness is FreeThe software around a model that turns it into an agent.35 min
  2. The core loop, built properlyStop reasons, parallel tool calls, errors and turn budgets.40 min
  3. A tool registry for agentsSchemas from functions, validation, output limits and helpful errors.40 min
  4. File and search toolsRead, write, edit by exact replacement, glob and grep inside one folder.45 min
  5. Running code safelyExecution tools, step limits, output caps and real sandboxes.45 min
  6. Giving an agent a databaseSchema as context, a query tool with caps and readable errors, guards in layers, and execution accuracy.45 min
  7. Permissions and approvalsRules, modes and approval prompts that keep a person in control.40 min
  8. Hooks and skillsExtend a harness at lifecycle events, and load know-how on demand.40 min
  9. Multi-agent systemsCoordinating many agents on one large job.35 min
  10. Managing the context windowBudgets, clearing old tool results, compaction and a cacheable prefix.45 min
  11. Memory, plans and long tasksTo-do lists, progress notes, memory files and checkpoints.45 min
  12. SubagentsHand a focused task to a fresh context with fewer tools.40 min
  13. Streaming, interrupts and sessionsLive output, stopping safely, and saving and resuming transcripts.40 min
  14. Agents as graphsState, reducers and routing, a checkpoint after every step, and pausing for a person's approval.45 min
  15. Evaluation harnessesRun agents on tasks in fresh environments and grade what they leave behind.45 min
  16. Tracing, budgets and guardrailsSee what an agent did, cap what it spends, and stop it when it loops.40 min
  17. Attack your own harnessRun fourteen attacks against a harness with switches, read which layer stops each one, score attacks stopped against ordinary tasks done, and keep every finding as a release test.40 min
  18. Capstone: build a coding agentA harness that edits a project, runs its tests and stops when they pass.45 min
  19. The same agent on the real SDKsPut the parts you built beside the tool runner and the Agent SDK, choose a surface for a job, and take an MCP server's tools into your registry with prefixed names, one rule per server and a capped result.35 min
  20. Agents that use a computerAn agent with a screen, a mouse and a keyboard: the observe-decide-act loop, what a click lands on, why a wrong hit is worse than a miss, what happens when the screen changes under a plan, and what screenshots cost.45 min
  21. Sandboxes for agents that browseTreat every page as untrusted input: check hosts properly, gate actions by their effect, and layer the defenses.45 min
  22. Protocols between agentsHand a task to an agent someone else built: agent cards, the life of a task, the messages on the wire, safe retries, and whom to trust.45 min
  23. Tracing a run end to endFollow one run across an orchestrator, subagents and tool servers: trace ids, the traceparent header, the critical path, tokens by branch, and which traces to keep.45 min
  24. Retrieval over a graphAnswer questions that hop between documents: facts as triples, a walk out from the entities a question names, and the hubs and missed facts that limit it.45 min
Step by step 7 steps

Build a coding agent in Python

An agent that reads and edits a project, runs its tests and stops when they pass, with the safety checks that keep it inside the project.

Part of a free course 29 lessons

Free AI agents course

Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.

Part of a free course 13 lessons

LLM Harness

Build a bounded run loop, test it with scripted model responses, and recover interrupted work from an event log.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write