Scoring and regeneration
babregen score judges a candidate module for one unit and calls no model. babregen local regenerates one unit with a local model and judges the result the same way. The cells on this page are not executed: local needs a model server, it is not deterministic and both commands write to your repository’s git metadata.
make guard
An LLM call is not deterministic, and judging a candidate runs the unit’s evaluations. Both are for experiments and for measuring how good a specification is. The static check is babregen check.
The judge
Both commands judge a candidate by the same procedure, implemented once in babregen.judge. run.toml names it in the field protocol (see run records).
Definition 1 (Judging a candidate) score and local need a git repository with at least one commit. The project (the folder with regen/) may be the top of the repository or a subfolder of it: the judge then works in the same subfolder of the worktree, and only the project’s own folder counts for “the working tree is dirty”. Without a repository or without a commit the command stops with exit code 2 and says so.
Only local refuses a dirty working tree. score makes no such check: it judges the base commit in a scratch worktree and reads the candidate from the file you name, which is normally an untracked file of the project. What it judges is the commit and that file, not your uncommitted edits to the records or to other modules; commit them first if the verdict is to count them.
The candidate is copied into a scratch git worktree of a base commit in which the original was deleted. The worktree lies outside the repository, so the working tree is never written, and it is removed afterwards, also after an error. The unit’s evaluations judge the candidate and, once, its unit tests and its dependents inside the repository, each phase (and each attempt of local) in a fresh worktree, so that nothing a candidate writes while it runs reaches a later phase: every declared consumer of kind code below the source directory is imported, and every live docstring example of the unit’s public names, taken from the original at the base commit, is run against the new module. Every pytest run and every dependent has a time limit; a run that exceeds it is killed together with the processes it started and counts as one evaluation error.
Definition 2 (The acceptance rule accept/1) A candidate is accepted if and only if its evaluations have no failure, no error and at least one pass, and no dependent fails. Unit tests are recorded as a second opinion and never affect acceptance. The rule is implemented once, as babregen.judge.accept, and run.toml records the verdict as accepted and the rule as rule.
The scoring environment holds only PYTHONPATH=<source_dir> from the architecture, PATH=/usr/bin:/bin, PYTHONDONTWRITEBYTECODE=1, PYTHONHASHSEED=0 and PYTEST_DISABLE_PLUGIN_AUTOLOAD=1: no pytest plugin of the environment is loaded, so a plugin such as pytest-randomly cannot change the counts or the order, and an evaluation must not need one.
babregen score
babregen score core.calc candidate.py
babregen score core.calc candidate.py --base 1a2b3c4 --timeout 300 --out /tmp/score-calcThe unit as recorded at --base (default HEAD) is judged: its evaluations, unit tests and consumers come from that commit, not from the working tree. --timeout S (default 120) limits every pytest run and every dependent and must be positive and finite; --python PATH selects the interpreter that scores candidates (default: <root>/.venv/bin/python if present, otherwise the interpreter running babregen); --out DIR is the run directory (default: a temporary one). The exit code is 0 if the candidate is accepted, 1 if not, 2 for a spec, unit, option or missing-tool error.
babregen local: short sessions against a local server
A deterministic driver sends fresh, short sessions (generate, repair, gap report) to the OpenAI-compatible /v1/completions endpoint of a local server such as LM Studio, with standard-library HTTP. The model is offered no tools; it sees only what the driver puts into the prompt, never the module it must write. The module of the first attempt whose evaluations pass is the final module; if none passes, it is the module of the last attempt that wrote one. The final module is judged once more by its unit tests and its dependents, and accept decides. Failing evaluations are handed back for up to --attempts tries.
babregen local core.calc --model my-model --model-sha256 <64 hex digits> \
--context-length 32768 --protocol my-protocol --template chatml --reasoning off
babregen local core.calc --model devstral --model-sha256 <64 hex digits> \
--context-length 65536 --protocol my-protocol --template mistral --reasoning none
babregen local core.calc --model my-model --model-sha256 <64 hex digits> \
--context-length 32768 --protocol my-protocol --canary # the confinement prompt onlyFour options are required, because the archive has to say what produced a run:
local.
| option | meaning |
|---|---|
--model ID |
the model identifier that the server lists; the endpoint must list it |
--model-sha256 HEX |
the SHA-256 of the model, 64 hexadecimal digits: of the file for a model in one file, for a model in a folder (MLX) of the manifest described below. It is recorded and not verified: the server does not show the files to the driver |
--context-length N |
the context length that the server loaded the model with; recorded, not verified |
--protocol ID |
the id of an active decision record in regen/decisions/ that fixes the protocol of the run (models, seeds, options, what counts as accepted). An unknown or superseded record is refused before the first session. It is recorded as protocol_record |
The manifest of a model folder has one line <sha256 of the file> <file name> per file, sorted by file name, and the option takes the SHA-256 of the manifest. Hidden files and README.md are left out: a download may or may not keep them, and they are no part of the model. The command reads the regular files of the folder itself; a model with files in subfolders or behind symbolic links needs its own rule, stated with the hash.
(cd MODEL_DIR && find . -maxdepth 1 -type f ! -name '.*' ! -name README.md \
| sed 's|^\./||' | LC_ALL=C sort | tr '\n' '\0' | xargs -0 shasum -a 256) > manifest.txt
shasum -a 256 manifest.txtlocal.
| option | meaning |
|---|---|
--allow FILE |
a repository file the generator may see, repeatable. It is read from the base commit, not from the working tree, and its SHA-256 is recorded; a path outside the repository, or a file that is not in the base commit, is refused |
--out DIR |
the run directory; it must not exist or be empty (default regen/runs/<YYYY-MM-DD>-<unit>-<model>-seed<seed>[-<host>][-r<k>]/, with --canary regen/runs/<YYYY-MM-DD>-canary-<model>[-<host>][-r<k>]/; every character of the model and host name outside [A-Za-z0-9._-] becomes -, and -r<k>, k from 2, is the first repeat that is free) |
--host LABEL |
a free label of the machine, for example bartz11. It is recorded as host and added to the default directory name, so that the archives of two machines never collide. It is not looked up and not checked. Without it host is the empty string, and local says so on stderr in one line |
--python PATH |
the interpreter that scores candidates |
--endpoint URL |
server, default http://127.0.0.1:1234; the text must be exactly http://localhost, http://127.0.0.1 or http://[::1], with an optional :PORT; user information, a path, a query, another scheme or any other host is refused |
--template |
chatml (Qwen) or mistral (Devstral; needs --reasoning none) |
--reasoning |
off appends an empty think block (<think>, a blank line, </think>, a blank line) after the assistant tag of the prompt. on appends the opening of the block (<think> and a line end), as the Qwen3.x templates do when thinking is enabled: the reply is then the reasoning, </think> and the answer, and only the text after the first </think> is read as module, report or canary reply (a reply without </think> has no answer; the whole reply stays in sessions.jsonl). none appends nothing and is the value for a model without a reasoning mode: for such a model off and on send a block that its template never writes |
--attempts, --max-tokens, --report-tokens, --session-timeout, --failure-chars |
budgets: the first four and the failure length are positive (--attempts at least 1), --session-timeout is positive and finite. The session timeout is the wall clock of one whole answer. --failure-chars is the upper bound of the failure summary a repair prompt shows |
--score-timeout S |
limits every scoring call, default 120 s, positive and finite; a timeout counts as one evaluation error |
--temperature, --top-p, --top-k, --seed |
sampling: --temperature finite and not negative, --top-p in (0, 1], --top-k not negative. The session of attempt n, generate or repair, uses --seed plus n minus 1, so that a repair does not replay its input under the same seed; the report session uses --seed |
The command refuses to run, before the first session, when the working tree is dirty (a tracked file has a change, or an untracked file lies outside regen/runs/, in the project’s folder; an untracked earlier run under regen/runs/ is fine), when --out exists and is not empty, when the endpoint is not local or does not answer GET /v1/models or does not list --model, when lsof or git is missing, when --protocol is not an active decision record, and for an invalid option. It refuses as well when the scoring interpreter cannot be probed for its Python and pytest versions (there is no “unknown”), when the evaluations do not all pass or a dependent fails on the original module at the base commit. The driver does not estimate the prompt’s size: a prompt that does not fit is caught by the server’s error and by the check of prompt_tokens against --context-length after every reply. A run is judged against the commit it started from: the bundle, the evaluations, the unit tests, the dependents and the original’s docstring examples all come from HEAD, never from the working tree, and [base] commit of run.toml is its full SHA.
The evaluations and the dependents on the original module are a built-in positive control. The original is what they were written for, so they must pass on it; if they do not, the interpreter, pytest, a missing package or a time limit that is too short makes every later verdict a verdict about the machine, and the run does not start. Their counts are recorded as [control], so a reader of the archive sees that the environment was sound. [tool] packages_sha256 is the SHA-256 of the sorted name==version lines of every distribution installed in the scoring interpreter: a virtual environment is mutable, and this shows whether two runs were scored in the same one.
The driver samples the remote endpoints of its own sockets with lsof every 0.25 s and records them in [egress]. This is a record, not a proof: it sees only the driver’s process, only at the sampling instants, and the remotes always include the loopback address of the model server, which may itself contact anything. A run whose sockets reached an address that is not loopback is aborted (abort_class = "egress"). The requests use http.client directly: no proxy of the environment is asked and no redirect is followed.
What a repair sees. Its <failures> block opens with the counts (Evaluations: P passed, F failed, E errors.) and lists each failing durable evaluation (FAILED or ERROR, the test id and at most ten lines of the assertion or exception, at most 240 characters each), whole entries in pytest’s order, up to --failure-chars; K more failing evaluations are not shown. says how many were left out. Without such a list (a timeout, a usage error, a conftest.py that does not import) the counts are followed by the tail of the output. The text is the same for the same candidate: temporary paths, the numbered directory of pytest, mkdtemp names, object addresses and the duration are replaced by placeholders (<worktree>, <tmp>, pytest-of-<user>/pytest-<n>, 0x<addr>, <time>).
Replies that are not evaluated use up their attempt and are recorded with wrote_module = false, a candidate_class and a candidate_error:
candidate_class |
reply | next attempt |
|---|---|---|
no_module |
no complete fenced module | a repair with the notice in place of the failures |
truncated |
cut off at the token limit | a repair with the notice |
surrogate |
a lone surrogate in the module | a repair with the notice |
syntax_error |
a module that does not compile; the scoring interpreter compiles it and does not run it | a repair that shows the invalid module and the SyntaxError text |
unchanged |
the reply to a repair is the module of its prompt, byte for byte | a fresh generation: the generate prompt, no module, no failures |
A change of whitespace alone makes a new module. An unchanged module costs no worktree and no pytest run.
A failure of the harness, the network or the scoring environment ends the run, and is never recorded as a failure of the model. The driver writes run.toml with status = "aborted", an abort_reason and an abort_class, keeps sessions.jsonl with the failed request, and exits with code 2. The generator did not fail: repeat the run (its directory name gets a suffix -r2, so the aborted one stays). babregen check ignores aborted runs for PROV08 and PROV09. The classes:
abort_class |
the run ended because |
|---|---|
network |
the connection failed or was reset |
timeout |
the answer was not complete after --session-timeout seconds of wall clock (see the note below the table) |
http_<code> |
the server answered with a status other than 200 (http_400, http_503, http_302: a redirect is not followed) |
bad_json |
the reply is not the JSON that /v1/completions sends, or it has no usage or no integer usage.prompt_tokens (a server that does not report usage cannot be audited) |
context |
the reply does not fit --context-length: prompt_tokens plus completion_tokens exceed it, or finish_reason is length and prompt_tokens plus --max-tokens exceed it (the window, not the budget, cut the reply); a complete reply that fits is never aborted |
model_mismatch |
the model of a reply is not --model (a strict comparison; --canary is the cheap probe that shows a mismatch before a long run) |
egress |
the driver’s sockets reached an address that is not loopback |
internal |
an exception of the harness itself, or an exit raised inside the run (the traceback is on stderr) |
interrupted |
Ctrl-C; run.toml is written and the interrupt is raised again |
A session that reaches --session-timeout aborts the run with class timeout: a slow or looping generation is not recorded as an attempt, so such runs are selected out of the completed ones, and an analysis of many runs has to count them as non-completions. A setup refusal (the section above) writes to standard error only, leaves no run directory and no run.toml, and exits 2; a batch must capture the log of every driver to know why a run did not start.
A reply that holds a lone surrogate (JSON allows one; no file can) counts as a reply without a module. The gap report is best effort: it is asked after the unit tests, the dependents and accept have run, so a failing report session leaves a completed run with its verdict and a report_error, and no report.md.
What a run leaves behind
The run directory holds these files; the keys of run.toml are listed in run records.
| file | content |
|---|---|
run.toml |
the record: protocol and protocol_record, status (and abort_reason, abort_class, report_error), babregen_version, start and finish, [base] (the commit), [tool] (Python and pytest versions, the hash of the installed distributions, the scoring time limit), [control] (the evaluations and the dependents on the original module, local only), accepted and rule, [inputs] (hashes of the bundle, the module and the --allow files at the base; babregen check reports PROV08 and PROV09 once they no longer match), one [[attempt]] per try with its evaluation counts, and [final] with the unit-test and dependent counts of the final module; local adds host, [generator] (model, its hash, context length, sampling), one [[session]] per completed session (with the hash of its rendered prompt, tokens, seconds and finish reason) and [egress] |
bundle.md |
the bundle the generator was given, built from the base commit |
<module>-<n>.py, evaluations-<n>.txt |
each candidate that was written, and the output of its evaluations |
unit_tests.txt, dependents.txt |
the scores of the final module; dependents.txt has one PASS/FAIL line per dependent |
sessions.jsonl |
local: every request and reply, and the failed request of an aborted run |
report.md |
local: the gap report of the generator |
canary.md |
local --canary: the reply to the confinement prompt |
The generator’s report, a list of every place where the bundle was ambiguous, silent or contradictory, is the most valuable output: fix the spec where it points.
Scoring a whole archive again
Every archived candidate can be judged again. babregen score UNIT <candidate> --base <commit> --timeout <s> gives, for the same candidate, base commit, time limit, Python and pytest, the same evaluations_*, unit_tests_* and dependents_* counts and the same accepted as the run that produced the candidate: the output text that scoring stores depends only on the run (the path of the worktree is <worktree>, the duration <time>, and the other names that change between two scorings have placeholders), and the environment is fixed. The time limit is an input of the verdict: a candidate that needs 5 s passes under a limit of 120 s and is an evaluation error under one of 3 s, so the script passes the [tool] scoring_timeout_s of the run. The script below scores every candidate that a completed run under regen/runs/ wrote, compares the counts with the [[attempt]] tables, and the verdict and the unit-test and dependent counts of the final candidate with accepted and [final]. It also compares the versions of Python, pytest and babregen and the hash of the installed distributions with [tool]: a different environment is reported as a difference, because the counts then prove nothing. A run with no verdict to reproduce is skipped, with the reason: a canary, an aborted run, a run that wrote no module. It needs no new command, only babregen score and the standard library. First an archived run on the sample repository:
python -c 'from babregen import make_sample_repo; make_sample_repo("/tmp/rescore-demo")'
git -C /tmp/rescore-demo init -q
git -C /tmp/rescore-demo add .
git -C /tmp/rescore-demo -c user.name=demo -c user.email=demo@example.org commit -q -m demo
cp /tmp/rescore-demo/src/samplepkg/core/calc.py /tmp/candidate.py
babregen --root /tmp/rescore-demo score core.calc /tmp/candidate.py \
--out /tmp/rescore-demo/regen/runs/2026-01-01-core.calc-demoThen the loop (save it as rescore.py; pass the repository as the argument and, if the runs were scored with another interpreter than the default, its path as the second):
import subprocess
import sys
import tempfile
import tomllib
from pathlib import Path
root = Path(sys.argv[1])
python = ["--python", sys.argv[2]] if len(sys.argv) > 2 else []
COUNTS = ("sha256", "evaluations_passed", "evaluations_failed", "evaluations_errors")
FINAL = (
"sha256",
"unit_tests_passed", "unit_tests_failed", "unit_tests_errors",
"dependents_passed", "dependents_failed",
)
def score_again(run, directory, number):
"""`babregen score` for an archived candidate: exit code, its run.toml or None."""
(candidate,) = directory.glob(f"*-{number}.py")
with tempfile.TemporaryDirectory() as out:
done = subprocess.run(
[
sys.executable, "-m", "babregen", "--root", str(root), "score",
run["unit"], str(candidate), "--base", run["base"]["commit"],
"--timeout", str(run["tool"]["scoring_timeout_s"]), "--out", out, *python,
],
capture_output=True,
text=True,
check=False,
)
record = Path(out) / "run.toml"
again = tomllib.loads(record.read_text()) if record.exists() else None
return done.returncode, again, done.stderr.strip()
differ = 0
for path in sorted((root / "regen/runs").glob("*/run.toml")):
run, name = tomllib.loads(path.read_text()), path.parent.name
skip = (
"a canary judges no module" if run.get("protocol") == "canary"
else "the run was aborted" if run["status"] != "completed"
else "the run wrote no module" if "final" not in run
else None
)
if skip:
print("skipped", name, f"({skip})")
continue
problems = set()
for attempt in run["attempt"]:
if not attempt["wrote_module"]:
continue
code, again, error = score_again(run, path.parent, attempt["n"])
if again is None:
problems.add(f"attempt {attempt['n']}: score refused: {error[-80:]}")
continue
for key in ("python", "pytest", "packages_sha256"):
if again["tool"][key] != run["tool"][key]:
problems.add(f"{key} is not that of the run")
if again["babregen_version"] != run["babregen_version"]:
problems.add("babregen_version is not that of the run")
if any(again["attempt"][0][k] != attempt[k] for k in COUNTS):
problems.add(f"attempt {attempt['n']}: evaluations")
if attempt["n"] == run["final"]["attempt"] and (
any(again["final"][k] != run["final"][k] for k in FINAL)
or again["accepted"] != run["accepted"]
or code != (0 if run["accepted"] else 1)
):
problems.add("final: verdict or counts")
detail = f": {'; '.join(sorted(problems))}" if problems else ""
print("DIFFERS" if problems else "reproduced", name + detail)
differ += bool(problems)
sys.exit(differ)python rescore.py /tmp/rescore-demoreproduced 2026-01-01-core.calc-demo
The loop exits with the number of runs that differ, so a script can stop on it; a skipped run is listed and not counted. A run that does not reproduce is not a statement about the model: it means that the interpreter, pytest, the installed packages or the base commit are not those of the run ([tool] and [base] say which they were), or that the archive was changed.
Exit codes
0 if the candidate is accepted by accept/1, 1 if not; 2 for a spec, unit, option or missing-tool error (no git or lsof, a non-local endpoint, an --allow file outside the repository, a time limit that is not positive and finite, a dirty working tree (local only), an existing run directory, an unknown or superseded --protocol, an unlisted model, a scoring environment that cannot be probed or fails the original module) and for an aborted run of local (see the classes above).