Skip to main content

babregen step by step

From an empty directory to a regenerated module, with the package mathregen

Author

Thomas Bartz-Beielstein

Published

November 28, 2026

This tutorial introduces babregen on a package that is small enough to read in full. The package, mathregen, has two functions: one returns the n-th Fibonacci number, the other the n-th prime. We build it in the order a developer would work in, and at every step we run the real babregen command and show what it prints.

The reader is expected to know Python packaging and pytest. Nothing about babregen or about regenerative software is assumed. babregen is the successor of spotregen. A reader who knows spotregen 0.15 finds the differences on the page Coming from spotregen.

Note 1: How to run this page

Keep step-by-step.qmd as a Quarto source and run it from top to bottom. Do not treat it as an interactive notebook. Quarto already executes the cells through a Jupyter kernel, so nothing is gained by converting the page, and running single cells is fragile for three reasons.

  • The cells share one stateful sandbox. Every cell acts on the same throw-away git repository, and later cells rely on what earlier ones copied, edited, committed or reset. A cell that runs twice or out of order fails or plants a fault a second time.
  • The page is a capture device, not the workflow. The workflow of babregen is shell commands in a package repository. The cells only replay those commands so that the output on the page is real.
  • The model run is not executed. Section 11.2 reads an archive, and its command lines are printed from the run records, not run.
purpose how
build the page make doc at the root of the babregen repository, with the whole site (uses the freeze in _freeze/), or uv run quarto render docs/tutorials/step-by-step.qmd (runs every cell again, about a minute)
work on the text uv run quarto preview docs/tutorials/step-by-step.qmd at the root of the babregen repository
debug one cell run all cells above it first, with the kernel of .venv; restart the kernel before a second pass
try babregen yourself the exercise sheet: the same commands in a terminal, in a clone of the example
watch this page in a terminal the script walkthrough.sh: every step of this page as shell commands, in a temporary git repository, with a pause after each section

An interactive run needs docs/tutorials/ as its working directory, because the cells import _mathregen_demo.py, and the kernel of the environment of babregen (.venv at the root of the repository), because the cells call babregen and pytest with the interpreter of the kernel. The cells therefore run the babregen of the checkout, not a release from PyPI.

NoteHow the output on this page is made

Every output block is captured from a real run when the page is rendered. The package is the example mathregen/ of the repository babregen-examples. Nothing of it is copied into the babregen repository. The helper docs/tutorials/_mathregen_demo.py clones that repository once, at the tag babregen-v0.1.0, into the ignored directory .examples/ at the root of the babregen repository. The environment variable BABREGEN_EXAMPLES names an existing checkout to use instead. The cells copy the files of mathregen/ into a throw-away git repository, one stage at a time, and call babregen, pytest and git there. <repo> in the output is the root of that repository and <tmp> its parent directory. This render used babregen 0.1.0.

The executed output is frozen in _freeze/, as for every page of this site. A render runs the cells only when the source of the page changed, so make doc needs neither the clone nor a network connection as long as the page is unchanged.

The one exception is the model run in Section 11.2. A language model is not deterministic, so it ran once, and the page reads its archive in mathregen/regen/runs/ of the clone.

1 The idea

Definition 1 (Regenerative software) Software is regenerative, in the sense of Chad Fowler, when a module can be deleted and written again from knowledge that lives outside its implementation. The code is disposable; the knowledge around it is the asset.

A language model can write a module in seconds. Whether the new module may replace the old one is a different question, and the code alone does not answer it. The answer needs to be written down somewhere else: what the module promises, how the promise is tested, who relies on it, and why it is the way it is. babregen keeps this knowledge in a tracked directory regen/ and checks it against the source tree.

Fowler names seven primitives. babregen gives each a record, a family of check IDs and a command (Table 1). The rest of this page meets them one by one.

Table 1: The seven primitives and their place in babregen.
primitive question it answers where it is recorded check IDs command
intent What must stay true and why? [[intent]] of a unit record INTENT context
compilation Which architecture must the code fit into? regen/architecture.toml, public and depends_on of a unit record COMPILE check
evaluation How is a replacement judged? evaluation files with the marker regen EVAL mutate, score
provenance Why is the system this way? regen/decisions/<id>.toml, hashes in the run.toml of a run PROV context, check
pace How fast may this layer change? pace of a unit record, policy in [pace] PACE measures, context
deletion Who notices if it is gone? [[consumers]] of a unit record DELETE deletion-test, score, local
compaction What can be removed? none of its own: findings on the other records COMPACT compact
NoteWhere the terms come from

The definitions on this page follow the article Deleting Code Without Losing Knowledge: A Case Study of Regenerative Software with Local Language Models (Bartz-Beielstein, Klimm and Hinterleitner, 2026), which applies spotregen, the predecessor of babregen, to itself, and the questions of Table 1 are taken from it. One word differs. The article calls a module file that is offered in place of the module of a unit a rebuild; the tool, and with it this page, calls it a candidate.

2 The package skeleton

mathregen is an ordinary package with a src/ layout, managed with uv. babregen is one development dependency. It needs Python 3.13 or later and has no dependencies of its own.

uv init --lib mathregen
cd mathregen
uv add --dev pytest ruff babregen

The result is this pyproject.toml. The marker regen at the end is the only line that has to do with babregen; Section 6 uses it.

sb.add("pyproject.toml", "Makefile", "README.md", ".gitignore")
sb.show("pyproject.toml")
# pyproject.toml
[project]
name = "mathregen"
version = "0.1.0"
description = "Math functions kept regenerable with babregen: Fibonacci numbers and primes"
readme = "README.md"
requires-python = ">=3.13"
# Standard library only (regen/architecture.toml, conventions).
dependencies = []

[build-system]
requires = ["uv_build>=0.9.18"]
build-backend = "uv_build"

[dependency-groups]
dev = [
    "pytest>=9.0.2",
    "ruff>=0.3.0",
    "babregen>=0.1.0",
]

[tool.pytest.ini_options]
testpaths = ["tests"]
markers = [
    "regen: durable evaluations of a regenerable unit (regen/units/*.toml); they must survive a rewrite of the implementation",
]

[tool.ruff]
line-length = 88
target-version = "py313"
# Archived candidates are evidence and are kept as the generator wrote them.
extend-exclude = ["regen/runs"]
sb.babregen("--version")
$ babregen --version
babregen 0.1.0
[exit 0]

3 Two functions and their unit tests

Nothing in this step is special to babregen. We write the code and its tests first.

Each function gets a module of its own. babregen works on modules: a regenerable unit is one module, so two modules can be deleted and rebuilt independently of each other.

sb.add("src", "scripts", "tests/test_fibonacci.py", "tests/test_primes.py")
sb.tree()
.gitignore
Makefile
README.md
pyproject.toml
scripts/table.py
src/mathregen/__init__.py
src/mathregen/fibonacci.py
src/mathregen/primes.py
tests/test_fibonacci.py
tests/test_primes.py
sb.show("src/mathregen/fibonacci.py")
# src/mathregen/fibonacci.py
"""Fibonacci numbers."""

__all__ = ["fibonacci"]


def fibonacci(n: int) -> int:
    """Return the n-th Fibonacci number, counted from ``fibonacci(0) == 0``.

    The sequence is 0, 1, 1, 2, 3, 5, 8, ...: every value is the sum of the two before
    it. The result is exact for every index, because only integers are added.

    Args:
        n: Index of the number, an ``int`` that is not negative.

    Returns:
        int: The n-th Fibonacci number.

    Raises:
        TypeError: If `n` is not an ``int``, or is a ``bool``.
        ValueError: If `n` is negative.

    Examples:
        ```{python}
        from mathregen.fibonacci import fibonacci

        print([fibonacci(n) for n in range(10)])
        ```
    """
    if isinstance(n, bool) or not isinstance(n, int):
        raise TypeError(f"n must be an int, not {type(n).__name__}")
    if n < 0:
        raise ValueError(f"n must not be negative, got {n}")
    previous, current = 0, 1
    for _ in range(n):
        previous, current = current, previous + current
    return previous

The module for the primes has a private helper, _is_prime.

sb.show("src/mathregen/primes.py", 1, 16)
sb.show("src/mathregen/primes.py", 38, 46)
# src/mathregen/primes.py, lines 1 to 16
"""Prime numbers."""

