About this notebook

Companion to Module 13: Capstone, a coding agent. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)

A coding agent is the agent loop of Module 4 with one tool, a shell, pointed at a repository. The model reads test failures, looks at code, edits it and runs the tests again. Most of what decides whether that works is not the model but the harness: what the tool returns, how much of it the model sees, how long the loop may run, and what survives when the context runs out.

           ┌──────────────────────────── harness ────────────────────────────┐
           │                                                                 │
 task ──>  │  model ──bash(command)──> sandbox (repo, no network, limits)    │
           │    ^                              │                             │
           │    │                              v                             │
           │    └── observation <── format: status line, scrub, truncate     │
           │                                                                 │
           │  step budget (max_steps)        PROGRESS.md in the repo          │
           └─────────────────────────────────────────────────────────────────┘

You will

  1. copy a toy repository with three bugs and see its failing tests;
  2. build the harness: one bash tool in a sandbox, an observation format, truncation;
  3. run the agent until the tests pass and inspect its changes;
  4. break the harness on purpose (truncate the wrong end) and count the cost;
  5. stop the agent with a step budget, then let a fresh agent resume from the progress file;
  6. check what the sandbox stops.

The model here is a scripted fixer

The “model” is agentlab/llm/fake_packs/nb13_coding_fixer.py, a rule set that knows the three planted bugs by name. It does follow the routine a real coding agent follows (run tests, read the failing file, check the code is there, patch, re-run), and it acts only on what the harness shows it, so the harness experiments below are real. What it cannot show is a model reasoning about an unfamiliar bug. Point the notebook at a live model to see that.

import difflib
import json
 
from agentlab.agent import Agent
from agentlab.coding import CodingHarness, format_observation, parse_pytest
from agentlab.config import fixtures_dir
from agentlab.display import show_trajectory
from agentlab.llm.fake_packs.nb13_coding_fixer import FIXES, patch_command
from agentlab.nbsetup import setup
 
nb = setup("13_mini_coding_agent", packs=["coding_fixer"])
llm = nb.llm

LLM backend

offline policy model (deterministic, rule-based, no API key used)

1. The repository

textkit is three small modules with eleven tests. The agent works on a copy, so the fixture stays broken for the next run.

TOY = fixtures_dir() / "coding" / "toy_repo"
harness = CodingHarness.from_copy(TOY)   # a fresh temporary directory, see section 2
repo = harness.repo
print("\n".join(harness.sandbox.files()))
print("\n" + harness.bash("python -m pytest -q --tb=short"))
README.md
pytest.ini
tests/test_slug.py
tests/test_stats.py
tests/test_words.py
textkit/__init__.py
textkit/slug.py
textkit/stats.py
textkit/words.py

exit code 1
.F...F..F..                                                              [100%]
=================================== FAILURES ===================================
________________________ test_slug_punctuation_at_ends _________________________
tests/test_slug.py:9: in test_slug_punctuation_at_ends
    assert slugify("  Hello, World!  ") == "hello-world"
E   AssertionError: assert '-hello-world-' == 'hello-world'
E     
E     - hello-world
E     + -hello-world-
E     ? +           +
_______________________________ test_median_even _______________________________
tests/test_stats.py:15: in test_median_even
    assert median([4, 1, 3, 2]) == 2.5
E   assert 3 == 2.5
E    +  where 3 = median([4, 1, 3, 2])
_________________________ test_word_count_extra_spaces _________________________
tests/test_words.py:9: in test_word_count_extra_spaces
    assert word_count("the  quick brown   fox") == 4
E   AssertionError: assert 7 == 4
E    +  where 7 = word_count('the  quick brown   fox')
=========================== short test summary info ============================
FAILED tests/test_slug.py::test_slug_punctuation_at_ends - AssertionError: as...
FAILED tests/test_stats.py::test_median_even - assert 3 == 2.5
FAILED tests/test_words.py::test_word_count_extra_spaces - AssertionError: as...
3 failed, 8 passed in <t>s

Three failures, each with the assertion that broke. That output is what the model will read, so it deserves as much design as a prompt.

