Coding and Software-Engineering Agents › A worked example: fixing a date parser
Language AI HandbookAll chapters The small datekit fixture splits three dash-separated integer fields. Its only calendar check rejects February 29 in years that lack a leap day. The issue says it rejects a leap-year date. We will locate the failing test, apply a constrained edit and review the result.
The repository layout is:
datekit/
datekit/
__init__.py
parse.py <- contains parse_iso_date
tests/
test_parse.py <- the visible test suite
The buggy parser reads three dash-separated integer fields. Its leap-year check accepts years divisible by 4 and rejects every year divisible by 100. The Gregorian rule makes one exception for century years divisible by 400, so the fixture wrongly rejects 2000.
PythonIn [7]Expand
# datekit/datekit/parse.py (buggy)
def _is_leap(year):
if year % 100 == 0:
return False # BUG: 2000 is a leap year (divisible by 400)
return year % 4 == 0
def parse_iso_date(s):
year, month, day = (int(p) for p in s.split("-"))
if month == 2 and day == 29 and not _is_leap(year):
raise ValueError(f"invalid date: {s}")
return (year, month, day)The visible test only covers a non-century leap year (2024) and a non-leap year (2023), so it passes. A new test, written by the reporter, exercises 2000-02-29 (a leap year, divisible by 400) and fails. This is our red state. The agent's task is to turn it green and keep the rest of the suite green without touching the tests.
We are going to build this entire pipeline in code. Everything below runs with the standard library, uses no network, and produces the same output each run. Let's set it up.
A temporary fixture repository
We create a private temporary directory holding a fixed parser and its visible tests. The parser illustrates leap-year behavior. The exercise does not implement a general ISO date validator, and dates outside that scope are not graded as if it did.
PythonIn [8]Expand
import ast
import difflib
import re
import subprocess
import sys
from pathlib import Path
from tempfile import TemporaryDirectory
from textwrap import dedent
fixture_directory = TemporaryDirectory(prefix="datekit-notebook-")
ROOT = Path(fixture_directory.name)
(ROOT / "datekit").mkdir()
(ROOT / "tests").mkdir()
(ROOT / "datekit" / "__init__.py").write_text(
"from .parse import parse_iso_date\n", encoding="utf-8"
)
(ROOT / "datekit" / "parse.py").write_text(
dedent(""" def _is_leap(year):
if year % 100 == 0:
return False # century years are incorrectly rejected
return year % 4 == 0
def parse_iso_date(s):
year, month, day = (int(p) for p in s.split("-"))
if month == 2 and day == 29 and not _is_leap(year):
raise ValueError(f"invalid date: {s}")
return (year, month, day)
""").lstrip(),
encoding="utf-8",
)
(ROOT / "tests" / "test_parse.py").write_text(
dedent(""" import unittest
from datekit import parse_iso_date
class DateParserTests(unittest.TestCase):
def test_regular_leap_year(self):
self.assertEqual(parse_iso_date("2024-02-29"), (2024, 2, 29))
def test_ordinary_non_leap_year(self):
with self.assertRaises(ValueError):
parse_iso_date("2023-02-29")
def test_century_leap_year(self):
self.assertEqual(parse_iso_date("2000-02-29"), (2000, 2, 29))
""").lstrip(),
encoding="utf-8",
)
VISIBLE_FILES = tuple(sorted(p.relative_to(ROOT) for p in ROOT.rglob("*.py")))
SOURCE_ONLY = Path("datekit/parse.py")
def snapshot(root=ROOT):
return {
p.relative_to(root): p.read_text(encoding="utf-8")
for p in sorted(root.rglob("*"))
if p.is_file()
}
initial_files = snapshot()The setup writes the known source and test files and saves a before-edit snapshot. It compares relative paths and decoded UTF-8 text. The snapshot does not preserve filesystem metadata, and text reading normalizes line endings.
Each run begins with a new directory. The directory makes the example easy to reset and keeps it separate from any working project.
The read-only navigation tools
The navigation functions read an enumerated set of fixture files. The search output has a hit limit, and the reader only accepts a known visible file. For production access, enforce the repository boundary independently of tool prompts.
PythonIn [9]Expand
def grep(pattern, max_hits=20):
"""Search the fixed visible fixture files, returning at most max_hits rows."""
if max_hits < 1:
return []
regex = re.compile(pattern)
hits = []
for path in VISIBLE_FILES:
for number, line in enumerate(
(ROOT / path).read_text().splitlines(), 1
):
if regex.search(line):
hits.append((str(path), number, line.strip()))
if len(hits) == max_hits:
return hits
return hits
def read_file(relative_path, start=1, end=None):
"""Read a known visible fixture file using a 1-indexed inclusive line range."""
path = Path(relative_path)
if path not in VISIBLE_FILES:
raise ValueError("Choose one of the visible fixture files.")
lines = (ROOT / path).read_text().splitlines()
if start < 1 or (end is not None and end < start):
raise ValueError("Invalid line range.")
return "\n".join(lines[start - 1 : end]), len(lines)
def repo_map():
"""Summarize the fixed visible Python files and their top-level symbols."""
out = []
for path in VISIBLE_FILES:
tree = ast.parse((ROOT / path).read_text())
names = [
node.name
for node in tree.body
if isinstance(node, (ast.FunctionDef, ast.ClassDef))
]
out.append((str(path), names))
return outConsoleOut [10]Expand
== Repository map == datekit/__init__.py: [] datekit/parse.py: ['_is_leap', 'parse_iso_date'] tests/test_parse.py: ['DateParserTests'] == grep for 'leap' == datekit/parse.py:1: def _is_leap(year): datekit/parse.py:8: if month == 2 and day == 29 and not _is_leap(year): tests/test_parse.py:7: def test_regular_leap_year(self): tests/test_parse.py:10: def test_ordinary_non_leap_year(self): tests/test_parse.py:14: def test_century_leap_year(self):
The repository map names the parser functions and the visible test class. Searching for leap brings both the implementation and the relevant test names into view. The test body gives the exact input and expected tuple.
The max_hits cap on grep is a small but important design choice. Without it, a search for a common token like leap in a large repository could return thousands of lines and flood the model's context. The cap forces the first search to return a triage list, not an exhaustive answer, and the agent's next move is to refine the query if twenty hits are not enough. This mirrors how a human uses grep | head interactively. The cap is not a limitation; it is a context-discipline mechanism.
Now the agent reads the two files that matter, spending context only where the grep pointed.
ConsoleOut [11]Expand
--- datekit/parse.py (10 lines) ---
def _is_leap(year):
if year % 100 == 0:
return False # century years are incorrectly rejected
return year % 4 == 0
def parse_iso_date(s):
year, month, day = (int(p) for p in s.split("-"))
if month == 2 and day == 29 and not _is_leap(year):
raise ValueError(f"invalid date: {s}")
return (year, month, day)
--- tests/test_parse.py (15 lines) ---
import unittest
from datekit import parse_iso_date
class DateParserTests(unittest.TestCase):
def test_regular_leap_year(self):
self.assertEqual(parse_iso_date("2024-02-29"), (2024, 2, 29))
def test_ordinary_non_leap_year(self):
with self.assertRaises(ValueError):
parse_iso_date("2023-02-29")
def test_century_leap_year(self):
self.assertEqual(parse_iso_date("2000-02-29"), (2000, 2, 29))The two reads locate _is_leap in datekit/parse.py and test_century_leap_year in the visible suite. The target expects (2000, 2, 29). Establish that this is the failing behavior before touching the source.
Running the tests to establish the red state
Run the notebook interpreter with -m unittest discover to select a known fixture suite. The child runs in the fixture’s working directory with a fixed command, a timeout and a small replacement environment. These settings make the local exercise repeatable. Filesystem and network isolation require separate controls.
PythonIn [12]Expand
def run_suite(root=ROOT, test_dir="tests"):
"""Run the named trusted fixture suite with the notebook's Python."""
if test_dir not in {"tests", "independent_checks"}:
raise ValueError("Choose a known local fixture suite.")
proc = subprocess.run(
[
sys.executable,
"-B",
"-m",
"unittest",
"discover",
"-s",
test_dir,
"-v",
],
cwd=root,
env={"PYTHONIOENCODING": "utf-8", "PYTHONNOUSERSITE": "1"},
capture_output=True,
text=True,
timeout=20,
check=False,
)
output = proc.stdout + proc.stderr
statuses = dict(
re.findall(r"^(test_\w+) \(.*\) \.\.\. (ok|FAIL|ERROR)$", output, re.M)
)
errors = re.findall(r"^(?:ValueError|AssertionError): (.+)$", output, re.M)
return {"returncode": proc.returncode, "status": statuses, "errors": errors}
red = run_suite()ConsoleOut [13]Expand
Visible suite before patch, exit: 1 ERROR test_century_leap_year ok test_ordinary_non_leap_year ok test_regular_leap_year Failure detail: ['invalid date: 2000-02-29']
Before editing, two cases pass and the century case errors with the exact invalid-date exception. An unrelated import or setup error would not establish the expected red state. Check the target test’s identity and error before applying the known repair.
Verbose unittest output names each fixture test and reports ok, FAIL, or ERROR. Together with the process exit status, that map lets the example distinguish a fixed target from missing or newly failing tests.
A minimal patch, enforced
Now the agent proposes a change. In a real system this would be the model's output; here we simulate the fact of the proposal and focus on the machinery that surrounds it: applying the patch as a surgical edit and enforcing constraints on what may change.
The repair changes the return value in the century branch. A century divisible by 400 is a leap year. Ordinary years continue through the existing divisibility-by-four branch. Apply the edit only after checking the red result.
PythonIn [14]Expand
def apply_patch(relative_path, old, new):
"""Edit the one allowed source file in the trusted fixture."""
if Path(relative_path) != SOURCE_ONLY:
raise PermissionError("Only the fixture parser can change.")
path = ROOT / SOURCE_ONLY
if path.is_symlink() or path.parent.is_symlink() or not path.is_file():
raise ValueError("The expected fixture file is missing or replaced.")
text = path.read_text(encoding="utf-8")
if text.count(old) != 1:
raise ValueError("The old fragment must match exactly once.")
path.write_text(text.replace(old, new), encoding="utf-8")PythonIn [15]Expand
target_test = "test_century_leap_year"
assert red["returncode"] == 1 and red["status"].get(target_test) == "ERROR"
assert red["errors"] == ["invalid date: 2000-02-29"]
old = " return False # century years are incorrectly rejected"
new = " return year % 400 == 0"
apply_patch(SOURCE_ONLY, old, new)
print("Patch applied to", SOURCE_ONLY)ConsoleOut [15]Expand
Patch applied to datekit/parse.py
The patch function checks the permitted fixture path and requires one exact old fragment. It rejects an unexpected file and a missing or duplicated match before writing. The final full-tree snapshot checks which paths changed.
The fixture keeps the verifier files outside the write allowlist. The patch helper checks the file again before opening it. The two snapshots reveal changes to file membership and decoded text.
The green step, and a check the agent cannot see
Run the visible tests again. Separately, the evaluator copies the two source files into a new temporary directory and creates its own tests there. Those tests were outside the earlier search and patch workflow. The reader can see both sides of the simulation.
The separate checks compare century cases from 1700 to 2500 with calendar.isleap and include an unrelated ordinary date. This tests additional years beyond the visible examples.
PythonIn [16]Expand
INDEPENDENT_CHECKS = dedent(""" import unittest
from calendar import isleap
from datekit import parse_iso_date
class IndependentDateChecks(unittest.TestCase):
def test_century_boundaries_against_standard_library(self):
for year in range(1700, 2501, 100):
with self.subTest(year=year):
example = f"{year}-02-29"
if isleap(year):
self.assertEqual(parse_iso_date(example), (year, 2, 29))
else:
with self.assertRaises(ValueError):
parse_iso_date(example)
def test_unrelated_ordinary_date(self):
self.assertEqual(parse_iso_date("2023-01-15"), (2023, 1, 15))
""").lstrip()
def run_held_out(candidate_files):
"""Evaluate a snapshot with grader-owned checks outside the fixture tree."""
with TemporaryDirectory(prefix="datekit-checks-") as other:
other_root = Path(other)
(other_root / "datekit").mkdir()
(other_root / "independent_checks").mkdir()
for relative_path in (Path("datekit/__init__.py"), SOURCE_ONLY):
(other_root / relative_path).write_text(
candidate_files[relative_path], encoding="utf-8"
)
(other_root / "independent_checks" / "test_dates.py").write_text(
INDEPENDENT_CHECKS, encoding="utf-8"
)
return run_suite(other_root, "independent_checks")The independent suite includes century cases such as 1900, 2000 and 2400, as well as an ordinary date. For example, a proposal that accepts only the two known leap years in the visible suite would still fail the independent century cases.
The 1900 case catches a rule that admits all century leap days. The 2400 case catches an edit specific to 2000. The ordinary date checks that the change leaves that unrelated behavior intact.
PythonIn [17]Expand
green = run_suite()
held = run_held_out(snapshot())
pass_to_pass = [
name for name, status in red["status"].items() if status == "ok"
]
print("Visible suite after patch, exit:", green["returncode"])
for name, status in green["status"].items():
print(f" {status:5s} {name}")
print("Target fixed:", green["status"].get(target_test) == "ok")
print(
"Earlier passes preserved:",
all(green["status"].get(name) == "ok" for name in pass_to_pass),
)
print("Independent suite:", held["status"])ConsoleOut [17]Expand
Visible suite after patch, exit: 0
ok test_century_leap_year
ok test_ordinary_non_leap_year
ok test_regular_leap_year
Target fixed: True
Earlier passes preserved: True
Independent suite: {'test_century_boundaries_against_standard_library': 'ok', 'test_unrelated_ordinary_date': 'ok'}The target changes from an error to a pass, earlier visible passes remain passes, and the independent suite succeeds. Check that the same visible test identities remain present. These results support the patch for the cases evaluated and leave approval to a reviewer.
- F2P (fail-to-pass): the target test went red to green. Here,
test_century_leap_year. - P2P (pass-to-pass): the previously passing tests still pass. Here, the other two visible tests.
- Held-out behavioral checks: the agent-invisible suite passes. It catches the tested century special cases and checks one ordinary date.
Require each of the three checks before sending the patch to review. Other special cases can still pass these checks, so the reviewer reads the proposed rule and considers where the tests leave gaps.
A tiny review pass
The last step is review. We can't automate a human judgment in a chapter, but we can automate the mechanical review checks that a reviewer would otherwise do by hand, and we can produce the diff that a human would look at. A reviewer model (a second LLM, or the human) then reads the diff and the check summary.
For this fixture, compare every file present before or after the edit. Require just datekit/parse.py to differ, then check the full-file diff contains exactly one removed and one added line.
PythonIn [18]Expand
def mechanical_review(before, after):
paths = set(before) | set(after)
changed = {p for p in paths if before.get(p) != after.get(p)}
if changed != {SOURCE_ONLY}:
raise AssertionError(
f"Unexpected changed paths: {sorted(map(str, changed))}"
)
diff = list(
difflib.unified_diff(
before[SOURCE_ONLY].splitlines(),
after[SOURCE_ONLY].splitlines(),
fromfile=f"before/{SOURCE_ONLY}",
tofile=f"after/{SOURCE_ONLY}",
lineterm="",
)
)
added_lines = sum(line.startswith("+") for line in diff[2:])
removed_lines = sum(line.startswith("-") for line in diff[2:])
if (added_lines, removed_lines) != (1, 1):
raise AssertionError(
"This fixture expects one removed and one added line."
)
return diffPythonIn [19]Expand
assert green["returncode"] == 0 and held["returncode"] == 0
assert red["status"].keys() == green["status"].keys()
assert green["status"].get(target_test) == "ok"
assert all(green["status"].get(name) == "ok" for name in pass_to_pass)
changed_diff = mechanical_review(initial_files, snapshot())
print("Only the allowlisted file changed. Full-file diff:")
print("\n".join(changed_diff))ConsoleOut [19]Expand
Only the allowlisted file changed. Full-file diff:
--- before/datekit/parse.py
+++ after/datekit/parse.py
@@ -1,6 +1,6 @@
def _is_leap(year):
if year % 100 == 0:
- return False # century years are incorrectly rejected
+ return year % 400 == 0
return year % 4 == 0
def parse_iso_date(s):The full-file diff shows one replaced line and its surrounding code. Read that context along with the before/after test results. A small patch makes review easier, but the size check alone cannot verify the intent or the behavior.
The mechanical checks enforce scope and preserve the complete diff. A reviewer still checks the Gregorian rule, surrounding assumptions, and coverage of additional cases.
Hand over the patch with its observed test results and mechanical scope check. The complete diff shows what changed. The reviewer uses that evidence to decide whether the change is ready.
The worked example in one loop
Before moving on, let's restate the whole pipeline as the loop a real agent would run, because the narrative above is what the loop does over one task. The loop is: map the repository, grep for the failing test's subject, read the candidate files, run the tests to confirm red, propose a minimal patch, apply it under constraint, run visible tests, run held-out checks, run mechanical review, and hand off the diff. Every step is either a read-only observation or a constrained mutation followed by a verifier. Nothing in the loop trusts the model's confidence. The model's output is a candidate action; the environment decides whether it was any good.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!