__all__ = ["nth_prime"]


def _is_prime(k: int) -> bool:
    """Whether `k` is prime, by trial division up to its square root."""
    if k < 2:
        return False
    divisor = 2
    while divisor * divisor <= k:
        if k % divisor == 0:
            return False
        divisor += 1
    return True

# src/mathregen/primes.py, lines 38 to 46
        ```
    """
    if isinstance(n, bool) or not isinstance(n, int):
        raise TypeError(f"n must be an int, not {type(n).__name__}")
    if n < 1:
        raise ValueError(f"n must be at least 1, got {n}")
    found = 0
    candidate = 1
    while found < n:

Both functions state three things that a reader could not guess from the name:

Table 2: The contract of the two functions.
fibonacci(n) nth_prime(n)
first index 0, with fibonacci(0) == 0 1, with nth_prime(1) == 2
below the first index ValueError ValueError
not an int, or a bool TypeError TypeError

The package re-exports both names, and a script uses them:

sb.show("src/mathregen/__init__.py")
sb.python("scripts/table.py")
# src/mathregen/__init__.py
"""Math functions, kept regenerable with babregen."""

from mathregen.fibonacci import fibonacci
from mathregen.primes import nth_prime

__all__ = ["fibonacci", "nth_prime"]
$ python scripts/table.py
 n  fibonacci(n)  nth_prime(n)
 1             1             2
 2             1             3
 3             2             5
 4             3             7
 5             5            11
 6             8            13
 7            13            17
 8            21            19
 9            34            23
10            55            29
[exit 0]

The unit tests pass. The tests of primes call the private helper _is_prime. This detail matters later: such a test is coupled to one implementation.

sb.pytest("-q")
$ pytest -q
......                                                                   [100%]
6 passed in 0.00s
[exit 0]

4 The architecture

Definition 2 (Architecture) The file regen/architecture.toml is the compilation target: the shape that every module of the package must fit into, whoever writes it. There is exactly one.

It names the package, lists for every module which other modules it may import, states the conventions that all code follows, and leaves some choices open on purpose.

sb.add("regen/architecture.toml")
sb.edit("regen/architecture.toml", 'decisions = ["regen-protocol"]', "decisions = []")
sb.show("regen/architecture.toml")
# regen/architecture.toml
# Compilation target of mathregen: the shape every regenerated module must fit into.
# `babregen check` enforces [allowed] on the whole src/ tree.

package = "mathregen"
source_dir = "src"

# Provenance of this file: the protocol under which a unit is regenerated.
decisions = []

# Where consumers are searched: Python files below scan_dirs, text of doc_globs.
scan_dirs = ["src", "tests", "scripts"]
doc_globs = ["README.md"]

conventions = [
    "Python >= 3.13, standard library only: [project].dependencies stays empty",
    "one module per function; the package __init__ re-exports the public names",
    "arguments and results are Python ints; no floating-point arithmetic",
    "Google-style docstring with a live ```{python} Examples block for every public function",
]

open_choices = [
    "the algorithm (iteration or fast doubling; trial division or a sieve)",
    "private helpers and their names",
    "the wording of error messages",
]

known_cycles = []

[pace]
fast = "the durable evaluations (make regen-eval) and a clean babregen check"
slow = "the durable evaluations, a clean babregen check and a decision record"

# Module -> modules of the package it may import. The two function modules import
# nothing; only the package __init__ imports them.
[allowed]
"__init__" = ["fibonacci", "primes"]
fibonacci = []
primes = []

(The final file names a decision record in decisions. That record is written in Section 7, so the list is empty here.)

Three parts deserve a remark. [allowed] says that the two function modules import nothing from the package and that only __init__ imports them. open_choices tells a future author, human or model, what is deliberately not fixed: the algorithm is free. [pace] states the verification that a change requires; a unit declares one of the paces fast, medium or slow, and the policy of that pace applies to it. The pace follows the position of a unit in the architecture: a foundation that others build on changes slowly and under more verification, an experiment may change fast. babregen does not carry the verification out. It checks that no slow unit depends on a faster one and copies the policy into the bundle (Definition 8). The policy is declared and displayed, not enforced.

Example 1 (The first check)  

sb.babregen("check")
$ babregen check
regen check: 0 units, 0 errors, 0 warnings
[exit 0]

babregen check reads regen/ and the source tree and prints one line per finding and a summary. It finds regen/architecture.toml by searching upwards from the current directory. There are no units yet, and the imports in src/ respect [allowed].

5 A unit record, drafted by the tool

Definition 3 (Unit) A unit is the part of the program that a unit record regen/units/<stem>.toml describes. It is implemented by one module, which a regeneration may replace. The record states what the module promises (intent), which tests judge it (evaluations) and who depends on it (consumers). The file fibonacci.toml describes the module mathregen.fibonacci; the name of the file is the only link. A unit is identified by its record, not by its current implementation: the module is what is deleted and rebuilt, the record is what survives.

babregen new-unit drafts a record from what the tree can tell.

Example 2 (The draft for fibonacci)  

sb.babregen("new-unit", "fibonacci", "--pace", "fast")
sb.show("regen/units/fibonacci.toml")
$ babregen new-unit fibonacci --pace fast
wrote regen/units/fibonacci.toml
next: write the intent items and evaluations, then run babregen check
still open (babregen check will report):
regen/units/fibonacci.toml:4: error INTENT01 declares no intent item (a unit without intent cannot be regenerated)
[exit 0]
# regen/units/fibonacci.toml
# Drafted by `babregen new-unit` on 2026-11-29. Review every field;
# `babregen check` fails with INTENT01 until the first [[intent]] item is written.

summary = "Fibonacci numbers."
pace = "fast"
public = ["fibonacci"]
depends_on = []
evaluations = []  # e.g. tests/test_regen_eval_fibonacci.py, marked pytest.mark.regen
unit_tests = ["tests/test_fibonacci.py"]

# Intent: what must stay true for any implementation, and why. Ask "what would a
# competent stranger get wrong?" and turn every incident that touched the module into
# an item with an evaluation and a decision record. `babregen add-intent` appends one.
#
# [[intent]]
# id = "FIB-1"
# scope = ""  # where the requirement applies
# invariant = ""  # what must remain true
# reason = ""  # why the invariant matters
# evaluations = []  # test functions in the evaluation files above
# decisions = []  # ids of regen/decisions/<id>.toml

[[consumers]]
ref = "scripts/table.py"
kind = "code"
note = ""

[[consumers]]
ref = "src/mathregen/__init__.py"
kind = "code"
note = ""

[[consumers]]
ref = "README.md"
kind = "doc"
note = ""

# Add what the tree cannot show as kind = "external": downstream files
# (ref = "<repo>:<path>"), scheduled runs and people (a free-text ref).
# `babregen add-consumer` appends a consumer; say in its note what it relies on.

The tool filled in what it could read: the summary from the docstring, the public name from __all__, the unit test, and three consumers. It found scripts/table.py and README.md although neither imports mathregen.fibonacci directly: both use the name that the package re-exports, and the scan follows re-exports.

What only a person can supply is left open, and the draft says so. It fails the check on purpose, so that a scaffold never passes unreviewed. The command has printed the finding already, and the check repeats it:

sb.babregen("check")
$ babregen check
regen/units/fibonacci.toml:4: error INTENT01 declares no intent item (a unit without intent cannot be regenerated)
regen check: 1 units, 1 errors, 0 warnings
[exit 1]

INTENT01 is the first finding of this tutorial. A finding line is {path}:{line}: {level} {id} {message}. The prefix of the ID is the primitive it belongs to, here intent. The exit code is 1: the check fails.

Example 3 (What a check ID means) babregen explain ID prints the condition of a check, a wrong and a corrected fragment of a record, and the usual fix. The fragments use the names of the sample repository of babregen, not those of mathregen.

sb.babregen("explain", "INTENT01")
$ babregen explain INTENT01
INTENT01 (error): a unit record declares no intent item

Wrong, in regen/units/core.calc.toml:

    # no [[intent]] item in this record

Right:

    [[intent]]
    id = "C-1"
    scope = "add"
    invariant = "add(a, b) == a + b"
    reason = "arithmetic"
    evaluations = ["test_add"]
    decisions = ["why-add"]

Fix: Write at least one [[intent]] item: scope, invariant, reason, and the evaluations that check it. Ask what a competent stranger would get wrong. `babregen add-intent UNIT` appends the block.
[exit 0]