2. The harness

One tool. The agent gets a single tool, bash(command). A shell covers reading (cat, grep), editing (a heredoc or a short script), and running (pytest), so there is nothing else to learn. Its definition is all the model knows about it:

bash_tool = harness.tool()
print(json.dumps(bash_tool.tool_definition, indent=1))
{
 "type": "function",
 "function": {
  "name": "bash",
  "description": "Run a bash command in the repository root. Returns the exit code and output.",
  "parameters": {
   "type": "object",
   "properties": {
    "command": {
     "type": "string"
    }
   },
   "required": [
    "command"
   ]
  }
 }
}

The sandbox. Every command runs in agentlab.sandbox.LocalSandbox with the repo as its work directory: a 10 s wall-clock limit, 5 s of CPU, 512 MiB, no network, and writes only inside the repo (section 6 checks these). The repo lives in a fresh temporary directory, so every run starts from the same files. Inside your home folder works too: the macOS jail lets pytest and git stat the directories above the repo, which they do to find their root, but not list or read them.

The observation format. format_observation puts the status first, because it is the one fact the model must not miss; then stdout and stderr; then it scrubs what changes between runs (the repo’s absolute path, temporary paths, in 0.03s timings), so the same command always reads the same, which also helps prompt caching. Finally it truncates. Here is the failing test run from above under three truncation settings.

raw = harness.sandbox.run(["/bin/bash", "-c", harness.TEST_COMMAND])
print(f"raw output: {len(raw.stdout)} characters\n")
for max_chars, keep in ((2000, "both"), (600, "both"), (600, "head")):
    obs = format_observation(raw, repo, max_chars=max_chars, keep=keep)
    seen = parse_pytest(obs).failing
    print(f"--- max_chars={max_chars}, keep={keep}: {len(obs)} characters, "
          f"failing tests visible: {len(seen)}")
    print("\n".join(obs.splitlines()[-4:]))
raw output: 1320 characters

--- max_chars=2000, keep=both: 1330 characters, failing tests visible: 3
FAILED tests/test_slug.py::test_slug_punctuation_at_ends - AssertionError: as...
FAILED tests/test_stats.py::test_median_even - assert 3 == 2.5
FAILED tests/test_words.py::test_word_count_extra_spaces - AssertionError: as...
3 failed, 8 passed in <t>s
--- max_chars=600, keep=both: 646 characters, failing tests visible: 3
FAILED tests/test_slug.py::test_slug_punctuation_at_ends - AssertionError: as...
FAILED tests/test_stats.py::test_median_even - assert 3 == 2.5
FAILED tests/test_words.py::test_word_count_extra_spaces - AssertionError: as...
3 failed, 8 passed in <t>s
--- max_chars=600, keep=head: 645 characters, failing tests visible: 0
E     ? +           +
_______________________________ test_median_even _______________________________
tests/test_stats.py:15: in test_me
[... 718 characters omitted ...]

A test run puts its verdict at the end: the FAILED lines and the counts. Cutting the tail keeps the part a model needs least. Keeping a third from the head and two thirds from the tail costs nothing in the common case and saves the verdict when the output is long.

3. Run the agent

The system prompt states the routine; the step budget is 15 model calls. Here is what the scripted fixer knows, and the command it sends for one of them:

SYSTEM = ("You fix failing tests in a Python repository using one tool, bash. Start by "
          "reading PROGRESS.md if it exists. Run the tests with "
          "`python -m pytest -q --tb=short`. Fix one failure at a time, re-run the tests "
          "after each change, and append one line to PROGRESS.md for each fix. Stop when "
          "all tests pass.")
for test_id, (path, old, new, why) in FIXES.items():
    print(f"{test_id}\n    {path}: {why}")
print("\n" + patch_command("tests/test_stats.py::test_median_even"))
tests/test_slug.py::test_slug_punctuation_at_ends
    textkit/slug.py: slugify left hyphens at the ends; strip them
tests/test_stats.py::test_median_even
    textkit/stats.py: median of an even count returned one middle value; average the two
