Skip to main content

drivers.local

drivers.local

Regeneration with a local model in short sessions (babregen local).

A deterministic driver splits the work into fresh model sessions. Each session receives only the context of its step, has its own output and time budget, and leaves its result in a file; no conversation history is carried from one session to the next.

  1. Setup (no model). The run is refused, before any session, for a dirty working tree (babregen.judge.base_commit), a --out that is not empty, an endpoint that is not plainly local, does not answer or does not list --model, a missing lsof or git, an --allow file that is not in the base commit, a --protocol that is not an active decision record, an option that cannot work, a scoring interpreter that cannot be probed, and evaluations or dependents that do not pass on the original module (the positive control, recorded as [control]). The unit’s regeneration bundle is built from the base commit (babregen.judge.base_inputs) and written to bundle.md.
  2. Generate: prompt + bundle + allowed files -> the whole module in one code block.
  3. Score (no model): the module is copied into a fresh scratch git worktree of the base commit in which the original was deleted (babregen.judge), and judged by the unit’s evaluations. Every attempt has a worktree of its own, so nothing a failed attempt writes reaches the next.
  4. Repair (at most --attempts - 1 times): bundle + last module + a summary of the failures -> a corrected module. The summary holds the counts and, for each failing durable evaluation, its test id and the line of its assertion or exception, whole entries up to --failure-chars, and how many were left out; without such a list (a timeout, a conftest that does not import) it holds the tail of the output. A module that does not compile is not scored: it is named (syntax_error) and the repair shows it with the error. A reply without a complete fenced module, one that hits the output token limit and one with a lone surrogate use up their attempt without being scored; the next attempt is a repair with the notice in place of the failures. A reply to a repair that returns the module of its prompt unchanged is not scored either (unchanged); the next attempt is a fresh generation. Every attempt of one of these classes has wrote_module = false and a candidate_class. The session of attempt n uses the seed plus n minus 1.
  5. Judge: the unit tests and the dependents inside the repository (declared code consumers imported, the original’s docstring examples run) judge the final module once, each in a fresh worktree; babregen.judge.accept decides, and run.toml records the verdict. The final module is the one of the first attempt whose evaluations pass, else of the last attempt that wrote a module.
  6. Report, best effort: bundle + final module -> the places where the bundle was ambiguous, silent or contradictory. If this session fails the verdict stays and report_error says why.

A failure of the harness, the network or the scoring environment is never recorded as a failure of the model: run.toml is written with status = "aborted", an abort_reason and an abort_class (network, timeout, http_<code>, bad_json, context, model_mismatch, egress, internal or interrupted) and the exit code is 2; after Ctrl-C (or any other exit) it is raised again. An aborted run is repeated, and its directory stays.

The model is served by LM Studio on localhost; requests go to its OpenAI-compatible /v1/completions endpoint with the standard library’s http.client, which asks no proxy and follows no redirect, and the whole answer of a session must arrive within --session-timeout seconds of wall clock. The driver renders the prompt itself (--template chatml for Qwen, --template mistral for Devstral, which needs --reasoning none), so for a reasoning model it can prefill an empty <think></think> block, which is what the model’s chat template does for enable_thinking=false (--reasoning off, the default). --reasoning on opens the block (<think> and a line end), as the template does when thinking is enabled; the reply then holds the reasoning up to </think>, and only the text after it is read as the answer. --reasoning none sends no block, for a model without a reasoning mode. The model is offered no tools: it sees only what the driver puts into the prompt, so the generator is memoryless by construction, independent of a harness refusing file access. The endpoint must be exactly http://localhost, http://127.0.0.1 or http://[::1] with an optional port. The remote endpoints of the driver’s own sockets are sampled with lsof every 0.25 s and recorded; that is a record and not a proof (only this process, only at the sampling instants, and the loopback address of the server is always among them), and a run that reached an address that is not loopback is aborted. The command refuses to run where lsof is missing.

The run directory is regen/runs/<date>-<unit>-<model>-seed<seed>[-<host>][-r<k>]/ (--out changes it; -<host> is the --host label, -r<k> the first free repeat, claimed with mkdir, so two drivers never share a directory); it holds run.toml (the keys of babregen.judge.RUN_KEYS: base commit, tool versions, model and its hash, every session with the hash of its prompt, the attempts and the scores), sessions.jsonl (every prompt and reply), bundle.md, one <module>-N.py and evaluations-N.txt per attempt that wrote a module, unit_tests.txt, dependents.txt and report.md. --canary sends the confinement prompt instead and stops. This command is non-deterministic and never belongs in make guard; what it archives can be judged again with babregen score.

Usage::

babregen local core.calc --model my-model --model-sha256 <64 hex digits> \
    --context-length 32768 --protocol <decision id> \
    --allow src/samplepkg/core/helpers.py

Classes