The command needs no regen/ tree, so it works before the first record exists. It is the first thing to try when a finding is new.

6 Evaluations and intent

Definition 4 (Durable evaluation) A durable evaluation is a test that uses only the public names of a unit and says nothing about how the module works. It stays valid when the module is deleted and written again. Evaluation files carry the pytest marker regen.

The unit tests of Section 3 travel with the implementation and may be rewritten with it. The durable evaluations are the opposite: they belong to the knowledge that stays. They are the judge of every future implementation. The question that tells the two apart is Fowler’s: would this assertion still be meaningful if we replaced the implementation tomorrow? The records of a unit and its durable evaluations together are its specification.

sb.add("tests/test_regen_eval_fibonacci.py")
sb.show("tests/test_regen_eval_fibonacci.py")
# tests/test_regen_eval_fibonacci.py
"""Durable evaluations of the unit mathregen.fibonacci (regen/units/fibonacci.toml).

They use the public function only and say nothing about how it computes, so they stay
valid when the module is deleted and written again.
"""

import pytest

from mathregen.fibonacci import fibonacci

pytestmark = pytest.mark.regen


def test_the_sequence_starts_at_index_zero_with_zero_and_one():
    assert fibonacci(0) == 0
    assert fibonacci(1) == 1
    assert [fibonacci(n) for n in range(11)] == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]


def test_every_value_is_the_sum_of_the_two_before_it():
    for n in range(2, 200):
        assert fibonacci(n) == fibonacci(n - 1) + fibonacci(n - 2)


def test_a_large_value_is_an_exact_int():
    assert fibonacci(100) == 354224848179261915075
    assert fibonacci(200) == 280571172992510140037611932413038677189525
    assert type(fibonacci(200)) is int


def test_a_negative_index_raises_value_error():
    for n in (-1, -2, -100):
        with pytest.raises(ValueError):
            fibonacci(n)


@pytest.mark.parametrize("n", [1.0, 2.5, "3", None, [1]])
def test_an_index_that_is_not_an_int_raises_type_error(n):
    with pytest.raises(TypeError):
        fibonacci(n)


def test_a_bool_index_raises_type_error():
    for n in (True, False):
        with pytest.raises(TypeError):
            fibonacci(n)

Definition 5 (Intent item) An intent item states one requirement in three parts: the scope (where it applies), the invariant (what must remain true) and the reason (why it matters). It names the evaluations that check it and the decisions behind it.

A good intent item answers the question “what would a competent stranger get wrong?” For fibonacci there are three such things: the first index, the temptation of the closed formula, and the fact that Python treats True as the integer 1. We replace the draft by the finished record.

sb.add("regen/units/fibonacci.toml")
sb.show("regen/units/fibonacci.toml")
# regen/units/fibonacci.toml
summary = """
The n-th Fibonacci number, `fibonacci(n)`, for an index counted from 0. The module is
one public function without state."""
pace = "fast"
public = ["fibonacci"]
depends_on = []
evaluations = ["tests/test_regen_eval_fibonacci.py"]
unit_tests = ["tests/test_fibonacci.py"]

[[intent]]
id = "FIB-1"
scope = "fibonacci"
invariant = """
`fibonacci(0) == 0`, `fibonacci(1) == 1`, and `fibonacci(n) == fibonacci(n - 1) +
fibonacci(n - 2)` for every n >= 2."""
reason = """
Two conventions are in use: the sequence 1, 1, 2, ... counted from index 1, and the
sequence 0, 1, 1, 2, ... counted from index 0. An implementation that picks the other
one is off by one index for every caller."""
evaluations = [
    "test_the_sequence_starts_at_index_zero_with_zero_and_one",
    "test_every_value_is_the_sum_of_the_two_before_it",
]
decisions = ["indexing-conventions"]

[[intent]]
id = "FIB-2"
scope = "fibonacci"
invariant = """
The result is an `int` and is exact for every index, however large:
`fibonacci(100) == 354224848179261915075`."""
reason = """
The closed formula with the golden ratio is the obvious shortcut, and in floating-point
arithmetic it gives wrong last digits from about n = 70 on. Callers use the values as
exact integers."""
evaluations = ["test_a_large_value_is_an_exact_int"]
decisions = ["integers-only"]

[[intent]]
id = "FIB-3"
scope = "fibonacci"
invariant = """
A negative index raises `ValueError`. An index that is not an `int` raises `TypeError`;
this includes `bool`, and a `float` with an integral value such as `3.0`."""
reason = """
A silent result for `fibonacci(True)` or `fibonacci(3.0)` hides a mistake of the
caller, and Python accepts both wherever an `int` is expected unless the function
refuses them."""
evaluations = [
    "test_a_negative_index_raises_value_error",
    "test_an_index_that_is_not_an_int_raises_type_error",
    "test_a_bool_index_raises_type_error",
]
decisions = ["integers-only"]

[[consumers]]
ref = "src/mathregen/__init__.py"
kind = "code"
note = "re-exports fibonacci"

[[consumers]]
ref = "scripts/table.py"
kind = "code"
note = "prints the first values"

[[consumers]]
ref = "README.md"
kind = "doc"
note = "states the index convention and shows fibonacci(10)"

The evaluation file is now listed under evaluations, and every intent item names the test functions that check it. The evaluation file needs no entry under consumers: declaring it as an evaluation is enough.

