From an empty directory to a regenerated module, with the package mathregen
Author
Thomas Bartz-Beielstein
Published
November 27, 2026
This tutorial introduces spotregen 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 spotregen command and show what it prints.
The reader is expected to know Python packaging and pytest. Nothing about spotregen or about regenerative software is assumed.
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 spotregen 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 commands are plain bash blocks that no kernel runs.
purpose
how
build the page
make doc at the root of the spotregen 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 spotregen repository
debug one cell
run all cells above it first, with the kernel of .venv; restart the kernel before a second pass
try spotregen yourself
the exercise sheet: the same commands in a terminal, on a copy of examples/mathregen/ with a git repository of its own
watch this page in a terminal
examples/walkthrough.sh in the spotregen repository: every step of this page as shell commands, in a temporary git repository, with a pause after each section (--no-pause runs through and exits with 1 if an exit code differs from this page)
An interactive run needs docs/tutorials/ as its working directory, because the cells import _mathregen_demo.py, and the kernel of the environment of spotregen (.venv at the root of the repository), because the cells call spotregen and pytest with the interpreter of the kernel.
NoteHow the output on this page is made
Every output block is captured from a real run when the page is rendered. The cells copy the tracked files of examples/mathregen/ (a directory at the root of the spotregen repository) into a throw-away git repository, one stage at a time, and call spotregen, pytest and git there. <repo> in the output is the root of that repository and <tmp> its parent directory. The helper is docs/tutorials/_mathregen_demo.py; uv run quarto render docs/tutorials/step-by-step.qmd runs every cell again.
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 examples/mathregen/regen/runs/.
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. spotregen keeps this knowledge in a tracked directory regen/ and checks it against the source tree.
Fowler names seven primitives. spotregen 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 spotregen.
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 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. spotregen is one development dependency. It needs Python 3.13 or later and has no dependencies of its own.
# pyproject.toml
[project]
name = "mathregen"
version = "0.1.0"
description = "Math functions kept regenerable with spotregen: 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",
"spotregen>=0.15.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.spotregen("--version")
$ spotregen --version
spotregen 0.15.0
[exit 0]
3 Two functions and their unit tests
Nothing in this step is special to spotregen. We write the code and its tests first.
Each function gets a module of its own. spotregen works on modules: a regenerable unit is one module, so two modules can be deleted and rebuilt independently of each other.
# 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.
# 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:
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.
# regen/architecture.toml
# Compilation target of mathregen: the shape every regenerated module must fit into.
# `spotregen 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 spotregen check"
slow = "the durable evaluations, a clean spotregen 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. spotregen 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.
spotregen 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 recordregen/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.
spotregen new-unit drafts a record from what the tree can tell.
$ spotregen new-unit fibonacci --pace fast
wrote regen/units/fibonacci.toml
regen/units/fibonacci.toml:5: error INTENT01 declares no intent item (a unit without intent cannot be regenerated)
next: write the intent items and evaluations, then run spotregen check
[exit 0]
# regen/units/fibonacci.toml
# Drafted by `spotregen new-unit` on 2026-11-27. Review every field;
# `spotregen 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.
#
# [[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).
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:
sb.spotregen("check")
$ spotregen check
regen/units/fibonacci.toml:5: 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.
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.
# 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.
# 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.
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 recordregen/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.
# 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.commit("mathregen 0.1.0 with its regen records")
$ git add -A && git commit -m 'mathregen 0.1.0 with its regen records'
e292319 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 3 (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.spotregen("check")
$ spotregen 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.
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",)sb.append("regen/units/primes.toml",'\n[[consumers]]\nref = "scripts/first_primes.py"\nkind = "code"\n''note = "prints the first twenty primes"\n',)sb.spotregen("check")
(The script was only an illustration. The sandbox returns to the commit of Section 7.)
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.
Blast radius. Who would notice that the unit is gone? Its consumers are declared.
Knowledge outside the implementation. Every intent item names evaluations, and the decisions behind it are on record.
Rebuild. The module is deleted and written again from that knowledge alone.
Judgement. The new module is judged without the old code as the oracle.
spotregen deletion-test checks components 1 and 2 and deletes nothing.
Example 4 (The deletion test of fibonacci)
sb.spotregen("deletion-test", "fibonacci")
$ spotregen 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: spotregen score judges a given candidate, and spotregen 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. spotregen 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 5 (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:
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, spotregen plants faults.
Definition 9 (Mutation analysis and mutation score)spotregen 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).
$ spotregen 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 `e292319d1ff0490a92caef4d1c43430fdb7b5527`, working tree dirty (the mutants were made from it); Python 3.14.2, pytest 9.1.1.
## 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:
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)spotregen 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 regen/ must be at the top of a git repository.
11.1 A candidate written by hand
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.
"""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 9 (A different algorithm is accepted)
record = sb.score("fibonacci", "fibonacci_doubling")
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.
"""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)
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 11 (Accepted although the unit tests fail)
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
spotregen 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. 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.
# regen/decisions/regen-protocol.toml, lines 1 to 22
title = "A unit of mathregen is regenerated with one local model under fixed options"
date = 2026-11-27
status = "active"
driver = """
`spotregen 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. The tutorial runs it once for each unit."""
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 spotregen, and nothing else. An accepted candidate \
is archived and reported; it does not replace the module in src/ without a review."""
approved_by = "bartzbeielstein"
evidence = ["url:https://advm1.gm.fh-koeln.de/~bartz/spotregen/docs/drivers.html"]
These are the commands that were run, once, on 2026-11-27. 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.
# regen/runs/2026-11-27-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>
spotregen: 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:
--- fibonacci-1.py
+++ fibonacci-2.py
@@ -26,3 +26,7 @@
"""
- 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 strict interpretation of the intent: bool is a subclass of int,
+ # but the bundle explicitly says "or is a bool" should raise TypeError.
+ 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")
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:
# regen/runs/2026-11-27-fibonacci-qwen-qwen3-coder-30b-seed1/report.md
1. **Bundle Section: Purpose**
- **Problem**: The bundle states "Pace: fast" but doesn't specify what makes it fast or how performance should be measured.
- **Module Choice**: The module implements an iterative approach for efficiency, which aligns with the "fast" pace by avoiding recursion limits and ensuring linear time complexity.
2. **Bundle Section: Architecture**
- **Problem**: The bundle says "open choice: the algorithm (iteration or fast doubling; trial division or a sieve)" but doesn't clarify which algorithm to choose for the Fibonacci function.
- **Module Choice**: The module chooses iteration over fast doubling, likely due to simplicity and sufficient performance for typical use cases.
3. **Bundle Section: Intent FIB-3**
- **Problem**: The intent says "An index that is not an `int` raises `TypeError`; this includes `bool`, and a `float` with an integral value such as `3.0`" but does not explicitly clarify whether `float` values with integral values should be rejected.
- **Module Choice**: The module strictly checks for `isinstance(n, int)` and explicitly excludes `bool` values by checking `isinstance(n, bool)`, thus rejecting both `bool` and `float` values.
The report has twenty items, and most of them restate the bundle. Item 3 is the useful one: it points at the sentence about bool and float in FIB-3, the place where the first attempt went wrong. 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.
WarningWhat the archive of this tutorial can and cannot do
score and local need regen/ at the top of a git repository. mathregen/ is not the top of one: it lies in examples/ of the spotregen repository. Both runs were therefore made in a copy of its tracked files with a git repository of its own, and the run directories were copied into the archive. The commit in [base] of each run.toml names a commit of that copy. The archive documents the runs, but the candidates cannot be scored again in place. In a package that is the top of its own repository this restriction does not exist.
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.
spotregen 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.
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 spotregen compact lists only them.
Example 13 (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.spotregen("compact")
$ spotregen 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:
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.
sb.show("Makefile", 13, 23)
# Makefile, lines 13 to 23
regen-check: ## Check regen/ against the source tree
uv run spotregen check --strict
regen-eval: sync ## Run the durable evaluations only (pytest -m regen)
uv run pytest tests/ -m regen -p no:cacheprovider
lint: ## ruff check and format check
uv run ruff check .
uv run ruff format --check .
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 14 (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.spotregen("check")
$ spotregen 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:
Add factorial = [] to [allowed] in regen/architecture.toml, and "factorial" to the list of "__init__" if the package re-exports the name (Section 4).
Run spotregen 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.
Write tests/test_regen_eval_factorial.py with the marker regen, and the intent items that name its tests (Section 6). The questions are the same as before: what is factorial(0), and what happens for a negative number, a bool, a float?
Cite a decision. integers-only already covers the argument type, so no new record is needed unless a new choice is made (Section 7).
Run spotregen check, spotregen deletion-test factorial and spotregen mutate factorial, and commit (Section 9, Section 10).
No existing record changes except the one line in the architecture. That is what the split into one module per function buys.