Lesson 53.5 · 5 of 5 · 8 min read · Reviewed 24 Nov 2026
Lab: a bug-fixing agent in a sandbox
By the end, you can
- Build a bug-fixing loop that edits code and reruns tests until they pass.
- Run the loop inside a sandbox with a step limit and a clean exit report.
This lab puts 103.1 and 103.4 together. You build a small agent that fixes a real bug in a tiny project, inside a sandboxSandbox: An isolated environment that limits what code or an agent can reach, such as files, network or credentials., and stops on its own.
The setup
The project is one function and three tests:
# cart.py
def cart_total(prices, coupon=0):
total = sum(prices)
return total - coupon # bug: can go below zero
# tests
assert cart_total([10, 5]) == 15
assert cart_total([10], coupon=3) == 7
assert cart_total([4], coupon=10) == 0 # fails: returns -6
In the Playground version, the “sandbox” is a dictionary of file contents run with exec in a fresh namespace, and the “model” is a scripted function that proposes edits. The shape of the loop is exactly what a real coding agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. does.
The loop you build
copy files into sandbox
for step in 1..max_steps:
result = run_tests(sandbox)
if result.all_passed: break
edit = propose_edit(sandbox, result.failures) # the model's job
if edit touches a test file: reject it, tell the model why
apply edit in sandbox
report: steps used, diff, final test log
Rules that make it safe
| Rule | Why |
|---|---|
| Work on a copy | The original files are untouched until a person accepts the diff |
| Step limit (for example 5) | A stuck agent stops and reports instead of looping |
| Edits to tests are rejected | The agent cannot “fix” a bug by changing what counts as correct |
| Every run uses a fresh namespace | One run cannot leak state into the next |
| Output is only the diff and log | Nothing else leaves the box |
A real-machine version
On your own machine you can run the same loop with a real model and a container:
- Put the project in a folder and write a
Dockerfilethat installs pytest. - Run each test pass with
docker run --rm --network none -v "$PWD":/workand a time limit. - Let the model see only the last 40 lines of pytest output.
- Write the model’s edit as a unified diff, apply it with
git apply, and keep the diff.
Keep any API key in an environment variable on your machine, never in the project files.
What good looks like
A good run reads: step 1, 1 failed; step 2, edit cart.py line 3 to clamp at zero; step 3, 3 passed; stopped. The diff is one line. If you seed a harder bug, the agent should hit the step limit and say what it tried, not claim success.
When to use it
This loop is the core of every coding agent. Once it works on a toy project, the hard parts in real use are the repo map (53.1), the quality of the tests, and how strict the sandbox is (53.4).
Key points
- The lab loop is: run tests, read the failure, propose one small edit, apply it in the sandbox, run tests again.
- The sandbox holds a copy of the code; only the final diff and the test log come out.
- A step limit and a 'no edits to tests' rule stop the agent from looping forever or cheating.
Fix a bug in a sandboxed loop
Build a bug-fixing loop that runs tests on a sandbox copy, applies one small edit per step, rejects edits to tests and stops at a step limit.
You will have: A loop that prints a step-by-step log, the final diff and the test results, with the original files unchanged.
Steps
- Copy FILES into a sandbox dictionary; never change FILES itself.
- Write run_tests that executes cart.py and the tests in a fresh namespace with exec and returns passes and failures.
- Use the scripted propose_edit (standing in for the model) and reject any edit to a test file.
- Loop until all tests pass or the step limit of 5 is reached, logging each step.
- Print a unified diff of cart.py with difflib, and confirm FILES is unchanged.
Done when
- The log ends with '3 passed' within 5 steps.
- The rejected test edit is reported in the log.
- The original FILES still contains the buggy line.
Open in the Playground No API key needed.
Starter code (Python)
import difflib
FILES = {
"cart.py": "def cart_total(prices, coupon=0):\n total = sum(prices)\n return total - coupon\n",
"test_cart.py": "assert cart_total([10, 5]) == 15\nassert cart_total([10], coupon=3) == 7\nassert cart_total([4], coupon=10) == 0\n",
}
def propose_edit(files, failures, step):
# A scripted stand-in for the model: first it tries to cheat, then it fixes the code.
if step == 1:
return {"file": "test_cart.py", "old": "== 0", "new": "== -6"}
return {"file": "cart.py", "old": "return total - coupon", "new": "return max(0, total - coupon)"}
def run_tests(files):
# TODO: exec files["cart.py"] in a fresh dict, then run each line of test_cart.py
# in that namespace; count passes and collect failing lines
return {"passed": 0, "failed": ["not run"]}
sandbox = dict(FILES)
for step in range(1, 6):
result = run_tests(sandbox)
print("step", step, ":", result["passed"], "passed,", len(result["failed"]), "failed")
if not result["failed"]:
break
edit = propose_edit(sandbox, result["failed"], step)
# TODO: reject edits to test files; otherwise apply the edit to the sandbox (not FILES)
Show a solution
import difflib
FILES = {
"cart.py": "def cart_total(prices, coupon=0):\n total = sum(prices)\n return total - coupon\n",
"test_cart.py": "assert cart_total([10, 5]) == 15\nassert cart_total([10], coupon=3) == 7\nassert cart_total([4], coupon=10) == 0\n",
}
def propose_edit(files, failures, step):
if step == 1:
return {"file": "test_cart.py", "old": "== 0", "new": "== -6"}
return {"file": "cart.py", "old": "return total - coupon", "new": "return max(0, total - coupon)"}
def run_tests(files):
ns = {}
exec(files["cart.py"], ns)
passed, failed = 0, []
for line in files["test_cart.py"].splitlines():
try:
exec(line, dict(ns))
passed += 1
except AssertionError:
failed.append(line)
return {"passed": passed, "failed": failed}
sandbox = dict(FILES)
for step in range(1, 6):
result = run_tests(sandbox)
print("step", step, ":", result["passed"], "passed,", len(result["failed"]), "failed")
if not result["failed"]:
print("stopped: all tests pass")
break
edit = propose_edit(sandbox, result["failed"], step)
if edit["file"].startswith("test_"):
print(" rejected: edit to", edit["file"], "(tests define done)")
continue
sandbox[edit["file"]] = sandbox[edit["file"]].replace(edit["old"], edit["new"])
print(" applied edit to", edit["file"])
else:
print("stopped: step limit reached")
diff = difflib.unified_diff(FILES["cart.py"].splitlines(), sandbox["cart.py"].splitlines(), "a/cart.py", "b/cart.py", lineterm="")
print("\n".join(diff))
print("originals unchanged:", "return total - coupon" in FILES["cart.py"])
Finished the chapter? Take the chapter check.