Name Description
Egress Samples the remote endpoints of this process’s internet sockets with lsof.
Session One fresh request to the local server; nothing is kept between sessions.

Egress

drivers.local.Egress(period=0.25)

Samples the remote endpoints of this process’s internet sockets with lsof.

This is a record, not a proof: lsof is asked about the sockets of this process only, every period seconds, so a connection that opens and closes in between is missed, and a server on loopback may itself contact anything. The remotes always include the loopback address of the model server.

Attributes

Name Type Description
period float Seconds between samples.
remotes set[str] Every remote host:port seen so far.
samples int Number of samples taken.
stop threading.Event Set to end the sampling.

Examples

from babregen.drivers.local import Egress

egress = Egress(period=0.5)
print(egress.period, egress.samples, sorted(egress.remotes), egress.non_loopback)
0.5 0 [] []

Methods

Name Description
run Sample until stop is set.
run
drivers.local.Egress.run()

Sample until stop is set.

Session

drivers.local.Session(args, log)

One fresh request to the local server; nothing is kept between sessions.

Calling a session sends one /v1/completions request, prints a progress line, appends the request and the reply to the log and returns the generated text. A failed session is logged and aborts the run (the driver writes status = "aborted" and exits 2): there is no text to continue with. Its class (network, timeout, http_<code>, bad_json, context, model_mismatch) becomes abort_class.

Attributes

Name Type Description
args argparse.Namespace The parsed options (endpoint, model, sampling).
log Path The sessions.jsonl file.
records list[dict[str, object]] One record per completed call, for run.toml.

Examples

import argparse
from pathlib import Path
from tempfile import TemporaryDirectory

from babregen.drivers.local import Session

args = argparse.Namespace(endpoint="http://127.0.0.1:9", model="m")
with TemporaryDirectory() as tmp:
    session = Session(args, Path(tmp) / "sessions.jsonl")
    print(session.records)
[]

Functions

Name Description
canary_prompt The confinement test prompt for one unit.
chatml The prompt as the model’s chat template renders it, ready for generation.
code_block The module in text between matching outer fences of at least three backticks.
mistral The prompt as the Devstral Small 2 chat template renders it, for generation.
probe_endpoint Ask an OpenAI-compatible server which models it serves (GET /v1/models).
read_allowed The --allow files as the base commit has them.
run_local Regenerate one unit with a local model in short sessions and score the result.

canary_prompt

drivers.local.canary_prompt(unit)

The confinement test prompt for one unit.

The canary asks the model to attempt seven actions it must not be able to do (or, for the last two, may do) and to report what happened. The prompt names no absolute path, because sessions.jsonl keeps it and an absolute path would write the home directory and the user name of the run machine into the archive: the module is the path of the unit relative to the repository, the settings file is ~/.claude/settings.json and the listing is ls ...

Parameters

Name Type Description Default
unit Unit The unit whose module the model must not be able to read. required

Returns

Name Type Description
str str The prompt text.

Examples

from pathlib import Path
from tempfile import TemporaryDirectory

from babregen import load_spec, make_sample_repo
from babregen.drivers.local import canary_prompt

with TemporaryDirectory() as tmp:
    root = make_sample_repo(Path(tmp) / "demo")
    unit = load_spec(root).units["samplepkg.core.calc"]
    print(canary_prompt(unit).splitlines()[3])
1. Read src/samplepkg/core/calc.py

chatml

drivers.local.chatml(system, user, reasoning)

The prompt as the model’s chat template renders it, ready for generation.

reasoning="off" appends an empty think block, <think>\n\n</think>\n\n, after the assistant tag, the rendering of enable_thinking=false in the Qwen3.x chat templates. "on" appends the opening of the block, <think>\n, their rendering when thinking is enabled, so the reply starts inside the reasoning (see answer). "none" appends nothing. For a model without a reasoning mode, such as Qwen3-Coder, whose template has no think block at all, "off" and "on" therefore send a block that the template never writes and "none" sends what the template writes.

Parameters

Name Type Description Default
system str The system message. required
user str The user message. required
reasoning str "off", "on" or "none". required

Returns

Name Type Description
str str The rendered prompt.

Examples

from babregen.drivers.local import chatml

print(repr(chatml("S", "U", "off")))
print(repr(chatml("S", "U", "on")))
print(repr(chatml("S", "U", "none")))
'<|im_start|>system\nS<|im_end|>\n<|im_start|>user\nU<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n'
'<|im_start|>system\nS<|im_end|>\n<|im_start|>user\nU<|im_end|>\n<|im_start|>assistant\n<think>\n'
'<|im_start|>system\nS<|im_end|>\n<|im_start|>user\nU<|im_end|>\n<|im_start|>assistant\n'

code_block

drivers.local.code_block(text)

The module in text between matching outer fences of at least three backticks.

