fix(785): close the re-review's BLOCKER — the leak guard pinned the FIX, not the property

Third cold review, this one scoped to the previous two fix commits. Its central finding is
the one worth reading, because the guard it faults is the guard I added to stop exactly
this class of thing.

BLOCKER — `test_the_subprocess_env_CARRIES_the_isolated_hook_fire_log_dir` asserted on
`_env()`'s RETURN VALUE. `_env()` can be perfectly correct while a call site passes
something else, and that is the reintroduction a future tidy-up actually produces.
Demonstrated: leave `_env()` exactly as shipped, restore a module-level snapshot and point
one `env=` at it — 13 tests pass and 58 records leak. I reproduced it before acting.

The guard was pinned to the SHAPE OF THE FIX rather than to the property, which is
`verify-against-the-REAL-predecessor`: it was witnessed red against a hand-written revert,
so "pins it" and #809's "witnessed red by reintroducing the snapshot" were both overclaims.

`test_driving_a_hook_LANDS_its_records_in_the_ISOLATED_dir` asserts the EFFECT instead —
drive a real hook through the real `_run()`, records must land in the fixture's dir — with
an anti-vacuity check that the hook reached a decision first. Measured: green at head, RED
under the call-site reintroduction that the old guard passed.

MEDIUM x3 — the workflow extractor was a text scanner and review broke it three ways in
one pass. A `run: |` block scalar was invisible, so reformatting the step to the form its
own sibling in that job already uses produced a FALSE RED whose message asserts a CI
regression that has not happened. A job or step switched off with `if: false` or
`continue-on-error: true` still read as wired — 7 green with the guard not gating at all.
And `run:` inside block-scalar TEXT was extracted and executed, so an `echo we no longer
run: PYTHONPATH=. python3 ... --check` left the subprocess proof green while the real step
was deleted. Two of the three are false greens.

`fixing-a-parser-bug-introduces-the-next-one` says the second round of a string predicate
is not the last. The structure is available — pyyaml is installed by the `script-tests` job
and four sibling suites already parse this workflow with it — so the scanner is replaced by
`yaml.safe_load`, and "would actually execute" is now three explicit conditions: the job
exists, the job is not disabled, the step is neither disabled nor allowed to fail. The six
ways it can stop gating are a parametrised test, and the block-scalar REFORMAT is a
negative control, because a detector that cannot tell a reformat from a removal trains its
readers to ignore it.

LOW — `_hook_calls` skipped whole-line comments but not inline ones, and broadening the
marker in the previous commit is what made that reachable: a trailing
`# ... .claude/hooks/removed-helper.sh` reddened a correct `pre-push`. The fix for one
over-match introduced another. Verified both directions.

NIT — a section header still said "three clauses" after the fourth mutation was added.

Docs. Two accuracy fixes, both verified against the files rather than reasoned about:
`test_hook_fire_log.py` proves THREE clauses (coverage, transparency, placement), not two,
and its row's Blocks column already claims two of them — the single `Proof ref` is a column
limit, not a coverage statement. And the "1,488 stray records" figure was unreproducible in
a durable doc, the same commit having deleted the evidence. Replaced with the reproduction
and a figure that survives it: 58 records per run, measured identically on macOS/git 2.55
and Linux/git 2.47.3.

Also corrects a count in 88832047b's own message: it says the inversion reddens "8 of 12";
that file had 13 tests at that commit. Third mislabelled figure in this branch, all three
in messages about mislabelled figures.