tests/test_words.py::test_word_count_extra_spaces
    textkit/words.py: word_count split on single spaces; split on any whitespace

python - <<'PATCH'
from pathlib import Path
p = Path('textkit/stats.py')
s = p.read_text()
old, new = '        return s[n // 2]\n    return s[n // 2]', '        return s[n // 2]\n    return (s[n // 2 - 1] + s[n // 2]) / 2'
assert s.count(old) == 1, 'patch does not apply'
p.write_text(s.replace(old, new))
PATCH
echo '- tests/test_stats.py::test_median_even: median of an even count returned one middle value; average the two' >> PROGRESS.md

The patch is a small Python script fed through a heredoc rather than sed -i, which behaves differently on macOS and Linux. It refuses to apply if the code it expects is not there exactly once.

async def solve(harness, max_steps=15):
    agent = Agent(llm, tools=[harness.tool()], instructions=SYSTEM, max_steps=max_steps)
    return await agent.run("Make the test suite pass.")
 
 
result = await solve(harness)
show_trajectory(result)
print("\nafter the run:", harness.run_tests())
[user] Make the test suite pass.
[agent -> bash] {"command": "cat PROGRESS.md 2>/dev/null || echo 'no progress file yet'"}
    [bash ok] exit code 0 no progress file yet
[agent -> bash] {"command": "python -m pytest -q --tb=short"}
    [bash ok] exit code 1 .F...F..F.. [100%] =================================== FAILURES =================...
[agent -> bash] {"command": "cat textkit/slug.py"}
    [bash ok] exit code 0 """URL slugs.""" import re def slugify(title: str) -> str: """Lower-case words jo...
[agent -> bash] {"command": "python - <<'PATCH'\nfrom pathlib import Path\np = Path('textkit/slug.py')\ns = p...
    [bash ok] exit code 0
[agent -> bash] {"command": "python -m pytest -q --tb=short"}
    [bash ok] exit code 1 .....F..F.. [100%] =================================== FAILURES =================...
[agent -> bash] {"command": "cat textkit/stats.py"}
    [bash ok] exit code 0 """Small statistics on lists of numbers.""" def mean(xs: list[float]) -> float: i...
[agent -> bash] {"command": "python - <<'PATCH'\nfrom pathlib import Path\np = Path('textkit/stats.py')\ns = ...
    [bash ok] exit code 0
[agent -> bash] {"command": "python -m pytest -q --tb=short"}
    [bash ok] exit code 1 ........F.. [100%] =================================== FAILURES =================...
[agent -> bash] {"command": "cat textkit/words.py"}
    [bash ok] exit code 0 """Counting words.""" def word_count(text: str) -> int: """Number of words in ``t...
