Files

263 lines
11 KiB
Python

#!/usr/bin/env python3
"""null standup entry -- Codeforge lane.
Rebuilds the log from parameters, never from the wall clock:
python3 wizard-work/null/wizard.py # writes wizard.log.md next to this file
python3 wizard-work/null/check.py # exit 0 == artifact is real, 1 == broken
python3 wizard-work/null/wizard.py --restamp # date this rebuild now
python3 wizard-work/null/wizard.py --stamp "2026-10-25 06:00 UTC"
Determinism. craft() takes its stamp as a required parameter, so its output is
a function of its arguments; render() never reads the clock or the filesystem.
Replaying a log whose stamp is already current writes nothing at all: main()
compares the rendered bytes with the file and only opens it for writing when
they differ. Two replays in any checkout leave the worktree clean. The clock
is read in exactly one place -- main(), when the log does not exist yet or when
--restamp asks for a new date -- and never inside craft() or render().
Location. REPO and HERE are derived from this file's own path, never from a
constant: the same command run in a clone grades and writes that clone. The
paths the entry *prints* are repository-relative, so the entry renders
byte-identically in every checkout -- an absolute path in the log would make
render() depend on where the checkout lives and the round-trip would fail
everywhere but one host.
Binding -- and why it is NOT "the commit whose tree holds these bytes".
The entry names a commit SHA, so its own bytes can never be the blob of the
commit it names: that blob would have to contain the very SHA that the blob
itself determines. That is a hash fixed point; no commit satisfies it, and a
gate demanding it is unsatisfiable and reads red forever (the failure this
replaces). The satisfiable binding names the commit that carries the WORK --
wizard.py and check.py -- and verifies the entry itself separately, on the
remote:
* the named commit is by null and is an ancestor of the remote main;
* the named commit's blobs of wizard.py and check.py are byte-identical to
the files on disk;
* the entry's own bytes are the blob of wizard.log.md on the remote main.
Nothing here is self-referential: the work files do not contain the SHA, and
the entry is committed after the work commit it names.
Import-free by design -- stdlib only, no module-level dunder reads beyond
locating this file. check.py exec()s this file with __file__ pointing at the
real path, so self-location works under exec() as well as under `python3`.
"""
import os
import re
import subprocess
import sys
from datetime import datetime, timezone
LANE = "Codeforge - hard coding and agentic reasoning"
try:
HERE = os.path.dirname(os.path.abspath(__file__))
except NameError: # exec()'d without __file__: fall back to the documented cwd
HERE = os.path.abspath(os.path.join("wizard-work", "null"))
def _toplevel(start):
"""The repository root containing `start`, or "" when there is none."""
try:
r = subprocess.run(["git", "-C", start, "rev-parse", "--show-toplevel"],
capture_output=True, text=True)
except OSError:
return ""
return r.stdout.strip() if r.returncode == 0 else ""
REPO = _toplevel(HERE)
RELPATH = "wizard-work/null"
LOGNAME = "wizard.log.md"
LOGPATH = RELPATH + "/" + LOGNAME
STAMP_FMT = "%Y-%m-%d %H:%M UTC"
STAMP_RE = re.compile(r"self-verified at [0-9-]+ [0-9:]+ UTC")
TASK = "name the line a mutated standup entry changed, and commit the negative control"
AREA = "wizard-work/null"
OPERATOR = "null"
WORK = [
"wizard.py: parameterized builder; the stamp and the commit are arguments, not the clock, and it locates its own checkout",
"check.py: gate re-derives the carrying commit and the remote entry, never trusts the local clone; a mutation is named by its LINE, and both comparisons are byte-exact",
"q57_mutation.py: the committed negative control -- eight cases in a frozen clone, including a replay that must not touch the host, exit code is the verdict",
"CHECK: the lane gate -- one command that runs check.py and the control and grades both",
"wizard.log.md: self-describing entry naming the commit that carries the work files",
]
EVIDENCE = [
("the named commit is by null and is an ancestor of the REMOTE main", "measured",
"check.py: git ls-remote origin refs/heads/main + git merge-base --is-ancestor"),
("the named commit's work files are byte-identical to disk", "measured",
"check.py: git show <sha>:path vs the file on disk, byte comparison"),
("the entry's bytes are the blob on the REMOTE main", "measured",
"check.py: git ls-remote + git show <remote>:wizard-work/null/wizard.log.md, bytes"),
("a mutation of the entry is reported by LINE, not by byte count", "measured",
"check.py: first_differing_line() + diff_detail(); q57_mutation.py cases 1-4"),
("a mutation that leaves every line equal is reported as a terminator, not a line", "measured",
"check.py: diff_detail() returns no line number when splitlines() agree; q57_mutation.py case 5"),
("the gate on disk is the gate published on the remote main", "measured",
"check.py: git show <remote>:wizard-work/null/check.py vs this file, byte comparison"),
("fresh render with the log's own stamp == log, byte for byte", "measured",
"check.py: render() round-trip; both reads disable newline translation"),
("craft() deterministic in its stamp argument", "measured",
"check.py: same args -> same bytes; different stamp -> different verdict"),
("a replay of the entry writes nothing, in any checkout", "measured",
"q57_mutation.py case 6: the fixture's wizard.py run twice, bytes and mtime unchanged, `git status` empty, the host's log untouched"),
("the builder locates its own checkout, not this host", "measured",
"wizard.py: REPO/HERE from __file__ + `git rev-parse --show-toplevel`; q57_mutation.py case 6 runs it inside a clone"),
]
def parse_log(text):
"""Pull the fields the gate re-checks out of a rendered log."""
fields = {}
for line in text.splitlines():
s = line.strip()
for key in ("lane", "operator", "target area", "base commit", "log"):
if s.startswith("- " + key + ": "):
fields[key] = s[len("- " + key + ": "):]
if s.startswith("VERDICT: "):
body = s[len("VERDICT: "):]
if " - " in body:
fields["task"] = body.split(" - ", 1)[0]
if "self-verified at " in body:
fields["stamp"] = body.split("self-verified at ", 1)[1].rstrip(" .")
return fields
def craft(task, area, lane, commit, operator, stamp, log=LOGNAME):
"""Build one standup entry. stamp is a parameter: replay is reproducible."""
verdict = "VERDICT: %s - %s built and self-verified at %s." % (task, area, stamp)
check = "CHECK: bash %s/CHECK" % RELPATH
summary = "%s lane entry: %s" % (lane, "; ".join(WORK))
return verdict, check, summary
def render(task, area, lane, commit, operator, stamp, work=WORK, log=LOGNAME):
"""Render the entry. Pure in its arguments: no clock, no filesystem."""
verdict, check, _ = craft(task, area, lane, commit, operator, stamp, log=log)
rows = "\n".join("| %s | %s | %s |" % (c, k, p) for c, k, p in EVIDENCE)
return """# null - standup entry
- lane: %s
- operator: %s
- target area: %s
- base commit: %s
- log: %s
## what was built
%s
## evidence
| claim | status | proof |
| --- | --- | --- |
%s
## result
%s
%s
## replay
```
python3 %s/wizard.py
bash %s/CHECK
```
""" % (lane, operator, area, commit, log,
"\n".join("- " + w for w in work), rows, verdict, check, RELPATH, RELPATH)
def stamp_now():
"""The current UTC minute, in the log's stamp format."""
return datetime.now(timezone.utc).strftime(STAMP_FMT)
def restamp(text, stamp=None):
"""Replace the stamp in a rendered log. Deterministic: no clock call here."""
return STAMP_RE.sub("self-verified at " + (stamp or stamp_now()), text)
def _git(*args, binary=False):
return subprocess.run(["git", "-C", REPO] + list(args),
capture_output=True, text=not binary)
def head_sha():
"""HEAD, for anyone who wants the local tip."""
return _git("rev-parse", "HEAD").stdout.strip() or ""
def _main_shas(path):
"""Commits on origin/main that ever touched `path`, newest first."""
r = _git("rev-list", "origin/main", "--", path)
if r.returncode != 0 or not r.stdout.strip():
return []
return r.stdout.split()
def _blob_matches(sha, path):
"""True iff commit `sha`'s blob at `path` is byte-identical to the disk file."""
local = os.path.join(REPO, path)
if not os.path.isfile(local):
return False
with open(local, "rb") as fh:
want = fh.read()
blob = _git("show", "%s:%s" % (sha, path), binary=True)
return blob.returncode == 0 and blob.stdout == want
def commit_carrying(paths):
"""The newest commit on origin/main whose blobs for every path equal disk.
That is the commit the entry names: it is the one that carries the exact
work bytes, so the entry cannot name a commit that does not hold them.
Returns "" when no such commit exists (the entry is not committed yet).
"""
cands = _main_shas(paths[0])
for sha in cands:
if all(_blob_matches(sha, p) for p in paths):
return sha
return ""
def main(argv=None):
argv = list(sys.argv[1:] if argv is None else argv)
path = os.path.join(HERE, LOGNAME)
stamp = parse_log(open(path, encoding="utf-8").read()).get("stamp") if os.path.exists(path) else None
if "--restamp" in argv:
stamp = None # date this rebuild now, deliberately
for i, a in enumerate(argv):
if a == "--stamp" and i + 1 < len(argv):
stamp = argv[i + 1] # an explicit date always wins
if not stamp:
stamp = stamp_now() # first build, or an explicit restamp; replays reuse it
sha = commit_carrying(["wizard-work/null/wizard.py", "wizard-work/null/check.py",
"wizard-work/null/q57_mutation.py", "wizard-work/null/CHECK"])
if not sha:
sha = "unresolved" # the gate refuses to pass on this
print("warning: no commit on origin/main carries these bytes yet -- "
"commit and push the work files, then re-run this builder")
text = render(TASK, AREA, LANE, sha, OPERATOR, stamp)
want = text.encode("utf-8")
have = open(path, "rb").read() if os.path.exists(path) else b""
if have == want:
print("unchanged: %s already reads this way (%d bytes, %s)"
% (LOGNAME, len(want), sha[:8] or "unresolved"))
else:
with open(path, "wb") as fh:
fh.write(want)
print("wrote: %s (%d bytes, %s)" % (LOGNAME, len(want), sha[:8] or "unresolved"))
verdict, check, _ = craft(TASK, AREA, LANE, sha, OPERATOR, stamp)
print(verdict)
print(check)
if __name__ == "__main__":
main()