The prose of the record is wrapped over several lines inside """, without a backslash at the line ends. babregen folds a prose field: a line break and the blanks around it load as one space. The reason of FIB-1 covers three lines in the file and is one line when it is loaded:

reason = tomllib.loads(sb.read("regen/units/fibonacci.toml"))["intent"][0]["reason"]
print(reason.strip().count("\n") + 1, "lines in the file,", fold(reason).count("\n") + 1, "line as loaded")
print(fold(reason)[:60] + "...")
3 lines in the file, 1 line as loaded
Two conventions are in use: the sequence 1, 1, 2, ... counte...

A blank line inside a prose field is an error, and so is a line break in a name. With the finished record the check reads:

sb.babregen("check")
$ babregen check
regen/units/fibonacci.toml:24: error PROV01 intent FIB-1: unknown decision 'indexing-conventions'
regen/units/fibonacci.toml:37: error PROV01 intent FIB-2: unknown decision 'integers-only'
regen/units/fibonacci.toml:54: error PROV01 intent FIB-3: unknown decision 'integers-only'
regen check: 1 units, 3 errors, 0 warnings
[exit 1]

INTENT01 is resolved. The new findings are of the family PROV, provenance: each intent item cites a decision that does not exist yet.

7 Decisions

Definition 6 (Decision record) A decision record regen/decisions/<id>.toml is a provenance record. It states what drove a decision, what was decided, who approved it, which alternatives were rejected and why, the evidence, and the assumptions the decision rests on. It may carry a review date (review_after), after which the check reports it as due for review.

The reason of an intent item says why an invariant matters. The decision record says why this invariant was chosen and not another one. Without it, the next author sees a rule and cannot tell whether it is a considered choice or an accident.

sb.add("regen/decisions")
sb.show("regen/decisions/indexing-conventions.toml")
# regen/decisions/indexing-conventions.toml
title = "Fibonacci numbers count from 0, primes count from 1"
date = 2026-11-27
status = "active"
driver = """
Both sequences have two conventions for the first index, and the package has to state
one of them for each function before the first caller relies on it."""
decision = """
`fibonacci` counts from 0 with fibonacci(0) == 0, the convention of the OEIS (A000045)
and of most programming texts. `nth_prime` counts from 1 with nth_prime(1) == 2, the
convention p_1 = 2 of number theory (OEIS A000040). Each function follows the
convention of its own literature; the README states both."""
approved_by = "bartzbeielstein"
evidence = ["file:README.md", "url:https://oeis.org/A000045", "url:https://oeis.org/A000040"]
assumes = ["callers read the README or the docstring before they index"]

[[alternatives]]
option = "count both from 0"
rejected_because = "a zeroth prime exists in no text; every table of primes would be shifted by one"

[[alternatives]]
option = "count both from 1"
rejected_because = "fibonacci(1) == fibonacci(2) == 1 leaves no place for 0, and the identities of the sequence are stated for F(0) = 0"

The second record, integers-only, explains why a bool and a float are refused. The third, regen-protocol, fixes how a unit is regenerated with a model; Section 11.2 needs it, and the architecture file cites it.

We add the records of the second unit, primes, which were written the same way, and the full architecture file.

sb.add("tests", "regen/units", "regen/decisions", "regen/architecture.toml")
sb.babregen("check")
$ babregen check
regen check: 2 units, 0 errors, 0 warnings
[exit 0]

Two units, no finding. The evaluations pass as well; -m regen selects them by their marker.

sb.pytest("-q", "-m", "regen")
$ pytest -q -m regen
....................                                                     [100%]
20 passed, 6 deselected in 0.01s
[exit 0]

7.1 Help in the editor

The records are TOML files that are written by hand, so the editor should know their schema. babregen schema KIND prints the JSON Schema of a record kind (architecture, unit or decision). The example keeps the three schemas in regen/schemas/.

(sb.root / "regen" / "schemas").mkdir()
for kind in ("architecture", "unit", "decision"):
    sb.babregen("schema", kind, "-o", f"regen/schemas/{kind}.schema.json")
$ babregen schema architecture -o regen/schemas/architecture.schema.json
wrote regen/schemas/architecture.schema.json
[exit 0]
$ babregen schema unit -o regen/schemas/unit.schema.json
wrote regen/schemas/unit.schema.json
[exit 0]
$ babregen schema decision -o regen/schemas/decision.schema.json
wrote regen/schemas/decision.schema.json
[exit 0]

These files are the ones that the example ships. The file .taplo.toml binds each schema to its records. The VS Code extension Even Better TOML reads it and then completes keys, offers the allowed values (for pace: fast, medium, slow) and marks a key that the schema does not know while you type.

sb.add(".taplo.toml", ".vscode")
sb.show(".taplo.toml", 7)
# .taplo.toml, lines 7 to 23
[[rule]]
include = ["regen/architecture.toml"]

[rule.schema]
path = "regen/schemas/architecture.schema.json"

[[rule]]
include = ["regen/units/*.toml"]

[rule.schema]
path = "regen/schemas/unit.schema.json"

[[rule]]
include = ["regen/decisions/*.toml"]

[rule.schema]
path = "regen/schemas/decision.schema.json"

The directory .vscode/ adds a task that runs babregen check and turns every finding line into an entry of the Problems panel, and snippets for an intent item, a consumer and a decision record. A schema knows the keys and their types. It does not know the names in the source tree, so the check remains the judge (Editor support).

This is the state that is worth a commit.

sb.commit("mathregen 0.1.0 with its regen records")
$ git add -A && git commit -m 'mathregen 0.1.0 with its regen records'
1f3cc4a mathregen 0.1.0 with its regen records

8 What the check catches

A passing check is not informative on its own. We plant two faults that happen in practice and watch the check. The check parses files and runs nothing. It reports where the records and the code disagree, with an error for what must be fixed and a warning for what asks for attention.

Example 4 (An undeclared script and a forbidden import) A colleague adds a script that uses nth_prime. Someone else lets primes import the Fibonacci module, perhaps for an experiment that was never removed.

sb.write(
    "scripts/first_primes.py",
    "from mathregen.primes import nth_prime\n\n"
    "print([nth_prime(n) for n in range(1, 21)])\n",
)
sb.append("src/mathregen/primes.py", "\nfrom mathregen.fibonacci import fibonacci\n")
sb.babregen("check")
$ babregen check
src/mathregen/primes.py:52: error COMPILE02 'primes' imports 'mathregen.fibonacci', but architecture.toml allows only []
regen/units/fibonacci.toml:1: error DELETE01 src/mathregen/primes.py depends on the unit but is not a declared consumer
src/mathregen/primes.py:52: error COMPILE07 mathregen.primes: imports 'mathregen.fibonacci' which is not in depends_on
regen/units/primes.toml:1: error DELETE01 scripts/first_primes.py depends on the unit but is not a declared consumer
regen check: 2 units, 4 errors, 0 warnings
[exit 1]

The two faults give four findings:

COMPILE02
The architecture allows primes no import inside the package. This is the compilation target at work: the shape of the package cannot erode unnoticed.
COMPILE07
The unit record of primes lists no dependency, but the module has one.
DELETE01, for fibonacci
primes.py now depends on the unit fibonacci and is not declared as its consumer.
DELETE01, for primes
The new script depends on the unit primes and is not declared.

DELETE01 protects the deletion test. If primes were regenerated today, nobody would know that scripts/first_primes.py has to keep working. The fix for the script is to declare it; the fix for the import is to remove it.

The block of a consumer need not be typed. babregen add-consumer appends it to the record. It infers the kind from the path and refuses a path that does not exist. --dry-run prints the block and writes nothing:

sb.reset()
sb.write(
    "scripts/first_primes.py",
    "from mathregen.primes import nth_prime\n\n"
    "print([nth_prime(n) for n in range(1, 21)])\n",
)
note = "prints the first twenty primes"
sb.babregen("add-consumer", "primes", "scripts/first_primes.py", "--note", note, "--dry-run")
sb.babregen("add-consumer", "primes", "scripts/first_primes.py", "--note", note)
sb.babregen("check")
$ babregen add-consumer primes scripts/first_primes.py --note 'prints the first twenty primes' --dry-run

[[consumers]]
ref = "scripts/first_primes.py"
kind = "code"
note = "prints the first twenty primes"
[exit 0]
$ babregen add-consumer primes scripts/first_primes.py --note 'prints the first twenty primes'
wrote regen/units/primes.toml
next: run babregen check
[exit 0]
$ babregen check
regen check: 2 units, 0 errors, 0 warnings
[exit 0]

(The script was only an illustration. The sandbox returns to the commit of Section 7.)

Example 5 (A misspelled evaluation name) Many checks compare a name in a record with the source tree, so a frequent fault is a typo. We drop one underscore from the name of an evaluation in intent item FIB-3.

sb.edit(
    "regen/units/fibonacci.toml",
    '"test_a_bool_index_raises_type_error"',
    '"test_a_bool_index_raises_typeerror"',
)
sb.babregen("check")
$ babregen check
regen/units/fibonacci.toml:52: error EVAL03 intent FIB-3: evaluation 'test_a_bool_index_raises_typeerror' not found; a similar name exists: 'test_a_bool_index_raises_type_error'
tests/test_regen_eval_fibonacci.py:43: warning COMPACT05 mathregen.fibonacci: evaluation 'test_a_bool_index_raises_type_error' is not linked to any intent item
regen check: 2 units, 1 errors, 1 warnings
[exit 1]

EVAL03 is reported at the line of the wrong name, and its message ends with the name that was probably meant. The second finding is the other side of the same typo: the evaluation exists and no intent item names it any more (COMPACT05, a warning).

A script or a CI job should not take such a line apart. babregen check --format json prints the findings as one document, in which the suggestion is a field of its own:

doc = json.loads(sb.capture("check", "--format", "json"))
print(doc["summary"])
for finding in doc["findings"]:
    print(finding["id"], finding["path"], finding["line"], "suggestion:", finding["suggestion"])
{'units': 2, 'errors': 1, 'warnings': 1}
EVAL03 regen/units/fibonacci.toml 52 suggestion: test_a_bool_index_raises_type_error
COMPACT05 tests/test_regen_eval_fibonacci.py 43 suggestion: None

A clean check shows that the records agree with the code. It cannot see what was never written down, so it does not show that the records hold enough knowledge to write a unit again, or that the evaluations would notice a wrong module. The next three sections test both.

9 The deletion test

Definition 7 (Deletion test) The deletion test asks of one unit, in Fowler’s words: could we delete this and regenerate it by Friday, and if not, what is in the way? It has four components.

  1. Blast radius. Who would notice that the unit is gone? Its consumers are declared.
  2. Knowledge outside the implementation. Every intent item names evaluations, and the decisions behind it are on record.
  3. Rebuild. The module is deleted and written again from that knowledge alone.
  4. Judgement. The new module is judged without the old code as the oracle.

babregen deletion-test checks components 1 and 2 and deletes nothing.

Example 6 (The deletion test of fibonacci)  

sb.babregen("deletion-test", "fibonacci")
$ babregen deletion-test fibonacci
# Deletion test: mathregen.fibonacci

File `src/mathregen/fibonacci.py`, pace fast.

## Blast radius

| consumer | kind | declared | note |
|---|---|---|---|
| `README.md` | doc | yes | states the index convention and shows fibonacci(10) |
| `scripts/table.py` | code | yes | prints the first values |
| `src/mathregen/__init__.py` | code | yes | re-exports fibonacci |
| `tests/test_fibonacci.py` | test | yes |  |
| `tests/test_regen_eval_fibonacci.py` | test | yes | evaluation |

## Knowledge outside the implementation

| intent | evaluations | decisions |
|---|---|---|
| FIB-1 | 2 | indexing-conventions |
| FIB-2 | 1 | integers-only |
| FIB-3 | 3 | integers-only |

Verdict: regenerable. 3 intent items, all evaluated; 5 dependents, all declared.
[exit 0]

The blast radius lists every file that breaks if the unit breaks: the three declared consumers and the unit’s own tests. The second table is the knowledge outside the implementation. The verdict is the exit code: 0 for regenerable.

This verdict is a precondition for an attempt, not its result. Components 3 and 4 are the subject of Section 11: babregen score judges a given candidate, and babregen local deletes, rebuilds and judges.

Definition 8 (Regeneration bundle) The bundle of a unit is the document that an author receives in order to write the module again. babregen context assembles it from the records as a single Markdown file. It is the whole input that describes the unit to an author. Of the module it keeps the public contract, that is signatures and docstrings. It contains no implementation, neither of the unit nor of a module the unit may import. The only code it copies in full is the evaluation files.

Example 7 (The bundle of fibonacci)  

bundle = sb.capture("context", "fibonacci")
print(*[line for line in bundle.splitlines() if line.startswith("#")], sep="\n")
# Regeneration bundle: mathregen.fibonacci
## Purpose
## Architecture (compilation target)
## Intent
### FIB-1
### FIB-2
### FIB-3
## Provenance
### indexing-conventions: Fibonacci numbers count from 0, primes count from 1
### integers-only: Arguments and results are Python ints, nothing else
## Public contract (signatures and docstrings, no bodies)
## Durable evaluations
## Consumers (must keep working)

The headings show the structure: purpose, architecture, intent, provenance, the public contract, the evaluations and the consumers. The section with the contract is the part of the module that survives:

start = bundle.index("## Public contract")
print(bundle[start : bundle.index("## Durable evaluations")].rstrip())
## Public contract (signatures and docstrings, no bodies)

```python
"""Fibonacci numbers."""


def fibonacci(n: int) -> int:
    """Return the n-th Fibonacci number, counted from ``fibonacci(0) == 0``.

    The sequence is 0, 1, 1, 2, 3, 5, 8, ...: every value is the sum of the two before
    it. The result is exact for every index, because only integers are added.

    Args:
        n: Index of the number, an ``int`` that is not negative.

    Returns:
        int: The n-th Fibonacci number.

    Raises:
        TypeError: If `n` is not an ``int``, or is a ``bool``.
        ValueError: If `n` is negative.

    Examples:
        ```{python}
        from mathregen.fibonacci import fibonacci

        print([fibonacci(n) for n in range(10)])
        ```
    """
    ...
```

The body is replaced by .... The loop that computes the numbers is nowhere in the bundle:

print("previous + current" in sb.read("src/mathregen/fibonacci.py"))
print("previous + current" in bundle)
True
False

Everything that we wrote in the last three sections ends up in this one document. It is what a model sees in Section 11.2, and nothing else.

10 How good are the evaluations?

Example 8 (The measures of both units)  

sb.babregen("measures")
$ babregen measures
| unit | pace | coverage | decisions | consumers | code | record | decision lines | evaluation lines | spec | ratio |
|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| mathregen.fibonacci | fast | 3/3 | 2 | 3 | 36 | 69 | 43 | 46 | 158 | 4.4 |
| mathregen.primes | fast | 3/3 | 2 | 3 | 50 | 68 | 43 | 54 | 165 | 3.3 |
| total | - | 6/6 | 4 | 6 | 86 | 137 | 86 | 100 | 323 | 3.8 |
[exit 0]

coverage is the intent coverage: the share of the intent items that name an evaluation which exists, 3 of 3 for each unit. It is not code coverage. It counts the recorded promises that have a judge, not the lines that ran. The columns from code on are line counts. Unit record, cited decisions and evaluation files add up to the specification size, and the last column is its ratio to the code: for two functions of a dozen lines the knowledge is about four times as long as the implementation. That is the price of being able to delete the code.

Intent coverage says that every recorded promise has a judge. It does not say that all necessary promises are recorded, and it does not say that the evaluations are sharp. For the last point, babregen plants faults.

Definition 9 (Mutation analysis and mutation score) babregen mutate makes small changes to the module, one at a time (a mutant), with a fixed set of operators, and runs the durable evaluations on each. A mutant is killed if an evaluation fails or ends in an error, or if the run exceeds its time limit, and survives otherwise. The mutation score is the share of killed mutants among all mutants. Every survivor then needs a verdict by a person: gap (an evaluation is missing), output (the mutant changes only text that no intent item pins) or equivalent (no promised behaviour changes).

Example 9 (All mutants of fibonacci are killed)  

sb.babregen("mutate", "fibonacci", "--timeout", "10")
$ babregen mutate fibonacci --timeout 10
M001 killed (5 failed)
M002 killed (1 failed)
M003 killed (4 failed)
M004 killed (1 failed)
M005 killed (2 failed)
M006 killed (2 failed)
M007 killed (1 failed)
M008 killed (2 failed)
M009 killed (2 failed)
M010 killed (3 failed)
M011 killed (3 failed)
# Mutation score: mathregen.fibonacci

10 evaluations in tests/test_regen_eval_fibonacci.py, 11 mutants.

Base commit `1f3cc4a1c91234f0b60ca9f760b87b673337bb76`, working tree clean; Python 3.14.2, pytest 9.2.0.

Mutation score: 11/11 (100 %).
[exit 0]

To see what a survivor looks like, suppose we had forgotten one evaluation, the one for bool.

Example 10 (A forgotten evaluation lets two mutants survive)  

text = sb.read("tests/test_regen_eval_fibonacci.py")
cut = text.index("def test_a_bool_index_raises_type_error")
sb.write("tests/test_regen_eval_fibonacci.py", text[:cut].rstrip() + "\n")
sb.babregen("mutate", "fibonacci", "--timeout", "10", drop="killed (")
$ babregen mutate fibonacci --timeout 10
M002 SURVIVED (survived)
M004 SURVIVED (survived)
# Mutation score: mathregen.fibonacci

9 evaluations in tests/test_regen_eval_fibonacci.py, 11 mutants.

Base commit `1f3cc4a1c91234f0b60ca9f760b87b673337bb76`, working tree dirty (the mutants were made from it); Python 3.14.2, pytest 9.2.0.

## Surviving mutants

| mutant | line | operator | original | mutated |
|---|---:|---|---|---|
| M002 | 29 | boolean | `isinstance(n, bool) or not isinstance(n, int)` | `isinstance(n, bool) and (not isinstance(n, int))` |
| M004 | 30 | raise | `raise TypeError(f'n must be an int, not {type(n).__name__}')` | `pass` |

Mutation score: 9/11 (82 %).
[exit 1]

Two mutants survive, and the exit code is 1. M004 is the instructive one: the whole raise TypeError is replaced by pass, and the five evaluations with two floats, a string, None and a list still pass. The reason is that Python raises a TypeError by itself a few lines later, when it compares a string with 0 or calls range with a float. Only a bool gets through. The explicit type check exists for the bool alone, and only the bool evaluation proves that it is there. Both survivors have the verdict gap, and the remedy is the evaluation that we restore now.

Not every survivor is a gap. The unit primes keeps three:

sb.babregen("mutate", "primes", "--timeout", "5", drop="failed)")
$ babregen mutate primes --timeout 5
M003 SURVIVED (survived)
M004 SURVIVED (survived)
M007 killed (timeout)
M008 killed (timeout)
M010 SURVIVED (survived)
M012 killed (timeout)
M014 killed (timeout)
M015 killed (timeout)
M026 killed (timeout)
M029 killed (timeout)
# Mutation score: mathregen.primes

10 evaluations in tests/test_regen_eval_primes.py, 31 mutants.

Base commit `1f3cc4a1c91234f0b60ca9f760b87b673337bb76`, working tree clean; Python 3.14.2, pytest 9.2.0.

## Surviving mutants

| mutant | line | operator | original | mutated |
|---|---:|---|---|---|
| M003 | 9 | return | `return False` | `return None` |
| M004 | 9 | constant | `False` | `True` |
| M010 | 13 | return | `return False` | `return None` |

Mutation score: 28/31 (90 %).
[exit 1]

All three sit in the private helper _is_prime. M003 and M004 change what the helper returns for a number below 2, and nth_prime never asks it about such a number. M010 returns None in place of False, which the caller cannot tell apart. No evaluation through the public function can kill these mutants, and none should: they change nothing that the contract promises. Their verdict is equivalent. Equivalent mutants stay in the denominator of the score, so 28 of 31 is a lower bound: all 28 mutants that are not equivalent are killed. A survivor is a question to a person, and the answer is a judgement that draws the line between a promise of the unit and a habit of its code. The mutants marked timeout turned the search into an endless loop.

11 Regeneration

We now do what the records were written for: replace a module by a new one that was written without looking at the old one.

Definition 10 (The acceptance rule) babregen score UNIT FILE judges a candidate module. It puts the candidate in the place of the original in a scratch copy of the last commit and runs the evaluations of the unit, its unit tests and its dependents. The candidate is accepted if and only if the evaluations have no failure, no error and at least one pass, and no dependent fails. The dependents that are run are the declared consumers of kind code below the source directory, which must import, and the docstring examples of the public names, taken from the original module, which must run against the candidate. Unit tests are recorded and never decide. The rule has the name accept/1, and run.toml records it next to every verdict.

score calls no model and never writes to the working tree. It judges against the last commit, so the project must lie in a git repository. The project, that is the folder with regen/, may be the repository itself, as in the sandbox of this page, or a subfolder of it, as mathregen/ in babregen-examples.

11.1 A candidate written by hand

The example keeps three candidates in candidates/, outside the source directory. We add and commit them.

sb.add("candidates")
sb.commit("three candidates to judge")
$ git add -A && git commit -m 'three candidates to judge'
58f81e6 three candidates to judge

The first candidate computes the Fibonacci numbers by fast doubling, an algorithm that has nothing in common with the loop of the original. The architecture left the algorithm open.

print(sb.read("candidates/fibonacci_doubling.py"))
"""Fibonacci numbers."""

__all__ = ["fibonacci"]


def _pair(n: int) -> tuple[int, int]:
    """Return (F(n), F(n + 1)) by fast doubling."""
    if n == 0:
        return 0, 1
    a, b = _pair(n // 2)
    c = a * (2 * b - a)
    d = a * a + b * b
    return (d, c + d) if n % 2 else (c, d)


def fibonacci(n: int) -> int:
    """Return the n-th Fibonacci number, counted from ``fibonacci(0) == 0``.

    Args:
        n: Index of the number, an ``int`` that is not negative.

    Returns:
        int: The n-th Fibonacci number.

    Raises:
        TypeError: If `n` is not an ``int``, or is a ``bool``.
        ValueError: If `n` is negative.
    """
    if type(n) is not int:
        raise TypeError(f"n must be an int, not {type(n).__name__}")
    if n < 0:
        raise ValueError(f"n must not be negative, got {n}")
    return _pair(n)[0]

Example 11 (A different algorithm is accepted)  

record = sb.score("fibonacci", "fibonacci_doubling")
$ babregen score fibonacci candidates/fibonacci_doubling.py --out ../runs/fibonacci_doubling
... (42 lines before)
run directory: <tmp>/runs/fibonacci_doubling
[exit 0]
accepted = true   (rule accept/1)
evaluations 10 passed, 0 failed, 0 errors
unit tests  2 passed, 0 failed, 0 errors
dependents  2 passed, 0 failed

The ten evaluations pass. The two dependents are the import of the package and the docstring example of the original, run against the new module. The exit code is 0. scripts/table.py and README.md are declared consumers too, but they lie outside src/, so the judge does not run them: they are part of the blast radius that a person checks.

The second candidate takes the shortcut that intent item FIB-2 warns about.

print(sb.read("candidates/fibonacci_binet.py"))
"""Fibonacci numbers."""

__all__ = ["fibonacci"]

PHI = (1 + 5**0.5) / 2


def fibonacci(n: int) -> int:
    """Return the n-th Fibonacci number by the closed formula with the golden ratio."""
    if n < 0:
        raise ValueError(f"n must not be negative, got {n}")
    return round(PHI**n / 5**0.5)

Example 12 (The closed formula is rejected)  

record = sb.score("fibonacci", "fibonacci_binet")
$ babregen score fibonacci candidates/fibonacci_binet.py --out ../runs/fibonacci_binet
... (42 lines before)
run directory: <tmp>/runs/fibonacci_binet
[exit 1]
accepted = false   (rule accept/1)
evaluations 5 passed, 5 failed, 0 errors
unit tests  2 passed, 0 failed, 0 errors
dependents  2 passed, 0 failed

The candidate is rejected with exit code 1. Note what did not catch it: the unit tests pass and the dependents pass, because they look at the first ten values only. The durable evaluations for exactness and for the argument type are what stand between this module and the package.

The third candidate replaces primes by a sieve.

Example 13 (Accepted although the unit tests fail)  

record = sb.score("primes", "primes_sieve")
$ babregen score primes candidates/primes_sieve.py --out ../runs/primes_sieve
... (42 lines before)
run directory: <tmp>/runs/primes_sieve
[exit 0]
accepted = true   (rule accept/1)
evaluations 10 passed, 0 failed, 0 errors
unit tests  0 passed, 0 failed, 1 errors
dependents  2 passed, 0 failed

The unit tests end in an error: they import _is_prime, and a sieve has no such helper. The candidate is accepted all the same. This is the division of labour from Section 6: the unit tests belong to the old implementation and are regenerated with the code, and only the durable evaluations judge.

11.2 A candidate written by a model

babregen local does the same with a language model as the author. A driver sends the bundle to a model that a local server such as LM Studio serves on this machine, takes the module from the reply, and judges it with the same rule. If evaluations fail, the failures go back to the model for a repair, up to --attempts times. Before the first session the driver runs the evaluations and the dependents on the original module and does not start unless they pass, so a later rejection is not a verdict about the machine (Scoring and regeneration has every option). The model is memoryless: it has no tools and sees nothing but a fixed instruction and the bundle, neither the deleted file, nor its unit tests, nor the history.

The command wants to know what produced a run. Four options are required: the model, the SHA-256 of its files, which the command records and cannot verify, the context length it was loaded with, and --protocol, the id of an active decision record that fixes the procedure before the first session.

sb.show("regen/decisions/regen-protocol.toml", 1, 20)
# regen/decisions/regen-protocol.toml, lines 1 to 20
title = "A unit of mathregen is regenerated with one local model under fixed options"
date = 2026-11-27
status = "active"
driver = """
`babregen local` asks for an active decision record that fixes the protocol of a run
before the first session, so that the archive says what produced a candidate and what
counts as accepted. Each unit is run once."""
decision = """
(1) Generator: Qwen3-Coder-30B-A3B-Instruct, MLX 4 bit, served by LM Studio on
localhost as `qwen/qwen3-coder-30b`, with the --model-sha256 listed under assumes and
loaded with a context length of 32768.
(2) Options: --template chatml --reasoning none (the model has no reasoning mode),
--attempts 3, --temperature 0.7, --top-p 0.8, --top-k 20, --seed 1, and the other
options at their defaults. No file is passed with --allow: the generator sees the
bundle and nothing else.
(3) Runs: one run for each unit, mathregen.fibonacci and mathregen.primes, after a
canary run of the same model. A run that the driver aborts is a machine failure and is
repeated; a completed run is not repeated, whatever its verdict.
(4) Acceptance: the rule accept/1 of babregen, and nothing else. An accepted candidate
is archived and reported; it does not replace the module in src/ without a review."""

These are the commands that were run, once, with babregen 0.0.1 on 2026-11-28. The first is a canary: a session whose prompt asks the model to read the original module, to list a directory, to run a shell command and to write files. It passes on what the driver recorded, never on the model’s own account.

babregen local fibonacci --model qwen/qwen3-coder-30b --model-sha256 6b189caf...7683 \
    --context-length 32768 --protocol regen-protocol \
    --template chatml --reasoning none --canary

for unit in fibonacci primes; do
    babregen local $unit --model qwen/qwen3-coder-30b --model-sha256 6b189caf...7683 \
        --context-length 32768 --protocol regen-protocol \
        --template chatml --reasoning none \
        --attempts 3 --temperature 0.7 --top-p 0.8 --top-k 20 --seed 1
done

Every run leaves a directory under regen/runs/:

for path in sorted(RUNS.iterdir()):
    print(path.name)
print()
print(*sorted(p.name for p in run_dir("fibonacci").iterdir()), sep="\n")
2026-11-28-canary-qwen-qwen3-coder-30b
2026-11-28-fibonacci-qwen-qwen3-coder-30b-seed1
2026-11-28-primes-qwen-qwen3-coder-30b-seed1

bundle.md
dependents.txt
evaluations-1.txt
evaluations-2.txt
fibonacci-1.py
fibonacci-2.py
report.md
run.toml
sessions.jsonl
unit_tests.txt

Example 14 (The run of fibonacci) run.toml is the record of the run. These are its verdict and its attempts:

run = run_record("fibonacci")
print("accepted =", str(run["accepted"]).lower(), f"  (rule {run['rule']})")
print("model    =", run["generator"]["model"])
print("base     =", run["base"]["commit"][:12])
for a in run["attempt"]:
    print(
        f"attempt {a['n']}: {a['evaluations_passed']} passed, "
        f"{a['evaluations_failed']} failed, {a['evaluations_errors']} errors"
    )
for s in run["session"]:
    print(f"session {s['n']}: {s['kind']:8s} {s['completion_tokens']:5d} tokens {s['seconds']:5.1f} s")
accepted = true   (rule accept/1)
model    = qwen/qwen3-coder-30b
base     = e1a764a186e2
attempt 1: 9 passed, 1 failed, 0 errors
attempt 2: 10 passed, 0 failed, 0 errors
session 1: generate   312 tokens   4.2 s
session 2: repair     363 tokens   4.9 s
session 3: report     716 tokens   8.1 s

The candidate was accepted on the second attempt. The first attempt failed one evaluation:

show_file(run_dir("fibonacci") / "evaluations-1.txt", -6)
# regen/runs/2026-11-28-fibonacci-qwen-qwen3-coder-30b-seed1/evaluations-1.txt
tests/test_regen_eval_fibonacci.py:45: Failed
=========================== short test summary info ============================
FAILED tests/test_regen_eval_fibonacci.py::test_a_bool_index_raises_type_error
1 failed, 9 passed in <time>
babregen: failing evaluations
FAILED tests/test_regen_eval_fibonacci.py::test_a_bool_index_raises_type_error
    tests/test_regen_eval_fibonacci.py:45: Failed: DID NOT RAISE TypeError

It is the bool evaluation. The model wrote if not isinstance(n, int), exactly the mistake that intent item FIB-3 describes, although the item was in the bundle. The driver handed the failure back, and the repair added the missing condition:

first = (run_dir("fibonacci") / "fibonacci-1.py").read_text().splitlines()
second = (run_dir("fibonacci") / "fibonacci-2.py").read_text().splitlines()
diff = difflib.unified_diff(first, second, "fibonacci-1.py", "fibonacci-2.py", n=1, lineterm="")
print("\n".join(diff))
--- fibonacci-1.py
+++ fibonacci-2.py
@@ -26,3 +26,6 @@
     """