[agent -> bash] {"command": "python - <<'PATCH'\nfrom pathlib import Path\np = Path('textkit/words.py')\ns = ...
    [bash ok] exit code 0
[agent -> bash] {"command": "python -m pytest -q --tb=short"}
    [bash ok] exit code 0 ........... [100%] 11 passed in <t>s
[agent] All 11 tests pass. Fixed in this session: test_slug_punctuation_at_ends, test_median_even, te...
--- status: complete, steps: 12

after the run: TestSummary(passed=11, failed=0, failing=[])

Twelve steps: one to read the (missing) progress file, then test, read, patch three times, a final test run and the answer. The progress file and the diff against the original are the record a reviewer would read:

print(harness.progress())
for rel in ("textkit/slug.py", "textkit/stats.py", "textkit/words.py"):
    a = (TOY / rel).read_text().splitlines()
    b = (repo / rel).read_text().splitlines()
    print("\n".join(difflib.unified_diff(a, b, f"a/{rel}", f"b/{rel}", n=0, lineterm="")))
- tests/test_slug.py::test_slug_punctuation_at_ends: slugify left hyphens at the ends; strip them
- tests/test_stats.py::test_median_even: median of an even count returned one middle value; average the two
- tests/test_words.py::test_word_count_extra_spaces: word_count split on single spaces; split on any whitespace

--- a/textkit/slug.py
+++ b/textkit/slug.py
@@ -8 +8 @@
-    return re.sub(r"[^a-z0-9]+", "-", title.lower())
+    return re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")
--- a/textkit/stats.py
+++ b/textkit/stats.py
@@ -18 +18 @@
-    return s[n // 2]
+    return (s[n // 2 - 1] + s[n // 2]) / 2
--- a/textkit/words.py
+++ b/textkit/words.py
@@ -8 +8 @@
-    return len(text.split(" "))
+    return len(text.split())

4. The wrong truncation costs steps

Now the same task with a 600-character limit that keeps only the head. The FAILED lines never reach the model. A sensible agent notices, re-runs the tests piped through tail, and keeps doing so; the scripted fixer does the same.

rows = []
for max_chars, keep in ((2000, "both"), (600, "both"), (600, "head")):
    h = CodingHarness.from_copy(TOY, max_chars=max_chars, keep=keep)
    r = await solve(h)
    tests = sum("pytest" in c.command for c in h.history)
    rows.append((max_chars, keep, r.status, r.context.current_step, tests, h.run_tests()))
print(f"{'max_chars':>9} {'keep':<5} {'status':<9} {'steps':>5} {'test runs':>9}  result")
for max_chars, keep, status, steps, tests, summary in rows:
    print(f"{max_chars:>9} {keep:<5} {status:<9} {steps:>5} {tests:>9}  "
          f"{summary.passed} passed, {summary.failed} failed")
print("\nthe workaround command:", h.history[2].command)
print(h.history[2].observation)
max_chars keep  status    steps test runs  result
     2000 both  complete     12         4  11 passed, 0 failed
      600 both  complete     12         4  11 passed, 0 failed
      600 head  complete     13         5  11 passed, 0 failed

the workaround command: python -m pytest -q --tb=no 2>&1 | tail -n 8
exit code 0
.F...F..F..                                                              [100%]
=========================== short test summary info ============================
FAILED tests/test_slug.py::test_slug_punctuation_at_ends - AssertionError: as...
FAILED tests/test_stats.py::test_median_even - assert 3 == 2.5
FAILED tests/test_words.py::test_word_count_extra_spaces - AssertionError: as...
3 failed, 8 passed in <t>s

One extra step here, because the fixer switched to tail for every later run. A model that did not notice would patch blind or stop. Note the exit code 0 on the workaround: in a pipeline the shell reports the exit status of tail, not of pytest, so a harness that trusted the status line would think the tests passed. Real harnesses run commands with set -o pipefail, or report the test result separately.

5. A step budget, and a progress file that survives it

Every agent needs a budget: a model that never stops is a bill that never stops. When the budget ends a run in the middle, the next run starts with an empty context. Whatever the first run learned is lost unless it wrote it down in the environment. Here the first session gets 8 steps, and a second, fresh agent continues on the same repository.

harness = CodingHarness.from_copy(TOY)
first = await solve(harness, max_steps=8)
print(f"session 1: status {first.status}, {first.context.current_step} steps, "
      f"tests now: {harness.run_tests()}")
print("PROGRESS.md:\n" + harness.progress())
second = await solve(harness, max_steps=15)
print(f"session 2: status {second.status}, {second.context.current_step} steps")
show_trajectory(second)
session 1: status max_steps, 8 steps, tests now: TestSummary(passed=10, failed=1, failing=['tests/test_words.py::test_word_count_extra_spaces'])
PROGRESS.md:
- tests/test_slug.py::test_slug_punctuation_at_ends: slugify left hyphens at the ends; strip them
- tests/test_stats.py::test_median_even: median of an even count returned one middle value; average the two

session 2: status complete, 6 steps
[user] Make the test suite pass.
[agent -> bash] {"command": "cat PROGRESS.md 2>/dev/null || echo 'no progress file yet'"}
    [bash ok] exit code 0 - tests/test_slug.py::test_slug_punctuation_at_ends: slugify left hyphens at the ...
[agent -> bash] {"command": "python -m pytest -q --tb=short"}
    [bash ok] exit code 1 ........F.. [100%] =================================== FAILURES =================...
[agent -> bash] {"command": "cat textkit/words.py"}
    [bash ok] exit code 0 """Counting words.""" def word_count(text: str) -> int: """Number of words in ``t...
[agent -> bash] {"command": "python - <<'PATCH'\nfrom pathlib import Path\np = Path('textkit/words.py')\ns = ...
    [bash ok] exit code 0
[agent -> bash] {"command": "python -m pytest -q --tb=short"}
    [bash ok] exit code 0 ........... [100%] 11 passed in <t>s
[agent] All 11 tests pass. Fixed in this session: test_word_count_extra_spaces. PROGRESS.md lists eve...
--- status: complete, steps: 6

The second session read the two lines the first one left, ran the tests, and fixed the last bug in six steps. In this toy the test suite alone would also have told it what was left; a progress file earns its keep on longer tasks, where it records what is not visible in the code: which approach was tried and abandoned, which test is known to be flaky, what the next step was going to be. Long-running agent harnesses keep such a file (with a feature list and a git log) for exactly this reason.

6. What the sandbox stops

The agent can run any command, so the sandbox, not the model, decides what a command can reach. Four probes:

probe = CodingHarness(harness.repo, timeout_s=2.0)
checks = {
    "runaway command": "sleep 30",
    "write outside the repo": "echo pwned > /etc/agent_was_here",
    "open a network socket": "python -c \"import socket; "
                             "socket.create_connection(('93.184.215.14', 80), 2)\" "
                             "2>&1 | tail -n 1; exit ${PIPESTATUS[0]}",
    "write inside the repo": "echo ok > scratch.txt && cat scratch.txt",
}
for label, command in checks.items():
    first, *rest = probe.bash(command).splitlines()
    print(f"{label:<24} {first}")
    if rest:
        print(f"{'':<24} {' '.join(rest)[:66]}")
print(f"\nisolation: {probe.sandbox.isolation}")
runaway command          killed: wall-clock time limit
write outside the repo   exit code 1
                          [stderr] /bin/bash: /etc/agent_was_here: Operation not permitted
open a network socket    exit code 1
                         PermissionError: [Errno 1] Operation not permitted
write inside the repo    exit code 0
                         ok

isolation: sandbox-exec: no network (loopback included); writes only inside the work directory; home directory unreadable except the work directory and Python

On Linux there is no sandbox-exec, so the file-system and network rows would succeed: use a container or a micro-VM there, as production coding agents do. The sandbox is the coding agent’s version of Module 12’s egress allowlist: a hard limit that does not depend on the model behaving.

7. From this toy to a real coding agent

  this notebook                             a production coding agent
  ----------------------------------------  ------------------------------------------
  scripted fixer with three known bugs      a model reading unfamiliar code
  one bash tool                             bash, plus often file-view and edit tools
                                            with line numbers (SWE-agent's "ACI")
  repo copy in a macOS sandbox              a container per task, snapshot and reset
  11 tests, about a second per run          minutes per run: choose which tests to run
  PROGRESS.md                               progress notes + a feature list + git commits
  max_steps = 15                            budgets in steps, tokens, money and wall time
  pass/fail on the toy repo                 SWE-bench, Terminal-Bench: hundreds of tasks

The same loop, with a verifier (the tests) at the end, is also the environment used to train coding agents with reinforcement learning, as in Notebook 11b: the reward is whether the hidden tests pass.

Try this

  • Add a fourth bug to a copy of toy_repo without adding it to FIXES. What does the scripted fixer do, and what would you want a real agent to do?
  • Give the harness max_chars=300, keep="both". Is a third of the budget for the head still the right split?
  • Make format_observation report the test summary separately from the output (parse it with parse_pytest), so that a pipe can no longer hide a failure.
  • Replace the scripted fixer with a live model (set MODEL, for example MODEL=anthropic/claude-sonnet-5-5) and the toy repo with a small project of your own. Which harness setting matters most?
nb.usage()
model callsinput tokensoutput tokenscost
63 (fake: 63)≈ 60,189≈ 2,368≈ USD 0.0697 (reference price)