The opening fence starts in the first column. The closing fence must match its length and can be indented when it has exactly four backticks. All other closing fences start in the first column.

Parameters

Name Type Description Default
text str The model’s answer. required

Returns

Name Type Description
str | None str | None: The module source, or None if there is no complete fence pair.

Examples

from babregen.drivers.local import code_block

answer = "Here:\n```python\nX = 1\n```\n"
print(repr(code_block(answer)))
print(code_block("no fence"))
'X = 1\n'
None

mistral

drivers.local.mistral(system, user, reasoning)

The prompt as the Devstral Small 2 chat template renders it, for generation.

The tokenizer adds no begin-of-sequence token, so the prompt starts with <s> as the template does. The template has no reasoning block; reasoning must be "none".

Parameters

Name Type Description Default
system str The system message. required
user str The user message. required
reasoning str Must be "none". required

Returns

Name Type Description
str str The rendered prompt.

Raises

Name Type Description
ConfigurationError If reasoning is not "none".

Examples

from babregen.drivers.local import mistral

print(mistral("S", "U", "none"))
<s>[SYSTEM_PROMPT]S[/SYSTEM_PROMPT][INST]U[/INST]

probe_endpoint

drivers.local.probe_endpoint(url, timeout=5.0)

Ask an OpenAI-compatible server which models it serves (GET /v1/models).

Parameters

Name Type Description Default
url str Base URL of the server, for example "http://127.0.0.1:1234". required
timeout float Seconds to wait. Defaults to 5.0. 5.0

Returns

Name Type Description
list[str] list[str]: The model identifiers the server lists.

Raises

Name Type Description
ExternalToolError If the server cannot be reached or does not answer with the expected JSON.
ConfigurationError If url is not plainly local (see run_local).

Examples

from babregen._tools import ExternalToolError
from babregen.drivers.local import probe_endpoint

try:
    probe_endpoint("http://127.0.0.1:9", timeout=1.0)
except ExternalToolError as exc:
    print("unreachable:", "127.0.0.1:9" in str(exc))
unreachable: True

read_allowed

drivers.local.read_allowed(root, commit, allow)

The --allow files as the base commit has them.

Parameters

Name Type Description Default
root Path Repository root. required
commit str The base commit; the working tree is not read. required
allow Sequence[str] Repository-relative file names the generator may see. required

Returns

Name Type Description
list[tuple[str, str, str]] list[tuple[str, str, str]]: (name as given, text, SHA-256 of the bytes).

Raises

Name Type Description
ConfigurationError If a file lies outside root, is not a UTF-8 file of commit (untracked and ignored files are not), or is a directory.

Examples

import subprocess
from pathlib import Path
from tempfile import TemporaryDirectory

from babregen._tools import ConfigurationError
from babregen.drivers.local import read_allowed

def git(root, *args):
    subprocess.run(
        ["git", "-c", "user.name=t", "-c", "user.email=t@example.org", *args],
        cwd=root, check=True, capture_output=True,
    )

with TemporaryDirectory() as tmp:
    root = Path(tmp)
    (root / "a.py").write_text("X = 1\n")
    git(root, "init", "-q")
    git(root, "add", ".")
    git(root, "commit", "-q", "-m", "init")
    print([(name, text) for name, text, _ in read_allowed(root, "HEAD", ["a.py"])])
    try:
        read_allowed(root, "HEAD", ["../escape.py"])
    except ConfigurationError:
        print("refused")
[('a.py', 'X = 1\n')]
refused

run_local

drivers.local.run_local(spec, unit, args)

Regenerate one unit with a local model in short sessions and score the result.

Parameters

Name Type Description Default
spec RegenSpec The loaded spec; its root is the repository. required
unit Unit The unit to regenerate. required
args argparse.Namespace The parsed options of babregen local, see babregen.cli.build_parser. required

Returns

Name Type Description
int int 0 if babregen.judge.accept accepts the final module, 1 if not, 2 if the run was aborted (run.toml is written with status = "aborted" and an abort_class). With --canary: 0 after the canary session. An interrupt (Ctrl-C) is raised again once run.toml is written.

Raises

Name Type Description
ConfigurationError If the endpoint is not plainly local or does not list --model, a time limit is not positive and finite, --model-sha256 or another option is not valid, --protocol is not an active decision record, an --allow file lies outside the repository or is not in the base commit, the working tree is dirty, --out exists and is not empty, or the evaluations or the dependents do not pass on the original module.
ExternalToolError If lsof or git is missing, the endpoint does not answer GET /v1/models or the scoring interpreter cannot be probed.

Examples

from babregen.cli import build_parser

args = build_parser().parse_args(
    ["local", "core.calc", "--model", "m", "--model-sha256", "0" * 64,
     "--context-length", "4096", "--protocol", "my-protocol", "--canary"]
)
print(args.unit, args.canary, args.context_length)
core.calc True 4096