-    if not isinstance(n, int):
+    # BUNDLE-CONFLICT: The bundle requires that bool values raise TypeError,
+    # but the current implementation only checks for isinstance(n, int).
+    # This is a stricter check that matches the bundle's intent.
+    if not isinstance(n, int) or isinstance(n, bool):
         raise TypeError("Index must be an int")

The run of primes went the same way: the same evaluation failed on the first attempt, and the second attempt was accepted. Its unit tests end in an error, as for the sieve above, because the model wrote no helper _is_prime.

run = run_record("primes")
print("accepted =", str(run["accepted"]).lower())
for a in run["attempt"]:
    print(f"attempt {a['n']}: {a['evaluations_passed']} passed, {a['evaluations_failed']} failed")
final = run["final"]
print(f"unit tests: {final['unit_tests_passed']} passed, {final['unit_tests_errors']} errors")
print(f"dependents: {final['dependents_passed']} passed, {final['dependents_failed']} failed")
accepted = true
attempt 1: 9 passed, 1 failed
attempt 2: 10 passed, 0 failed
unit tests: 0 passed, 1 errors
dependents: 2 passed, 0 failed

Two observations follow from these two runs, and no more than that: they are one run for each unit with one model and one seed.

First, writing the requirement down was not enough. The intent item was in the bundle, and the model missed it twice. What made the difference was the evaluation behind the item. In Section 10 the same evaluation was the only one that killed mutant M004.