Refs: #785
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-21 21:29:00 +02:00
co-authored by Claude Opus 5
parent a01def3f10
commit b2b651779a
4 changed files with 226 additions and 75 deletions
+15 -4
View File
@@ -200,10 +200,21 @@ fixture set `ETV_HOOK_FIRE_LOG_DIR` *for the test currently running* and that a
its own sandbox does not touch the real log. It cannot see another suite that snapshots
`os.environ` at IMPORT time — before the autouse fixture runs — and hands that stale mapping to its
subprocesses. That suite's hooks then write to `$HOME/.cache/ersatztv/hook-fire/` while every
assertion stays green, because the fire-log library is fail-open. #785 shipped exactly that defect
and measured 1,488 stray records before catching it; the pin is
`test_worktree_ownership_guard.py::test_the_subprocess_env_CARRIES_the_isolated_hook_fire_log_dir`,
which is per-file rather than general. Generalising it is #809.
assertion stays green, because the fire-log library is fail-open. #785 shipped exactly that defect,
inside the file added to prove those very hooks.
The reproduction is the part worth keeping: restore a module-level `{**os.environ}` snapshot — or
leave the helper correct and point a single `env=` argument at one — then run that file and count
records for its synthetic session ids. **58 per run**, measured identically on macOS/git 2.55 and
Linux/git 2.47.3. (The accumulated total observed before the fix ran to four figures across many
runs; that is an observation rather than a reproducible measurement, so check the per-run figure.)
The pin is `test_worktree_ownership_guard.py::test_driving_a_hook_LANDS_its_records_in_the_ISOLATED_dir`,
which asserts the EFFECT — records land in the fixture's dir — rather than the shape of the fix. Its
predecessor asserted the helper's return value, and cold review showed that leaves the call site
unguarded: `_env()` correct, one `env=` reverted, all tests green, records still leaking. Pinning to
a hand-written revert rather than to the property is `verify-against-the-REAL-predecessor`. It is
still per-file rather than general; generalising it is #809.
**That unproven set carries no number here on purpose.** It restated the count, drifted the moment
the BOM guard was regraded, and `test_the_summary_counts_match_the_table` cannot see it — the parser
+172 -67
View File
@@ -23,6 +23,9 @@ import subprocess
import sys
from pathlib import Path
import pytest
import yaml
import scripts.build_decisions_catalog as bc
import scripts.decisions_lib as dl
@@ -138,41 +141,63 @@ WORKFLOW = REPO_ROOT / ".gitea" / "workflows" / "pr-checks.yml"
def _decisions_guard_run_lines(workflow: Path | None = None) -> list[str]:
"""Every ACTIVE `run:` line inside the `decisions-guard` job, scoped to that job.
"""Every command line the `decisions-guard` job would ACTUALLY execute.
Three things this deliberately does, each closing a way the extractor could report coverage
that is not there:
Parsed with `yaml.safe_load`, not scanned as text. The first version of this scanned lines for
the literal `run:`, and cold review broke it three ways in one pass: a `run: |` block scalar was
invisible (its content lines contain no `run:` — and the sibling "Validate decision lifecycle"
step in this very job uses that form); a job or step switched off with `if: false` or
`continue-on-error: true` still read as wired; and `run:` appearing inside block-scalar *text*
(`echo we no longer run: ...`) was extracted and executed as though it were the step's command.
Two of those are false GREENS.
* it finds the job by its key (`decisions-guard:`) and stops at the next top-level job, so a
matching command in some OTHER job cannot stand in for this one;
* it strips comment lines FIRST, so a step that has been commented out — the ordinary way a
CI check gets switched off during an incident and never switched back — does not read as
wired. `guard-ships-with-mutation-proof` is explicit that the guard being WIRED is not the
guard RUNNING, and a text search over YAML cannot tell those apart unless it excludes
comments;
* it returns the job's run lines rather than a single grepped match, so the caller asserts
the command it needs is among the commands that job actually executes.
`fixing-a-parser-bug-introduces-the-next-one` says a string predicate over structured text needs
several rounds and then fails in a way nobody anticipated. The structure is available — `pyyaml`
is installed by the `script-tests` job and four sibling suites already parse this workflow with
it — so this reads the structure instead of guessing at it.
"Actually execute" is the operative phrase, and it is three separate conditions: the job exists,
the job is not disabled, and the step is neither disabled nor allowed to fail. A guard that is
present but switched off is the `guard-ships-with-mutation-proof` distinction between a guard
being WIRED and a guard RUNNING.
"""
lines = (workflow or WORKFLOW).read_text().splitlines()
try:
start = next(i for i, ln in enumerate(lines) if ln.strip() == "decisions-guard:")
except StopIteration:
raise AssertionError(
"no `decisions-guard:` job in pr-checks.yml. Either the job was renamed or removed — "
"the second is the far more serious finding, and this test is where it surfaces"
) from None
indent = len(lines[start]) - len(lines[start].lstrip())
body = []
for ln in lines[start + 1 :]:
stripped = ln.strip()
if stripped and not stripped.startswith("#"):
cur = len(ln) - len(ln.lstrip())
if cur <= indent:
break
if stripped.startswith("#"):
doc = yaml.safe_load((workflow or WORKFLOW).read_text())
jobs = (doc or {}).get("jobs") or {}
job = jobs.get("decisions-guard")
assert job is not None, (
"no `decisions-guard` job in pr-checks.yml. Either it was renamed or it was removed — the "
f"second is the far more serious finding. Jobs present: {sorted(jobs)}"
)
assert not _disabled(job), (
"the `decisions-guard` job is disabled at the job level "
f"(if: {job.get('if')!r}, continue-on-error: {job.get('continue-on-error')!r}), so nothing "
"in it runs — including the catalog guard"
)
lines: list[str] = []
for step in job.get("steps") or []:
if _disabled(step):
continue
body.append(ln)
return [ln.split("run:", 1)[1].strip() for ln in body if "run:" in ln]
run = step.get("run")
if not run:
continue
lines.extend(ln.strip() for ln in str(run).splitlines() if ln.strip())
return lines
def _disabled(node: dict) -> bool:
"""A job or step that cannot fail the run: switched off, or allowed to fail.
`if:` is normally an expression string that is truthy at parse time (`github.event_name == ...`)
and only a literal false/`"false"` means "never". `continue-on-error: true` is the subtler one —
the step still runs and still reports, but its failure does not fail the job, so it is not a
gate.
"""
cond = node.get("if", True)
if cond is False or (isinstance(cond, str) and cond.strip().lower() == "false"):
return True
coe = node.get("continue-on-error", False)
return coe is True or (isinstance(coe, str) and coe.strip().lower() == "true")
def _ci_check_command(workflow: Path | None = None) -> list[str]:
@@ -180,58 +205,138 @@ def _ci_check_command(workflow: Path | None = None) -> list[str]:
`testing.guard-derives-population-from-source`: a hand-copied command is a second copy of the
workflow that drifts silently, and this test's entire value is that it runs what CI runs.
The match requires the line to BEGIN with `PYTHONPATH=.` rather than merely to contain the
script name, because a block scalar's text can mention the command without invoking it — an
`echo we no longer run: PYTHONPATH=. python3 scripts/build_decisions_catalog.py --check` was
extracted and executed by the previous version, which is a guard proving a command nobody runs.
"""
runs = _decisions_guard_run_lines(workflow)
matches = [r for r in runs if "build_decisions_catalog.py" in r and "--check" in r]
matches = [r for r in runs if r.startswith("PYTHONPATH=.") and "build_decisions_catalog.py" in r and "--check" in r]
assert matches, (
"the `decisions-guard` job has no ACTIVE step running "
"`build_decisions_catalog.py --check`. The catalog guard has stopped running in CI — that "
f"is the finding, not this test's failure. Active run lines in that job: {runs}"
f"is the finding, not this test's failure. Active command lines in that job: {runs}"
)
assert len(matches) == 1, f"expected exactly one such step, found {matches}"
body = matches[0]
assert body.startswith("PYTHONPATH=."), (
f"the decisions-guard invocation no longer starts with PYTHONPATH=.: {body!r}"
)
return ["bash", "-c", body.replace("python3", sys.executable, 1)]
assert len(matches) == 1, f"expected exactly one such command, found {matches}"
return ["bash", "-c", matches[0].replace("python3", sys.executable, 1)]
def test_the_extractor_rejects_a_COMMENTED_OUT_step():
"""A step commented out is a guard that has stopped running, and must not read as wired.
@pytest.mark.parametrize(
"label,mutate",
[
(
"the step is COMMENTED OUT",
lambda s: s.replace(
" - name: Active catalog in sync\n"
" run: PYTHONPATH=. python3 scripts/build_decisions_catalog.py --check\n",
" # - name: Active catalog in sync\n"
" # run: PYTHONPATH=. python3 scripts/build_decisions_catalog.py --check\n",
1,
),
),
(
"the step is DELETED",
lambda s: s.replace(
" - name: Active catalog in sync\n"
" run: PYTHONPATH=. python3 scripts/build_decisions_catalog.py --check\n",
"",
1,
),
),
(
"the step is switched off with `if: false`",
lambda s: s.replace(
" - name: Active catalog in sync\n"
" run: PYTHONPATH=. python3 scripts/build_decisions_catalog.py --check\n",
" - name: Active catalog in sync\n"
" if: false\n"
" run: PYTHONPATH=. python3 scripts/build_decisions_catalog.py --check\n",
1,
),
),
(
"the step is allowed to fail with `continue-on-error: true`",
lambda s: s.replace(
" - name: Active catalog in sync\n"
" run: PYTHONPATH=. python3 scripts/build_decisions_catalog.py --check\n",
" - name: Active catalog in sync\n"
" continue-on-error: true\n"
" run: PYTHONPATH=. python3 scripts/build_decisions_catalog.py --check\n",
1,
),
),
(
"the whole JOB is switched off with `if: false`",
lambda s: s.replace(
" decisions-guard:\n name: decisions lifecycle\n runs-on: small\n"
" if: github.event_name == 'pull_request'\n",
" decisions-guard:\n name: decisions lifecycle\n runs-on: small\n if: false\n",
1,
),
),
(
"the command survives only as TEXT inside another step's block scalar",
lambda s: s.replace(
" - name: Active catalog in sync\n"
" run: PYTHONPATH=. python3 scripts/build_decisions_catalog.py --check\n",
" - name: Note\n"
" run: |\n"
" echo we no longer run: PYTHONPATH=. python3 "
"scripts/build_decisions_catalog.py --check\n",
1,
),
),
],
)
def test_a_guard_that_stopped_RUNNING_is_DETECTED(tmp_path, label, mutate):
"""Six ways the catalog guard can stop gating, each of which must be caught.
Without this the subprocess proof below stays green for as long as the text survives anywhere in
the file — including inside the `#` that switched it off. That is the shape
`guard-ships-with-mutation-proof` names as "the guard being WIRED is not the guard RUNNING".
Commenting out is one of them and was the only one the first version detected. `if: false`,
`continue-on-error: true` and a job-level `if: false` all leave the text in place, and a mention
inside another step's block scalar leaves it in place AND parseable — that one had the extractor
executing a command out of an `echo`.
"""
active = _decisions_guard_run_lines()
assert any("build_decisions_catalog.py" in r for r in active), "precondition: it is wired today"
for r in active:
assert not r.lstrip().startswith("#"), f"a comment line survived the strip: {r!r}"
raw = WORKFLOW.read_text()
commented = raw.replace(
mutated = mutate(raw)
assert mutated != raw, f"the mutation for {label!r} matched nothing; RETARGET it"
alt = tmp_path / "pr-checks.yml"
alt.write_text(mutated)
try:
_ci_check_command(alt)
except AssertionError:
return
raise AssertionError(
f"the extractor still reported the catalog guard as running when {label}. The subprocess "
"proof below would stay green over a guard CI does not gate on."
)
def test_the_extractor_accepts_the_step_in_BLOCK_SCALAR_form(tmp_path):
"""The negative control for the six above: a legitimate reformatting must NOT be flagged.
`run: |` is idiomatic in this very job (the sibling "Validate decision lifecycle" step uses it),
and the text-scanning version reported that form as "the guard has stopped running in CI" — a
false red whose message asserts a serious regression that has not happened. A detector that
cannot tell a reformat from a removal trains its readers to ignore it.
"""
raw = WORKFLOW.read_text()
mutated = raw.replace(
" - name: Active catalog in sync\n"
" run: PYTHONPATH=. python3 scripts/build_decisions_catalog.py --check\n",
" # - name: Active catalog in sync\n"
" # run: PYTHONPATH=. python3 scripts/build_decisions_catalog.py --check\n",
" - name: Active catalog in sync\n"
" run: |\n"
" PYTHONPATH=. python3 scripts/build_decisions_catalog.py --check\n",
1,
)
assert commented != raw, "retarget this mutation; the step's text has changed"
assert mutated != raw, "retarget this reformatting; the step's text has changed"
import tempfile
with tempfile.TemporaryDirectory() as d:
alt = Path(d) / "pr-checks.yml"
alt.write_text(commented)
raised = False
try:
_ci_check_command(alt)
except AssertionError:
raised = True
assert raised, (
"the extractor still found the command after the step was commented out, so the subprocess "
"proof would stay green over a guard CI no longer runs"
)
alt = tmp_path / "pr-checks.yml"
alt.write_text(mutated)
cmd = _ci_check_command(alt)
assert "build_decisions_catalog.py" in cmd[-1], cmd
def test_CLI_subprocess_exits_nonzero_on_a_stale_catalog(tmp_path):
+5 -3
View File
@@ -63,9 +63,11 @@ def _hook_calls(text: str) -> list[str]:
"""
names = []
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("#"):
continue
# INLINE comments too, not just whole-line ones. Broadening the marker from `./.claude/hooks/`
# to the path segment made a trailing `# ... .claude/hooks/removed-helper.sh` match, which
# would redden this file for a `pre-push` that is perfectly correct — a false red the
# narrower marker did not have. The fix for one over-match must not introduce another.
stripped = line.split("#", 1)[0].strip()
marker = ".claude/hooks/"
if marker in stripped:
rest = stripped.split(marker, 1)[1]
+34 -1
View File
@@ -184,6 +184,39 @@ def test_the_subprocess_env_CARRIES_the_isolated_hook_fire_log_dir():
)
def test_driving_a_hook_LANDS_its_records_in_the_ISOLATED_dir(tmp_path):
"""The invariant, asserted at the EFFECT rather than at the helper that is supposed to produce it.
`test_the_subprocess_env_CARRIES_...` above checks `_env()`'s return value, and that is not the
same claim: `_env()` can be perfectly correct while a call site passes something else. Cold
review demonstrated exactly that — restore the module-level snapshot and change one `env=_env()`
back to `env=_ENV`, and all thirteen tests pass while 54 records leak into the real log. The
guard was pinned to the shape of the fix instead of to the property, which is
`verify-against-the-REAL-predecessor`: a hand-written revert is not the code a future tidy-up
produces.
So this drives a real hook through the real `_run()` and asserts the records landed where the
fixture put them. It cannot pass while anything in this file logs to the production dir,
whatever the mechanism.
"""
isolated = Path(os.environ["ETV_HOOK_FIRE_LOG_DIR"])
before = {p.name for p in isolated.glob("*.jsonl")} if isolated.exists() else set()
repo = _scratch_repo(tmp_path)
wt = _add_worktree(repo, "wt-a", MARKER_HOOK, SESSION_A)
rc, out = _run(GUARD, _commit_payload(SESSION_B, wt), wt)
# Anti-vacuity: if the hook decided nothing, it may simply have had nothing to log.
assert rc == 0 and _denied(out), f"the hook reached no decision, so 'records landed' would prove nothing: {out!r}"
after = {p.name for p in isolated.glob("*.jsonl")} if isolated.exists() else set()
assert after > before, (
f"driving two hooks added no record to the isolated log dir {isolated}. Either the "
"instrumentation stopped firing, or these hooks are logging somewhere else — and the only "
"somewhere else is the production log this file must never touch"
)
def test_the_marker_hook_really_marks_the_worktree_it_was_told_about(tmp_path):
repo = _scratch_repo(tmp_path)
wt = _add_worktree(repo, "wt-a", MARKER_HOOK, SESSION_A)
@@ -300,7 +333,7 @@ def test_a_git_C_into_a_foreign_worktree_is_DENIED_from_the_main_tree(tmp_path):
# ------------------------------------------------------------------------------------------------
# MUTATION PROOFS — three clauses, one per thing the mechanism hangs on
# MUTATION PROOFS — four clauses, one per thing the mechanism hangs on
#
# Each mutant is an isolated copy with ONE clause disarmed, and each test asserts the UNMUTATED pair
# reaches the opposite decision on the same fixture FIRST. Without that positive control a mutation