import subprocess
import sys
import tempfile
from pathlib import Path
from babregen import make_sample_repo
tmp = tempfile.TemporaryDirectory()
root = make_sample_repo(Path(tmp.name) / "demo")
(root / "scripts").mkdir()
(root / "scripts/use_it.py").write_text("from samplepkg.core import calc\n")
candidate = Path(tmp.name) / "candidate.py"
candidate.write_text((root / "src/samplepkg/core/calc.py").read_text())
def git(*args):
subprocess.run(
["git", "-c", "user.name=demo", "-c", "user.email=demo@example.org", *args],
cwd=root,
check=True,
capture_output=True,
)
git("init", "-q")
git("add", ".")
git("commit", "-q", "-m", "demo")
def babregen(*args, keep=None, head=None, rooted=True):
"""Run `babregen` on the sample repository; show the call, the output and the exit code."""
command = [sys.executable, "-m", "babregen", *(["--root", str(root)] if rooted else []), *args]
done = subprocess.run(command, cwd=root, capture_output=True, text=True, check=False)
shown = [a if a != str(candidate) else "candidate.py" for a in args]
print("$ babregen", *shown)
lines = (done.stdout + done.stderr).splitlines()
lines = [x.replace(str(root), "<root>").replace(tmp.name, "<tmp>") for x in lines]
if keep:
lines = [x for x in lines if keep(x)]
if head:
lines = lines[:head] + (["..."] if len(lines) > head else [])
print("\n".join(lines))
print(f"[exit {done.returncode}]")Commands
Every command of babregen, with one example that runs against the sample repository when this page is rendered. --root DIR selects the repository; without it, babregen searches upwards from the current directory for regen/architecture.toml. The exit codes are the same everywhere: 0 for success, 1 when a check finds an error (or a warning with --strict), a deletion test finds a gap, a mutant survives or a candidate is not accepted, and 2 for an error of the input (an unknown unit or name, a record that does not load, an option that is refused).
| command | what it does | needs regen/ |
writes |
|---|---|---|---|
check |
validate regen/ against the source tree |
yes | no |
deletion-test |
blast radius and knowledge gaps of one unit | yes | no |
context |
the regeneration bundle of one unit | yes | with -o |
compact |
compaction candidates | yes | no |
measures |
pace, coverage and specification size | yes | no |
mutate |
mutation score of one unit | yes | with --out |
score |
judge a candidate module by accept/1 |
yes | a run directory |
new-unit |
draft the record of a module | yes | a new record |
schema |
the JSON Schema of a record kind | no | with -o |
explain |
what a check ID means | no | no |
example |
one complete, commented record | no | no |
new-decision |
create a decision record | yes | a new record |
add-intent |
append an intent item to a unit record | yes | the record |
add-consumer |
append a consumer to a unit record | yes | the record |
coding |
code the failures of rejected runs: briefs, a checked proposal, an offline page, the answers | yes | a review directory |
gate |
rate the surviving mutants on three offline pages, with a sealed plant | yes | a review directory |
local |
regenerate a unit with a local model | yes | a run directory |
ui |
the browser interface on this machine | no | regen/ui.toml, and files below the git directory |
check
babregen check [--strict] [--format {text,json}] compares the records with the source tree and prints one line per finding, {path}:{line}: {level} {id} {message}, and a summary. --strict also fails on warnings. --format json prints one document instead (see JSON output). The IDs are explained by explain.
A strict check and an archive of runs in the working tree do not go together. Once a run is archived under regen/runs/, every edit of the module gives PROV09 and every edit of a record gives PROV08, both warnings, so that check --strict exits 1, and nothing acknowledges an old run: the only clean way is a new scored run after each edit. Keep the archives on an archive branch (as babregen keeps those of its studies on archive/v1), and run the strict check, where one is a guard, on a tree that has none.
babregen("check")
babregen("check", "--format", "json", head=9)$ babregen check
regen/units/core.calc.toml:1: error DELETE01 scripts/use_it.py depends on the unit but is not a declared consumer
regen check: 1 units, 1 errors, 0 warnings
[exit 1]
$ babregen check --format json
{
"format": 1,
"summary": {
"units": 1,
"errors": 1,
"warnings": 0
},
"findings": [
{
...
[exit 1]
deletion-test
babregen deletion-test UNIT lists everything that depends on the unit (its blast radius) and everything that a regeneration would need that lives outside the implementation. The exit code is 0 when the unit is regenerable.
babregen("deletion-test", "core.calc")$ babregen deletion-test core.calc
# Deletion test: samplepkg.core.calc
File `src/samplepkg/core/calc.py`, pace fast.
## Blast radius
| consumer | kind | declared | note |
|---|---|---|---|
| `docs/guide.qmd` | doc | yes | teaches add |
| `scripts/use_it.py` | code | NO | |
| `src/samplepkg/app/main.py` | code | yes | sums values with add |
| `tests/test_regen_eval_calc.py` | test | yes | evaluation |
## Knowledge outside the implementation
| intent | evaluations | decisions |
|---|---|---|
| C-1 | 1 | why-add |
## Gaps
- DELETE01: scripts/use_it.py depends on the unit but is not a declared consumer
Verdict: NOT regenerable yet (1 gaps).
[exit 1]
context
babregen context UNIT [-o FILE] prints the bundle that a model would receive to write the unit again: the records and the stubs of its dependencies, never the bodies.
babregen("context", "core.calc", head=14)$ babregen context core.calc
# Regeneration bundle: samplepkg.core.calc
Write `src/samplepkg/core/calc.py` from scratch. You do not get the current implementation. Keep every public name and signature of the contract below, satisfy every intent item, and import nothing outside `depends_on`.
## Purpose
Adds numbers.
Pace: fast (evals).
## Architecture (compilation target)
- `core` may import from: nothing inside the package
- this unit may import: nothing inside the package
...
[exit 0]
compact
babregen compact lists what the records carry that nothing needs any more: unused edges, stale cycles, evaluations that no intent item names, decisions that nothing cites.
babregen("compact")$ babregen compact
regen compact: 0 candidates
[exit 0]
measures
babregen measures shows, for every unit, the pace, the intent coverage and the size of the specification against the code.
babregen("measures")$ babregen measures
| unit | pace | coverage | decisions | consumers | code | record | decision lines | evaluation lines | spec | ratio |
|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| samplepkg.core.calc | fast | 1/1 | 1 | 2 | 10 | 23 | 9 | 9 | 41 | 4.1 |
| total | - | 1/1 | 1 | 2 | 10 | 23 | 9 | 9 | 41 | 4.1 |
[exit 0]
mutate
babregen mutate UNIT [--max N] [--timeout S] [--out FILE] plants mutants in the module and runs the evaluations against each. It needs a git repository with a commit; the project may be a subfolder of the repository. The exit code is 1 when a mutant survives. The progress is on stderr.
babregen("mutate", "core.calc", "--max", "2")$ babregen mutate core.calc --max 2
# Mutation score: samplepkg.core.calc
1 evaluations in tests/test_regen_eval_calc.py, 2 mutants.
Base commit `574fa68cd6097e9139675f83ce78b0a723da662c`, working tree clean; Python 3.14.2, pytest 9.2.0.
Mutation score: 2/2 (100 %).
M001 killed (1 failed)
M002 killed (1 failed)
[exit 0]
score
babregen score UNIT FILE [--base REV] [--timeout S] [--python PATH] [--out DIR] judges a candidate module by the acceptance rule accept/1: the unit’s evaluations, its unit tests and its dependents must pass. It prints the run record and exits 0 when the candidate is accepted. It needs a git repository with a commit; the project may be a subfolder of the repository.
babregen("score", "core.calc", str(candidate), keep=lambda x: x.startswith(("accepted", "rule", "[final]", "dependents", "evaluations")) , head=8)$ babregen score core.calc candidate.py
accepted = true
rule = "accept/1"
[final]
dependents_passed = 1
dependents_failed = 0
evaluations_passed = 1
evaluations_failed = 0
evaluations_errors = 0
[exit 0]
new-unit
babregen new-unit MODULE --pace P [--dry-run] drafts regen/units/<unit>.toml from the tree. See Draft a unit.
babregen("new-unit", "app.main", "--pace", "fast", "--dry-run", keep=lambda x: not x.startswith("# Drafted"), head=12)$ babregen new-unit app.main --pace fast --dry-run
# `babregen check` fails with INTENT01 until the first [[intent]] item is written.
summary = "TODO: what samplepkg.app.main is for."
pace = "fast"
public = ["total"]
depends_on = ["samplepkg.core.calc"]
evaluations = [] # e.g. tests/test_regen_eval_main.py, marked pytest.mark.regen
unit_tests = []
# 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.
...
[exit 0]
schema
babregen schema {architecture,unit,decision} [-o FILE] prints the JSON Schema of a record kind, derived from babregen.spec.FIELDS. It needs no regen/ tree. See Editor support.
babregen("schema", "decision", head=10, rooted=False)$ babregen schema decision
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "regen/decisions/<id>.toml of babregen",
"description": "One decision record, derived from babregen.spec.FIELDS.",
"type": "object",
"properties": {
"title": {
"description": "What was decided, in one line. [prose: line breaks are folded]",
"type": "string",
"minLength": 1
...
[exit 0]
explain
babregen explain ID prints, for a check ID, its level and condition, a wrong and a corrected fragment of a record and the usual fix. The ID may be in lower case; an unknown ID exits 2 with a suggestion. It needs no regen/ tree.
babregen("explain", "eval03", rooted=False)
babregen("explain", "eval3", rooted=False)$ babregen explain eval03
EVAL03 (error): an evaluation named by an intent item is not defined in the unit's evaluation files
Wrong, in regen/units/core.calc.toml:
evaluations = ["test_ad"]
Right:
evaluations = ["test_add"]
Fix: Correct the name: the finding names a similar one when it exists. When no test has that name, the evaluation is missing: write the test, then name it.
[exit 0]
$ babregen explain eval3
babregen: unknown check ID 'eval3' (the IDs are INTENT, COMPILE, EVAL, PROV, PACE, DELETE and COMPACT, each followed by two digits); a similar name exists: 'EVAL03'
[exit 2]
example
babregen example {agents,architecture,decision,unit} prints one complete, valid, commented record that uses the names of the sample repository, with folded prose; agents prints the template of regen/agents.toml, which is no record. It needs no regen/ tree.
babregen("example", "decision", head=14, rooted=False)$ babregen example decision
# regen/decisions/why-add.toml: a decision record. The file name is the id that intent
# items cite (decisions = ["why-add"]). The names are those of the sample repository.
title = "Addition is provided by the package" # what was decided, in one line
date = 2026-01-01
status = "active" # active (the default), superseded or expired
# What forced the decision: an incident, a requirement, a measurement. Prose is folded:
# wrap it, write no backslash.
driver = """
A user asked for a function that sums two integers, and three scripts had their own
copy of it."""
decision = """
The package provides add(a, b) in samplepkg.core.calc and promises plain arithmetic.
...
[exit 0]
new-decision
babregen new-decision ID --title T --driver T --decision T --approved-by NAME [options] creates regen/decisions/ID.toml and never overwrites a file. The id is the file name without .toml: lower-case letters and digits with ., - or _ between them, at most 100 characters. --status (active, superseded or expired), --review-after and --assumes (repeatable) fill the optional keys. --evidence file:PATH must name an existing file; --alternative and --rejected-because are given in pairs. --date defaults to today (UTC). The command checks everything before it writes, and --dry-run prints the text that would be created.
babregen(
"new-decision", "why-sub",
"--title", "Subtraction is provided",
"--driver", "A user asked for it.",
"--decision", "Provide sub next to add.",
"--approved-by", "maintainer",
"--evidence", "file:src/samplepkg/core/calc.py",
"--date", "2026-11-28",
"--dry-run",
)
babregen(
"new-decision", "why-sub",
"--title", "Subtraction is provided",
"--driver", "A user asked for it.",
"--decision", "Provide sub next to add.",
"--approved-by", "maintainer",
"--evidence", "file:src/samplepkg/core/calc.py",
)$ babregen new-decision why-sub --title Subtraction is provided --driver A user asked for it. --decision Provide sub next to add. --approved-by maintainer --evidence file:src/samplepkg/core/calc.py --date 2026-11-28 --dry-run
title = "Subtraction is provided"
date = 2026-11-28
status = "active"
driver = "A user asked for it."
decision = "Provide sub next to add."
approved_by = "maintainer"
evidence = ["file:src/samplepkg/core/calc.py"]
[exit 0]
$ babregen new-decision why-sub --title Subtraction is provided --driver A user asked for it. --decision Provide sub next to add. --approved-by maintainer --evidence file:src/samplepkg/core/calc.py
wrote regen/decisions/why-sub.toml
next: cite it from an intent item (babregen add-intent UNIT --decision why-sub) or from `decisions` of architecture.toml, then run babregen check
still open (babregen check will report):
regen/decisions/why-sub.toml:1: warning COMPACT06 no intent item references this decision
[exit 0]
add-intent
babregen add-intent UNIT --scope T --invariant T --reason T [--id ID] [--evaluation NAME]... [--decision ID]... appends one [[intent]] block to the record of the unit. The prose is given, never drafted. Every evaluation must be defined in an evaluation file of the unit and every decision must exist; all wrong names are reported at once, each with a similar name. The default id is the dominant PREFIX- of the unit with the next number.
babregen(
"add-intent", "core.calc",
"--scope", "add", "--invariant", "add(0, x) == x", "--reason", "zero is the identity",
"--evaluation", "test_ad", "--decision", "why-sub",
)
babregen(
"add-intent", "core.calc",
"--scope", "add", "--invariant", "add(0, x) == x", "--reason", "zero is the identity",
"--evaluation", "test_add", "--decision", "why-sub",
)$ babregen add-intent core.calc --scope add --invariant add(0, x) == x --reason zero is the identity --evaluation test_ad --decision why-sub
babregen: evaluation 'test_ad' is not defined in the evaluation files of samplepkg.core.calc; a similar name exists: 'test_add'
[exit 2]
$ babregen add-intent core.calc --scope add --invariant add(0, x) == x --reason zero is the identity --evaluation test_add --decision why-sub
wrote regen/units/core.calc.toml
next: run babregen check
still open (babregen check will report):
regen/units/core.calc.toml:1: error DELETE01 scripts/use_it.py depends on the unit but is not a declared consumer
[exit 0]
add-consumer
babregen add-consumer UNIT REF [--kind {code,test,doc,external}] [--note T] appends one [[consumers]] block. Without --kind the kind is inferred as new-unit does: a file that is not Python is a doc, Python below the source directory is code, below tests a test, any other code. REF must be a plain repository path that exists, unless the kind is external; one that is already declared is refused.
babregen("add-consumer", "core.calc", "scripts/use_it.py", "--note", "runs add on its argument")
babregen("check", "--strict")$ babregen add-consumer core.calc scripts/use_it.py --note runs add on its argument
wrote regen/units/core.calc.toml
next: run babregen check
[exit 0]
$ babregen check --strict
regen check: 1 units, 0 errors, 0 warnings
[exit 0]
coding
babregen coding start DIR RUN..., babregen coding check DIR [RUN], babregen coding page DIR and babregen coding intake DIR FILE are the first of the two human steps: a person codes why rejected runs were rejected. DIR is a new directory below regen/runs/ that holds no run.toml, and each RUN is the directory of a rejected run (babregen score --out). start writes coding.toml, two briefs for agents and an empty proposals/. check verifies what exists: the proposals (every quote against the file it names), both pages and both answers files against a rebuild, the chain and the order of the commits; check DIR RUN checks the proposal of one run, which is what the agent that writes it runs. There are two stages, with one offline page each, as for the gate. page writes coding-own.html, built from the run directories only, which holds no proposal and reads nothing below proposals/; intake takes the downloaded answers in as answers-own.toml. After that file is committed, page writes coding-final.html for the runs that have a proposal, and intake takes the final answers in as answers-final.toml. If no run has a proposal there is no second stage, and page says so. Exit 0 is success; exit 1 means that content which was checked fails (a quote, a number, a hash, a file that breaks its format); exit 2 means a wrong argument, a missing file, a step taken out of order or a target that exists. A page is built, taken in and verified by the babregen that started the session: with another version check compares no page hash and prints a note that names the version, and page and intake refuse. The two human steps explains the steps and their files.
babregen("coding", "start", "regen/runs/study/coding", "regen/runs/study/run-1")
babregen("coding", "check", "regen/runs/study/coding")
babregen("coding", "page", "regen/runs/study/coding")$ babregen coding start regen/runs/study/coding regen/runs/study/run-1
wrote regen/runs/study/coding/coding.toml
wrote regen/runs/study/coding/BRIEF.md
wrote regen/runs/study/coding/BRIEF-CHECK.md
[exit 0]
$ babregen coding check regen/runs/study/coding
ok
[exit 0]
$ babregen coding page regen/runs/study/coding
wrote regen/runs/study/coding/coding-own.html (stage own, 22172 bytes)
[exit 0]
gate
babregen gate start DIR REPORT..., babregen gate assign DIR, babregen gate seal DIR, babregen gate page DIR, babregen gate intake DIR FILE and babregen gate check DIR are the second human step: a person rates every surviving mutant (gap, output or equivalent) on up to three pages, and a random plant checks whether a proposal sways the rating. REPORT is a file of babregen mutate --out. The steps and the exit codes are those of coding. check can run at any stage and says how far the session has come. The three stages and what check proves are in The two human steps.
babregen("mutate", "core.calc", "--max", "3", "--out", "regen/runs/study/mutants.toml",
keep=lambda x: x.startswith(("Mutation score", "wrote")))
babregen("gate", "start", "regen/runs/study/gate", "regen/runs/study/mutants.toml")
babregen("gate", "check", "regen/runs/study/gate")$ babregen mutate core.calc --max 3 --out regen/runs/study/mutants.toml
Mutation score: 2/3 (67 %).
wrote regen/runs/study/mutants.toml
[exit 1]
$ babregen gate start regen/runs/study/gate regen/runs/study/mutants.toml
started: 1 survivors from 1 mutation files
next: the first agent reads BRIEF-first.md and writes regen/runs/study/gate/sealed/first.toml
[exit 0]
$ babregen gate check regen/runs/study/gate
ok (stage reached: started)
[exit 0]
local
babregen local UNIT --model M --model-sha256 HEX --context-length N --protocol ID regenerates a unit with a model that LM Studio serves on this machine, from a clean working tree, and archives the run under regen/runs/. It is not deterministic and needs a model server, so this page shows only its options; see Scoring and regeneration.
babregen("local", "--help", head=8)$ babregen local --help usage: babregen local [-h] --model MODEL --model-sha256 HEX --context-length N --protocol ID [--endpoint ENDPOINT] [--allow FILE] [--host LABEL] [--attempts ATTEMPTS] [--out OUT] [--reasoning {off,on,none}] [--template {chatml,mistral}] [--max-tokens MAX_TOKENS] [--report-tokens REPORT_TOKENS] [--session-timeout SESSION_TIMEOUT] [--score-timeout SCORE_TIMEOUT] ... [exit 0]
ui
babregen ui [--port N] [--no-browser] [--approve] [--check] starts a small server on this machine and opens a start page in the browser. The browser interface is the guide, with pictures and a walk through one unit; this section is the reference. In the interface, a pilot is a package directory whose modules become units: the start page lists the package of regen/architecture.toml and its subpackages as check boxes, nothing ticked in advance, and posting the choice writes regen/ui.toml.
The overview shows, for every module of the pilots, the state of the record, the check, the deletion test, the mutation report, the gate, the run and the coding. The first step that is not done decides the line of the unit and says what comes next; the steps after it show “waits”. The overview proposes mutation and gate before the regeneration and blocks a step only on a real precondition: then it shows the reason, with an editor link to the file and line, instead of a link. The gate and coding directories below regen/runs/ are listed with their stage, next step and reason, which come from the status functions of the review engine and from nothing below sealed/ or proposals/.
Each cell opens its step in a new tab, at /step/<name>: check, deletion-test, context, compact, measures, schema, explain and example show their result as tables or text; new-unit, add-intent, add-consumer and new-decision show a preview of the text first and write only on a second request with the same fields. Every value of a form is chosen from a list that the server made or checked against a limit.
mutate, score and local are long steps. The first request shows the exact command line, which the server builds from listed values and bounded numbers; the second starts it as a subprocess with an argument list (never a shell), no standard input and its own process group, its output in log files of the job directory. One long job runs per project. A second one is refused with a link to the running job, and a step that writes a file waits until it ends; a step that only reads goes on. The page of a running job refreshes itself and shows the elapsed time, the end of the log and a cancel button, which terminates the process group and kills it after a short grace. Stopping the server stops the job the same way, and a server that starts and finds a job recorded as running stops its group only if the pid still runs that command. Exit code 1 of a command is a result, 2 a failure, and a signal an interruption. The commands write where they always write, below regen/runs/, and a repeated run gets the suffix -r2, -r3 and never overwrites. local takes the model, its hash, the context length and the endpoint from the settings of this machine and says what is missing instead of offering the button. The result page reads its tables from the files the command wrote, so the overview finds the results again after a restart. A report or run is marked stale, with the reason, when the module or the evaluations it was made from changed, and the overview then proposes the rerun.
The two human steps are in the interface too. The overview links the page of every gate and coding directory. That page says who acts next (a person in the browser, an operator in a terminal, an agent, or git by a button), in plain words and with the command an operator runs, and offers only the buttons of the stage; its state comes from gate status and coding status and shows nothing below sealed/ or proposals/. A gate has no button for its two agents, for assign or for seal: whoever drew and sealed the proposals does not rate, so an operator, another person or an agent session, runs them in a terminal and the page waits. gate start and coding start are steps with forms made of lists; gate check and coding check show their problems as tables. A review page is built by a button and opens in its own tab. It is served only if its bytes equal what the engine rebuilds, byte for byte and with a policy of its own that allows exactly its own inline style and script by their hashes. The answers you give are kept by the browser for the address of the server, which includes the port, so the port of a project is fixed and nothing is sent while you answer. When you are done you press the download button of the page and give the downloaded file, unchanged, to the page of the directory: a file chooser, and the interface passes exactly those bytes to intake, which decides. The commits of the evidence chain are buttons with a fixed list of files and a fixed message; after the seal comes the push, because the blind page records whether the seal is on the upstream. A directory that was started with another version offers check only.
The button for a coding agent runs a command from regen/agents.toml, which only a person writes (babregen example agents prints a template). The command is an argument list in which only {brief} and {target} are replaced, and it runs only after you approved it once in a terminal with babregen ui --approve, which shows every argument, the working directory, the resolved program and the time limit. The approval is kept in a file of your user outside every repository and is bound to the project, the role and the whole text of the command; the browser cannot give one. The button appears only after answers-own.toml is committed and until the final page exists. The page shows the state and the exit of the agent and never its output, which can hold the proposal; the log is shown when the coding is complete.
Every action is a job with an address, /jobs/<id>, kept below the git directory (<git-dir>/babregen-ui/<project>/jobs/), so that it is never tracked and never makes the tree dirty; one changing action runs at a time. A job page lists the files that the job wrote with their git state. A button commits exactly those files with the message that the page shows, under your git identity; other staged changes stay staged, the commit is verified afterwards, and a push is a second button that lists every commit the upstream lacks and never forces. The settings page writes machine.toml in the same place: the port (default 8765) and the options of local for this machine.
One server runs per project: it holds a lock on server.lock in the same directory for its life, and a second babregen ui for the project ends with exit code 2 and names the first (its address, never the token) instead of stopping the job that the first runs.
The command needs a git repository and ends with exit code 2 otherwise. The server listens on 127.0.0.1 only and answers a request only with the exact host 127.0.0.1:<port>, a session cookie, and for a change the own origin and a token of the form. The browser is started with the path of a file that only you can read and that holds the launch token, which is valid once; with --no-browser the address with the token is printed instead. A port that is taken is an error: no other port is chosen. --check loads regen/ui.toml and machine.toml, prints the address and serves nothing.
babregen("ui", "--check")
babregen("ui", "--check", "--port", "9000")$ babregen ui --check
http://127.0.0.1:8765/
[exit 0]
$ babregen ui --check --port 9000
http://127.0.0.1:9000/
[exit 0]