Second, after its work the model is asked for a gap report: a list of the places where the bundle was ambiguous, silent or contradictory. This is the report for fibonacci, shortened to its first items:

show_file(run_dir("fibonacci") / "report.md", 1, 16)
# regen/runs/2026-11-28-fibonacci-qwen-qwen3-coder-30b-seed1/report.md
1. **Bundle Section: Purpose**
   - Problem: The purpose statement says "Pace: fast" but doesn't specify what makes it fast or how performance should be measured.
   - Module Choice: The module implements an iterative solution which is fast and avoids recursion limits, aligning with the "fast" pace requirement.

2. **Bundle Section: Architecture**
   - Problem: The architecture specification says "open choice: the algorithm (iteration or fast doubling; trial division or a sieve)" but doesn't specify which one to choose.
   - Module Choice: The module chooses an iterative approach for simplicity and clarity, which is fast enough for the purpose.

3. **Bundle Section: Intent - FIB-3**
   - Problem: The intent states that a float with an integral value such as `3.0` should raise TypeError, but this is not explicitly stated in the docstring or examples.
   - Module Choice: The module strictly checks for isinstance(n, int) and also explicitly excludes bool values to match the intent.

4. **Bundle Section: Public contract**
   - Problem: The docstring in the public contract says "Args: n: Index of the number, an ``int`` that is not negative" but doesn't explicitly mention that bools should raise TypeError.
   - Module Choice: The module adds an explicit check for isinstance(n, bool) to comply with the intent from FIB-3.

The report has ten items, and most of them restate the bundle. Items 3, 4 and 6 name FIB-3, the intent item where the first attempt went wrong. Item 4 is the useful one: the docstring of the public contract does not say in its Args section that a bool is refused. A gap report is raw material that a person has to read, and where it points at a real ambiguity, the fix belongs in the record, not in the code.

The runs were made in mathregen/ of a clean clone of babregen-examples. The commit in [base] of each run.toml is a commit of that repository, so everyone who clones it can judge an archived candidate again. We do so in a fresh clone, with the accepted module of the run of fibonacci.

Example 15 (An archived candidate is judged again)  

clone = Clone()
run = run_record("fibonacci")
name = run_dir("fibonacci").name
module = f"regen/runs/{name}/fibonacci-{run['final']['attempt']}.py"
clone.babregen("score", "fibonacci", module, "--base", run["base"]["commit"][:12], "--out", "../again", tail=1)
again = tomllib.loads((clone.root.parent / "again" / "run.toml").read_text())
print("accepted =", str(again["accepted"]).lower())
print("same module:", again["final"]["sha256"] == run["final"]["sha256"])
print("same bundle:", again["inputs"]["bundle_sha256"] == run["inputs"]["bundle_sha256"])
$ babregen score fibonacci regen/runs/2026-11-28-fibonacci-qwen-qwen3-coder-30b-seed1/fibonacci-2.py --base e1a764a186e2 --out ../again
... (42 lines before)
run directory: <tmp>/again
[exit 0]
accepted = true
same module: True
same bundle: True

The accepted candidates were not put into src/. The protocol says so in clause (4): an accepted candidate is a result to review, not a merge.

babregen check reads the archive too. Each run records the SHA-256 of the bundle it was given and of the module it replaced. When a record or the module changes later, the check reports that the newest run judged something else (PROV08, PROV09), so an old verdict is never taken for a current one. One changed word in the reason of an intent item is enough:

clone.edit("regen/units/fibonacci.toml", "hides a mistake", "conceals a mistake")
clone.babregen("check")
$ babregen check
regen/runs/2026-11-28-fibonacci-qwen-qwen3-coder-30b-seed1/run.toml:46: warning PROV08 mathregen.fibonacci: the newest archived run (started 2026-11-28T18:32:09Z) judged a different bundle: its verdict is evidence of that day only
regen check: 2 units, 0 errors, 1 warnings
[exit 0]

The sandbox of this page holds no archive, which is why its checks never showed this warning.

12 Compaction and the guard

Knowledge goes stale. A consumer stops using a unit, an allowed import is never used, a decision is cited by nothing. The check reports such things as warnings of the family COMPACT, and babregen compact lists only them.

Example 16 (Two stale entries) We allow fibonacci an import that it does not use, and we rewrite the README so that it no longer mentions the primes.

sb.edit("regen/architecture.toml", "fibonacci = []", 'fibonacci = ["primes"]')
readme = sb.read("README.md")
sb.write("README.md", readme.replace("nth_prime", "p").replace("mathregen.primes", "the second module"))
sb.babregen("compact")
$ babregen compact
regen/architecture.toml:37: warning COMPACT02 allowed edge fibonacci -> primes is unused
regen/units/primes.toml:66: warning COMPACT07 consumer README.md no longer references the unit
regen compact: 2 candidates
[exit 0]

Warnings do not fail the check. --strict makes them fail it:

sb.babregen("check", "--strict", tail=1)
$ babregen check --strict
... (2 lines before)
regen check: 2 units, 0 errors, 2 warnings
[exit 1]

The last step is to make the check a habit. mathregen runs it in make guard, with --strict, next to the linter. The check is deterministic and takes a fraction of a second, so it belongs before every push. mutate, score and local do not: they run tests or call a model, and they are for the moments when a unit is examined or replaced.

makefile = sb.read("Makefile").splitlines()
first = next(n for n, line in enumerate(makefile, 1) if line.startswith("regen-check:"))
last = next(n for n, line in enumerate(makefile, 1) if line.startswith("guard:"))
sb.show("Makefile", first, first + 1)
sb.show("Makefile", last, last)
# Makefile, lines 17 to 18
regen-check:  ## Check regen/ against the source tree
    $(RUN) babregen check --strict
# Makefile, lines 37 to 37
guard: sync regen-check lint  ## Compliance checks before a push: regen spec and lint

13 A third function

The package will grow. Adding a function repeats the steps of this page in small. We start one, a module for factorials, and stop after the first step to see what the check says.

Example 17 (A new module without a place in the architecture)  

sb.write(
    "src/mathregen/factorial.py",
    '"""Factorials."""\n\n__all__ = ["factorial"]\n\n\n'
    "def factorial(n: int) -> int:\n"
    '    """Return n!, the product of the integers from 1 to n."""\n'
    "    result = 1\n"
    "    for k in range(2, n + 1):\n"
    "        result *= k\n"
    "    return result\n",
)
sb.babregen("check")
$ babregen check
src/mathregen/factorial.py: error COMPILE03 subpackage 'factorial' is not listed in [allowed] of architecture.toml
regen check: 2 units, 1 errors, 0 warnings
[exit 1]

COMPILE03: the module is not part of the architecture. From here the list is:

  1. Add factorial = [] to [allowed] in regen/architecture.toml, and "factorial" to the list of "__init__" if the package re-exports the name (Section 4).
  2. Run babregen new-unit factorial --pace fast (Section 5). A module that other units import would declare slow; the policy of that pace asks for a decision record with every change, and a slow unit may not depend on a fast one.
  3. Write tests/test_regen_eval_factorial.py with the marker regen, and name the file under evaluations of the record (Section 6). The questions are the same as before: what is factorial(0), and what happens for a negative number, a bool, a float?
  4. Record a new choice with babregen new-decision. integers-only already covers the argument type, so a new record is needed only for a new choice (Section 7).
  5. Append the intent items with babregen add-intent, each with its evaluations and decisions.
  6. Run babregen check, babregen deletion-test factorial and babregen mutate factorial, and commit (Section 9, Section 10).

Steps 4 and 5 are commands that write a record. They create a file or append one complete block, never rewrite existing text, check every name before they write, and have --dry-run (Write the records treats them in full). We carry out steps 1 to 5 for one requirement, the value of factorial(0).

Example 18 (A decision record and an intent item, written by commands) Steps 1 to 3 are done: the architecture has its line, the draft exists and names an evaluation file with one test, test_the_empty_product_is_one. The decision comes first, as a dry run.

decision = [
    "new-decision", "empty-product",
    "--title", "factorial(0) is 1",
    "--driver", "A loop that starts at the wrong value returns 0 for every n.",
    "--decision", "factorial(0) == 1, the empty product.",
    "--approved-by", "maintainer", "--date", "2026-11-28",
]
sb.babregen(*decision, "--dry-run")
$ babregen new-decision empty-product --title 'factorial(0) is 1' --driver 'A loop that starts at the wrong value returns 0 for every n.' --decision 'factorial(0) == 1, the empty product.' --approved-by maintainer --date 2026-11-28 --dry-run
title = "factorial(0) is 1"
date = 2026-11-28
status = "active"
driver = "A loop that starts at the wrong value returns 0 for every n."
decision = "factorial(0) == 1, the empty product."
approved_by = "maintainer"
[exit 0]

The text is what we want, so we run the command again without --dry-run. The intent item follows, at first with a typo in the name of the evaluation.

sb.capture(*decision)
intent = [
    "add-intent", "factorial",
    "--scope", "factorial",
    "--invariant", "factorial(0) == 1",
    "--reason", "The empty product is 1, and a loop that starts at 0 returns 0 for every n.",
    "--decision", "empty-product",
]
sb.babregen(*intent, "--evaluation", "test_the_empty_product_is_1")
$ babregen add-intent factorial --scope factorial --invariant 'factorial(0) == 1' --reason 'The empty product is 1, and a loop that starts at 0 returns 0 for every n.' --decision empty-product --evaluation test_the_empty_product_is_1
babregen: evaluation 'test_the_empty_product_is_1' is not defined in the evaluation files of mathregen.factorial; a similar name exists: 'test_the_empty_product_is_one'
[exit 2]
sb.babregen(*intent, "--evaluation", "test_the_empty_product_is_one")
sb.babregen("check")
$ babregen add-intent factorial --scope factorial --invariant 'factorial(0) == 1' --reason 'The empty product is 1, and a loop that starts at 0 returns 0 for every n.' --decision empty-product --evaluation test_the_empty_product_is_one
wrote regen/units/factorial.toml
next: run babregen check
[exit 0]
$ babregen check
regen check: 3 units, 0 errors, 0 warnings
[exit 0]

The wrong name is refused with exit code 2 before anything is written, and the right one appends the item FAC-1. The check passes with three units. The record is not finished: the other questions of step 3 need their evaluations and intent items, and step 6 is still to do.

No existing record changes except the one line in the architecture. That is what the split into one module per function buys.

14 Summary

Table 3: The steps of this tutorial.
step command primitive
state the shape of the package edit regen/architecture.toml compilation, pace
draft a unit record babregen new-unit MODULE --pace P deletion
write evaluations and intent edit tests/test_regen_eval_*.py; babregen add-intent UNIT ... or edit regen/units/*.toml evaluation, intent
declare a consumer babregen add-consumer UNIT REF deletion
record the reasons babregen new-decision ID ... or edit regen/decisions/*.toml provenance
get help in the editor babregen schema KIND, .taplo.toml all
check records against the tree babregen check [--strict] [--format json] all
understand a finding babregen explain ID all
check the preconditions of a deletion babregen deletion-test UNIT deletion
see what an author would receive babregen context UNIT intent, provenance
measure intent coverage and specification size babregen measures pace, intent
test the evaluations babregen mutate UNIT evaluation
judge a candidate babregen score UNIT FILE evaluation, deletion
regenerate with a local model babregen local UNIT ... deletion, provenance
find stale knowledge babregen compact compaction

The three kinds of TOML files and every check ID are on the page Schema and check IDs, every command with an example on the page Commands, and the options of score and local on the page Scoring and regeneration. The commands that write a record have a tutorial of their own, Write the records. To type the commands of this page yourself, take the exercise sheet; to watch them run in a terminal, take the walkthrough.