diff --git a/.claude/hooks/pretooluse-merge-consent.sh b/.claude/hooks/pretooluse-merge-consent.sh index 738227099..8ebf9654c 100755 --- a/.claude/hooks/pretooluse-merge-consent.sh +++ b/.claude/hooks/pretooluse-merge-consent.sh @@ -179,10 +179,33 @@ fi # after which a later, successful status read could still auto-grant. A transient failure would then # have produced a "merge gate: satisfied" message for a comparison that never happened. Every # unreadable input here therefore falls through to a human (`ask`), never to silence. -live_base=$(printf '%s' "$prjson" | jq -r '.base.ref // ""' 2>/dev/null || true) -if [ -z "$live_base" ]; then +# RE-READ THE BASE HERE, ONCE, FOR EVERY PATH BELOW (ersatztv#778). +# +# `$base_ref` above comes from the PR snapshot taken at the top of this hook, and the docs-only +# enumeration between there and here is up to forty round trips. A PERSISTENT retarget in that gap +# needs no ABA and no force-push: every base-dependent decision below would be formed against a +# branch the PR no longer targets. Checking a stale identifier is not checking — which is the whole +# of `process.check-and-use-pins-a-version`, so the guard enforcing that rule must not break it. +# +# This re-read first landed inside the scheduled-auto-merge branch only, which fixed the branch- +# protection lookup and left the #632 retarget DETECTION below still reading the stale snapshot. Cold +# review demonstrated the consequence with this repo's own fixture: scheduled+retarget denied, while +# immediate+retarget auto-GRANTED. That is the twin-missed shape — a fix applied to the path where it +# was noticed — so the re-read is hoisted above every consumer rather than duplicated into each. +prjson_now=$(gq "repos/$owner/$repo/pulls/$pr") +if [ -z "${prjson_now//[[:space:]]/}" ] || ! printf '%s' "$prjson_now" | jq -e 'type == "object"' >/dev/null 2>&1; then + decide ask "H10 merge gate: could not re-read PR #$pr to confirm it still targets '$base_ref' before checking the verdict against it. Confirm the target branch, then merge." +fi +base_now=$(printf '%s' "$prjson_now" | jq -r '.base.ref // ""' 2>/dev/null || true) +if [ -z "$base_now" ]; then decide ask "H10 merge gate: PR #$pr reports no base branch (.base.ref), so the verdict cannot be checked against the branch it was formed for (ersatztv#632). Confirm the PR still targets the branch it was reviewed against before merging." fi +if [ -n "$base_ref" ] && [ "$base_now" != "$base_ref" ]; then + decide deny "H6/H10 merge gate: BLOCKED — PR #$pr was retargeted from '$base_ref' to '$base_now' while this gate was evaluating. Every check formed against '$base_ref', including the changed-file enumeration and the review verdict, describes a merge that is no longer the one being requested (ersatztv#632). Re-review against '$base_now' and run: scripts/post-review-verdict.sh $pr MERGEABLE" +fi +# From here on both names are the freshly-confirmed base; they are equal by the check above. +base_ref=$base_now +live_base=$base_now if [ -n "$sha" ]; then # This is the THIRD read of this endpoint in a worst-case hook run (the ordinary-CI branch and the # scheduled-auto-merge branch each do their own). Sharing one snapshot would close a narrow @@ -356,25 +379,10 @@ else # present -> proceed, ABSENT -> deny. Absence is not a degraded read; it is #622's hole reopened, # and the whole point of that issue is that the failure is silent from the merge caller's side. [ -n "$base_ref" ] || decide ask "H6/H10 merge gate: could not resolve PR #$pr's base branch, so the 'review-verdict/h10' required-check protection that makes a scheduled auto-merge safe (ersatztv#622) can't be confirmed. Verify branch protection on the base, or merge immediately instead of scheduling." - # RE-READ THE BASE FIRST — this guard had the very defect it exists to enforce (found in the fifth - # cold-review round). `$base_ref` comes from the PR snapshot taken at the top of this hook, and - # everything between then and here is round trips: the file enumeration alone can be forty pages. - # A PERSISTENT retarget in that gap needs no ABA and no force-push: the protection lookup would - # name the OLD base, confirm `review-verdict/h10` on a branch the PR no longer targets, and grant a - # scheduled merge onto one that may require nothing. Checking a stale identifier is not checking. - # So the identifier is refreshed and compared before it is used, which is this record's own - # read-compare-refuse rule applied to the read that implements it. - prjson_bp=$(gq "repos/$owner/$repo/pulls/$pr") - if [ -z "${prjson_bp//[[:space:]]/}" ] || ! printf '%s' "$prjson_bp" | jq -e 'type == "object"' >/dev/null 2>&1; then - decide ask "H6/H10 merge gate: could not re-read PR #$pr to confirm it still targets '$base_ref' before checking that branch's protection. Confirm the target branch and its 'review-verdict/h10' required check manually, or merge immediately instead of scheduling." - fi - base_now_bp=$(printf '%s' "$prjson_bp" | jq -r '.base.ref // ""' 2>/dev/null || true) - if [ -z "$base_now_bp" ]; then - decide ask "H6/H10 merge gate: re-read PR #$pr but it reported no base branch, so it is unproven that it still targets '$base_ref'. Confirm the target and its required checks before scheduling an auto-merge." - fi - if [ "$base_now_bp" != "$base_ref" ]; then - decide deny "H6/H10 merge gate: BLOCKED — PR #$pr was retargeted from '$base_ref' to '$base_now_bp' while this gate was evaluating. Every check above was formed against '$base_ref', including the review verdict, so none of them describe the merge that would now happen (ersatztv#632). Re-review against '$base_now_bp' and run: scripts/post-review-verdict.sh $pr MERGEABLE" - fi + # The base was re-read and confirmed unchanged above, for every path — see the hoist comment + # there. It is deliberately NOT re-read a second time here: two reads would create a window + # between them for no gain, and the hoisted check already covers the enumeration gap that made + # this necessary. # 404 MUST be separated from every other failure, and `gq` cannot do it: it wraps `curl -sf`, # which turns any HTTP error into exit 22 and empty output, so "no branch protection exists at # all" is indistinguishable from "Gitea is down" through that helper. Those are opposite answers. @@ -385,13 +393,40 @@ else # Collapsing the two, which the first version of this guard did, sends the single most likely # real-world trigger ("branch protection was removed") to a human prompt that reads like a # transient hiccup. + # The ref goes in a URL PATH SEGMENT, so it is percent-encoded. A base like `release/26.4` would + # otherwise inject a `/` and request a path that does not exist — producing a 404 that this code + # would read as "unprotected" and turn into a hard DENY whose reason names a specific, false cause. + bp_ref=$(printf '%s' "$base_ref" | jq -sRr @uri) bp_file=$(mktemp) || decide ask "H6/H10 merge gate: could not allocate a temp file to read branch protection for '$base_ref'. Confirm the 'review-verdict/h10' required check manually before scheduling an auto-merge." - if [ -n "${ETV_GITEA_TOKEN:-}" ]; then - bp_code=$(curl -s -o "$bp_file" -w '%{http_code}' -H "Authorization: token $ETV_GITEA_TOKEN" "$base_url/repos/$owner/$repo/branch_protections/$base_ref" 2>/dev/null || true) - else - bp_code=$(curl -s -o "$bp_file" -w '%{http_code}' -u "$ETV_GITEA_BASICAUTH" "$base_url/repos/$owner/$repo/branch_protections/$base_ref" 2>/dev/null || true) - fi + bp_get() { # $1 = path under the repo + if [ -n "${ETV_GITEA_TOKEN:-}" ]; then + curl -s -o "$bp_file" -w '%{http_code}' -H "Authorization: token $ETV_GITEA_TOKEN" "$base_url/repos/$owner/$repo/$1" 2>/dev/null || true + else + curl -s -o "$bp_file" -w '%{http_code}' -u "$ETV_GITEA_BASICAUTH" "$base_url/repos/$owner/$repo/$1" 2>/dev/null || true + fi + } + bp_code=$(bp_get "branch_protections/$bp_ref") bp=$(cat "$bp_file" 2>/dev/null || true) + # A 404 here does NOT prove the branch is unprotected: Gitea keys this endpoint on the RULE NAME, + # so a base covered by a GLOB rule (`rel/*`) 404s on its own name while being fully protected. + # Before denying, ask the list endpoint whether any rule matches — a deny is not a prompt, it + # blocks the operation outright, and a deny whose stated cause is false is worse than an ask. + if [ "$bp_code" = "404" ]; then + bp_code=$(bp_get "branch_protections") + bp_list=$(cat "$bp_file" 2>/dev/null || true) + if [ "$bp_code" = "200" ] && printf '%s' "$bp_list" | jq -e 'type == "array"' >/dev/null 2>&1; then + # Match a rule by exact name or by its glob, the same way Gitea applies them. + bp=$(printf '%s' "$bp_list" | jq --arg b "$base_ref" -c 'map(select((.branch_name // .rule_name // "") as $n | $n == $b or ($b | test("^" + ($n | gsub("\\*"; ".*")) + "$")))) | first // empty' 2>/dev/null || true) + if [ -n "${bp//[[:space:]]/}" ]; then + bp_code=200 # a rule DOES cover this base; fall through and inspect it + else + bp_code=404 # the list was readable and nothing matches: truly unprotected + fi + else + bp_code=${bp_code:-000} # could not read the list either -> the ask arm below + bp="" + fi + fi rm -f "$bp_file" if [ "$bp_code" = "404" ]; then decide deny "H6/H10 merge gate: BLOCKED — '$base_ref' has NO branch protection at all (Gitea returned 404), so 'review-verdict/h10' is not a required check on it. A scheduled auto-merge is safe ONLY because that per-sha required check stops a commit pushed after scheduling from merging unreviewed (ersatztv#622). Restore branch protection on '$base_ref', or merge immediately (without merge_when_checks_succeed) once CI is green." diff --git a/docs/guard-inventory.md b/docs/guard-inventory.md index aeeb4e785..02cdba063 100644 --- a/docs/guard-inventory.md +++ b/docs/guard-inventory.md @@ -125,8 +125,8 @@ all. | `scripts/tests/test_post_review_verdict.py` | the `script-tests` job | PROOF | NONE | — | | `scripts/tests/test_pr_changed_files.py` | the `script-tests` job | PROOF | NONE | — | | `scripts/tests/test_prepush_rebase_check_tag_exemption.py` | the `script-tests` job | PROOF | NONE | — | -| `scripts/tests/test_remote_state_inventory.py` | the `script-tests` job, on an executable that talks to a remote service with no row in `docs/remote-state-inventory.md` | GUARD | MUTATION | `test_remote_state_inventory.py::test_MUTATION_PROOF_a_dropped_row_and_a_phantom_row_are_both_detected` | | `scripts/tests/test_prove_fix.py` | the `script-tests` job | PROOF | NONE | — | +| `scripts/tests/test_remote_state_inventory.py` | the `script-tests` job, on an executable that talks to a remote service with no row in `docs/remote-state-inventory.md` | GUARD | MUTATION | `test_remote_state_inventory.py::test_MUTATION_PROOF_a_dropped_row_and_a_phantom_row_are_both_detected` | ## What the numbers say diff --git a/docs/remote-state-inventory.md b/docs/remote-state-inventory.md index 7e23c0f0b..c3088b280 100644 --- a/docs/remote-state-inventory.md +++ b/docs/remote-state-inventory.md @@ -1,8 +1,18 @@ # Remote-state inventory (ersatztv#778) -Every executable in `scripts/` (**excluding `scripts/tests/`**), `.claude/hooks/`, `.husky/` and -`.gitea/workflows/` that reads live remote state and later acts on that read, and whether the read is -bound to something that cannot change underneath it. +Every **git-tracked** file matching one of these, that reads live remote state and later acts on +that read, and whether the read is bound to something that cannot change underneath it: + +| Directory | Files | +|---|---| +| `scripts/` (recursive, **excluding `scripts/tests/`**) | `*.sh`, `*.py` | +| `.claude/hooks/` | `*.sh` | +| `.husky/` | all tracked files | +| `.gitea/workflows/` | `*.yml`, `*.yaml` | + +The per-directory extensions are stated because the prose once attached them to `scripts/` alone +while the guard applied them everywhere, so a `.py` hook would have joined the scope the doc +described and acquired no row. The scope qualifier is load-bearing, not throat-clearing: this file twice claimed to cover "every executable in this repo" while its own derivation missed real remote readers, so the heading now @@ -30,8 +40,12 @@ artifact; the test keeps it from rotting. - **Class** — - `PINNED` — the read is bound to an immutable version identifier (a **full** commit sha, an - image digest, a monotonic event count) **and** the action re-validates against that identifier - before it commits. Binding alone is not enough; a snapshot nobody re-checks is not pinned. + image digest, a monotonic event count), and that binding still holds when the action runs. Two + shapes qualify, and the second was missing from the first wording: either the action + **re-validates** against the identifier immediately before committing (a snapshot nobody + re-checks is not pinned — binding alone is never enough), **or** the check and the use are a + single step over a value that cannot move, such as a workflow reading a full sha straight out of + its own fixed event payload. What never qualifies is a value captured early and trusted later. - `CAS` — the write itself carries a compare-and-set condition the server enforces. - `UNSAFE-KNOWN` — read-then-act with nothing pinning it, **accepted** with the reason stated in the Note. Every row here must say why the residual is tolerable, not merely that it exists. diff --git a/scripts/tests/test_merge_consent_required_check.py b/scripts/tests/test_merge_consent_required_check.py index 1b9444fc4..97075eea0 100644 --- a/scripts/tests/test_merge_consent_required_check.py +++ b/scripts/tests/test_merge_consent_required_check.py @@ -61,6 +61,17 @@ def respond(body, code="200"): sys.stdout.write(code) sys.exit(0) +if url.rstrip("/").endswith("/branch_protections"): + # The LIST endpoint, consulted only after a 404 on the by-name lookup. Gitea keys the by-name + # endpoint on the RULE name, so a base covered by a glob rule 404s there while being protected. + mode = (state / "bp").read_text().strip() + if mode == "GLOB-RULE": + respond(json.dumps([{"branch_name": "m*", "enable_status_check": True, + "status_check_contexts": ["review-verdict/h10"]}])) + if mode == "LIST-UNREADABLE": + respond('{"message":"internal error"}', "500") + respond("[]") + if "/branch_protections/" in url: # Record the call so the positive control can prove the guarded case REACHED this endpoint, # rather than passing because the hook bailed earlier for an unrelated reason. @@ -69,7 +80,7 @@ if "/branch_protections/" in url: if mode == "TRANSPORT-ERROR": # curl itself fails: no body, and `-w` prints 000. respond("", "000") - if mode == "NOT-FOUND": + if mode in ("NOT-FOUND", "GLOB-RULE", "LIST-UNREADABLE"): respond('{"message":"not found"}', "404") if mode == "FORBIDDEN": respond('{"message":"token does not have at least one of required scope(s)"}', "403") @@ -126,6 +137,15 @@ if "/pulls/" in url and "/files" in url: print("[]") sys.exit(0) +if "/status" in url and (state / "no_recorded_base").exists(): + # A verdict posted before ersatztv#632 carries no `(base: …)` marker, so the #632 detection + # takes its graceful-adoption path and forms no opinion. That isolates the hoisted retarget + # check as the ONLY guard that can deny. + print(json.dumps({"state": "success", "statuses": [ + {"context": "review-verdict/h10", "status": "success", + "description": "Review-verdict: MERGEABLE @ %s" % os.environ["STUB_SHORT"]}]})) + sys.exit(0) + if "/status" in url: # A 2xx body whose `.statuses` IS an array but whose members are scalars. `.statuses | type == # "array"` passes; indexing a number then makes jq exit 5 and, under `set -e`, kills the hook @@ -196,6 +216,10 @@ def hook(tmp_path): def set_branch_protection(self, mode): (state / "bp").write_text(mode) + def drop_recorded_base(self): + """Serve a pre-#632 verdict (no `(base: …)`), so only the hoisted check can deny.""" + (state / "no_recorded_base").write_text("1") + def set_retarget(self, ref): """Persistent retarget: every PR read after the first reports `ref`.""" (state / "retarget").write_text(ref) @@ -427,6 +451,23 @@ def test_a_SCALAR_status_row_asks_instead_of_killing_the_hook(hook): assert decision["hookSpecificOutput"]["permissionDecision"] == "ask" +def test_a_PERSISTENT_retarget_denies_on_the_IMMEDIATE_path_too(hook): + """The twin. The re-read first landed inside the scheduled branch only, so this exact case — + same fixture, `merge_when_checks_succeed` absent — AUTO-GRANTED while its sibling denied. + + Cold review demonstrated it side by side, and it is the shape this repo has on record as + "fix one path, then check its TWIN": the fix was applied where the defect was noticed, and the + other consumer of the same stale value kept it. The re-read is now hoisted above every + base-dependent decision rather than duplicated into the branch that happened to be under review. + """ + hook.drop_recorded_base() + hook.set_retarget("scratch") + reason = hook.reason(scheduled=False) + assert "deny" in reason, ( + "an immediate merge was auto-granted after the PR was retargeted mid-evaluation") + assert "scratch" in reason and "main" in reason + + def test_a_PERSISTENT_retarget_after_the_first_read_denies(hook): """The defect this guard had itself, found in the fifth cold-review round. @@ -438,6 +479,7 @@ def test_a_PERSISTENT_retarget_after_the_first_read_denies(hook): the whole of `process.check-and-use-pins-a-version` — so the guard enforcing that rule had to stop breaking it. """ + hook.drop_recorded_base() hook.set_retarget("scratch") reason = hook.reason() assert "deny" in reason, ( @@ -459,3 +501,35 @@ def test_a_NON_STRING_status_reaches_the_scheduled_validator(hook): hook.set_branch_protection("NONSTRING-STATUS-ROW") reason = hook.reason() assert "ask" in reason, "a non-string .status produced a verdict-shaped decision" + + +def test_a_base_covered_by_a_GLOB_rule_is_not_reported_as_unprotected(hook): + """Gitea keys the by-name branch-protection endpoint on the RULE name, so a base covered by a + glob rule (`m*`, `rel/*`) 404s on its own name while being fully protected. + + Reading that 404 as "unprotected" produced a hard DENY stating a specific, false cause — and a + deny is not a prompt, it blocks the operation outright. The list endpoint is consulted before + denying, and a matching rule is inspected like any other. + """ + hook.set_branch_protection("GLOB-RULE") + reason = hook.reason() + assert "NO branch protection" not in reason, ( + "a base protected by a glob rule was reported as having no protection at all") + assert "deny" not in reason, ( + "a glob rule that DOES require review-verdict/h10 was not honoured") + + +def test_an_unreadable_LIST_asks_rather_than_denying_on_the_404(hook): + """The 404 fallback must not convert 'could not confirm' into 'confirmed absent'. If the by-name + lookup 404s and the list cannot be read, nothing has been established either way.""" + hook.set_branch_protection("LIST-UNREADABLE") + reason = hook.reason() + assert "ask" in reason, "an unreadable rule list was treated as proof of absence" + assert "NO branch protection" not in reason + + +def test_the_base_ref_is_URL_ENCODED_in_the_protection_lookup(): + """A base like `release/26.4` would otherwise inject a path separator and request a URL that + does not exist, producing a 404 this code would read as 'unprotected'.""" + src = HOOK.read_text() + assert "@uri" in src, "the base ref must be percent-encoded before going in a URL path segment" diff --git a/scripts/tests/test_remote_state_inventory.py b/scripts/tests/test_remote_state_inventory.py index 3e0e6e4da..dca76aa00 100644 --- a/scripts/tests/test_remote_state_inventory.py +++ b/scripts/tests/test_remote_state_inventory.py @@ -33,7 +33,9 @@ predicate over content. from __future__ import annotations +import fnmatch import re +import subprocess from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[2] @@ -58,54 +60,99 @@ CLASSES = {"PINNED", "CAS", "UNSAFE-KNOWN", "N/A"} # safe direction" — was answered by the filter ALSO under-including. Enumerating the directories # costs more rows and has no blind spot; that is the trade the rule already made. SCOPE = ( - (REPO_ROOT / "scripts", ("*.sh", "*.py")), - (REPO_ROOT / ".claude" / "hooks", ("*.sh",)), - (REPO_ROOT / ".husky", ("*",)), - (REPO_ROOT / ".gitea" / "workflows", ("*.yml",)), + ("scripts", ("*.sh", "*.py")), + (".claude/hooks", ("*.sh",)), + (".husky", ("*",)), + (".gitea/workflows", ("*.yml", "*.yaml")), ) -# RECURSIVE. `Path.glob` is not, and the second cold review found the consequence: four nested files -# were outside the population, one of them `scripts/scripted-schedules/entrypoint.py`, which calls -# `get_context` against a live ErsatzTV server and then acts on the result. That is the third time -# this population has been found incomplete, each time by a different mechanism — first a content -# filter that omitted `git fetch`, then a non-recursive glob. Both were the same error: a claim of -# completeness resting on a traversal nobody had checked against the filesystem. +# THE POPULATION IS DERIVED FROM `git ls-files`, NOT FROM THE FILESYSTEM. # -# `scripts/tests/` is the one DIRECTORY-level exclusion, and it is a scope decision rather than a -# content filter: those files run only under pytest and authorize nothing. Their network activity is -# CONFINED rather than absent — the first wording here claimed the only calls were to PATH-installed -# stubs, which cold review falsified: `test_hook_fire_log.py` starts a real `http.server` on -# 127.0.0.1 and drives it with real `curl`, and several suites create real local git remotes. All of -# it is fixture state the test itself creates and tears down, so there is no live remote to race, -# which is why the exclusion stands — but the justification had to be true to be worth anything. -# Excluding a directory is reviewable in one line; excluding files by what they contain is what kept -# failing. -EXCLUDED_DIRS = (REPO_ROOT / "scripts" / "tests",) +# This is the third time this population has been found incomplete or wrong, each time by a +# different mechanism, and the third fix is the one that stops patching the traversal: +# +# 1. a content filter on an outbound-network token list, which omitted `git fetch` — this repo's +# commonest remote read — so a hook that fetches `origin/main` and derives a PUSH DECISION was +# structurally invisible; +# 2. a non-recursive `Path.glob`, which missed four nested files including one that calls a live +# ErsatzTV API and acts on the reply; +# 3. `Path.rglob`, which is recursive and therefore ALSO enumerated `.husky/_/` — 17 husky shims +# generated by `npm ci` via web/package.json's `prepare` script, gitignored (`.husky/_/.gitignore` +# is `*`) and untracked. That made this guard RED on every developer checkout while staying green +# in CI, whose `script-tests` job checks out and pip-installs but never runs `npm ci`. A guard +# that fails everywhere except where it runs is worse than no guard: it trains its readers to +# ignore it, and it would have done so on the artifact whose entire thesis is population +# correctness. +# +# The lesson each time was the same one this repo already wrote down — derive the population from an +# AUTHORITATIVE source — and the filesystem is not one. It reports build output, editor droppings and +# anything else that happens to be on disk, and it varies per machine. The repo's index is +# authoritative, versioned, identical for every checkout and for CI, and it excludes untracked +# generated files by construction rather than by an exclusion list that must be maintained. +# +# `scripts/tests/` is still excluded explicitly, because those files ARE tracked. That exclusion is a +# scope decision, reviewable in one line: they run only under pytest and authorize nothing. Their +# network activity is CONFINED rather than absent — `test_hook_fire_log.py` starts a real +# `http.server` on 127.0.0.1 and drives it with real `curl`, and several suites create real local git +# remotes — but all of it is fixture state the test creates and tears down, so there is no live remote +# to race. +EXCLUDED_DIRS = ("scripts/tests",) # `| ` + backticked path, optionally followed by ` — `, then the class cell. _ROW = re.compile(r"^\|\s*`([^`]+?)`[^|]*\|\s*`([^`]+)`\s*\|", re.M) +def _tracked_files() -> list[str]: + """Every file git tracks, as repo-relative posix paths. + + Fails LOUDLY rather than returning nothing: an empty population would make every completeness + assertion below pass vacuously, which is the exact failure this guard exists to prevent. + """ + proc = subprocess.run( + ["git", "-C", str(REPO_ROOT), "ls-files", "-z"], + capture_output=True, check=True, + ) + return [p for p in proc.stdout.decode().split("\0") if p] + + def derived_population() -> set[str]: - """Every in-scope file, as a repo-relative posix path. No content predicate of any kind.""" + """Every in-scope tracked file, as a repo-relative posix path. + + No content predicate of any kind: a file that reads no remote state earns an explicit `N/A` row + rather than silently staying out. + """ found: set[str] = set() - for directory, globs in SCOPE: - if not directory.is_dir(): + for path in _tracked_files(): + if any(path == d or path.startswith(d + "/") for d in EXCLUDED_DIRS): continue - for pattern in globs: - for path in sorted(directory.rglob(pattern)): - if not path.is_file(): - continue - if any(excluded in path.parents for excluded in EXCLUDED_DIRS): - continue - found.add(path.relative_to(REPO_ROOT).as_posix()) + for directory, globs in SCOPE: + if not (path == directory or path.startswith(directory + "/")): + continue + name = path.rsplit("/", 1)[-1] + if any(fnmatch.fnmatch(name, pattern) for pattern in globs): + found.add(path) + break return found +def _inventory_section(text: str) -> str: + """Only the classification tables, never the surrounding prose. + + This is the second time this parser has read the document's own explanation as data: the + UNSAFE-KNOWN justification check once parsed the "Columns" paragraph that DEFINES + `UNSAFE-KNOWN`, and adding a scope TABLE to the heading made three more prose rows parse as + sites. A guard that treats its own documentation as input is the failure this whole change is + about, so the boundary is explicit rather than left to a cleverer regex. + """ + start = text.index("## The inventory") + end = text.index("## Limits", start) + return text[start:end] + + def inventory_rows(text: str | None = None) -> list[tuple[str, str]]: if text is None: text = INVENTORY.read_text(encoding="utf-8") - return _ROW.findall(text) + return _ROW.findall(_inventory_section(text)) def inventory_sites(text: str | None = None) -> set[str]: @@ -172,7 +219,11 @@ def test_MUTATION_PROOF_a_dropped_row_and_a_phantom_row_are_both_detected(): assert population - inventory_sites(dropped), ( "a row was removed from the inventory and the comparison still reported complete coverage") - phantom = text + "\n| `scripts/does-not-exist.sh` — invented | `PINNED` | n/a |\n" + # Inserted INSIDE the inventory section, not appended to the file: rows are parsed only between + # "## The inventory" and "## Limits", so appending at the end would test nothing. + phantom = text.replace( + "## Limits", + "| `scripts/does-not-exist.sh` — invented | `PINNED` | n/a |\n\n## Limits", 1) assert inventory_sites(phantom) - population == {"scripts/does-not-exist.sh"}, ( "a row naming a file that does not exist was not reported as phantom") @@ -187,7 +238,7 @@ def test_every_class_cell_comes_from_the_closed_vocabulary(): def test_every_unsafe_row_states_why_the_residual_is_accepted(): """`UNSAFE-KNOWN` means 'accepted with a reason', not 'noticed'. A row that records the window without the argument for tolerating it is how a deferral becomes permanent by default.""" - text = INVENTORY.read_text(encoding="utf-8") + text = _inventory_section(INVENTORY.read_text(encoding="utf-8")) thin = [] for line in text.splitlines(): # TABLE ROWS ONLY. The first version matched any line containing the token, so the prose in @@ -203,3 +254,45 @@ def test_every_unsafe_row_states_why_the_residual_is_accepted(): thin.append(site[:60]) assert not thin, ( f"UNSAFE-KNOWN row(s) with no stated justification: {thin}") + + +def test_the_population_never_includes_a_file_git_does_not_track(monkeypatch): + """The regression for the third population defect, and the reason the source is the index. + + `Path.rglob` enumerated `.husky/_/` — 17 husky shims generated by `npm ci`, gitignored and + untracked — so this guard was RED on every developer checkout and GREEN in CI, which never runs + `npm ci`. A guard that fails everywhere except where it runs trains its readers to ignore it. + + Asserted through the mechanism rather than against the current disk, so it holds on a machine + that has never installed husky: the tracked list is narrowed, and anything outside it must + disappear from the population even though it is still sitting on disk and still matches the + scope globs. + """ + real = derived_population() + assert real, "empty population — the derivation is broken, not the repo" + + victim = sorted(real)[0] + tracked = [p for p in _tracked_files() if p != victim] + monkeypatch.setattr( + "scripts.tests.test_remote_state_inventory._tracked_files", + lambda: tracked, + raising=False, + ) + # Patch the module object this test is running inside, whatever name it was imported under. + import sys + mod = sys.modules[__name__] + monkeypatch.setattr(mod, "_tracked_files", lambda: tracked) + + assert (REPO_ROOT / victim).is_file(), ( + f"{victim} must still exist on disk for this proof to mean anything") + assert victim not in derived_population(), ( + f"{victim} is on disk and matches the scope, but git no longer tracks it — it must not enter " + "the population, or untracked build output can redden this guard again") + + +def test_every_derived_member_is_tracked(): + """The same property stated as an invariant over the real tree, so a future refactor that goes + back to walking the filesystem fails here rather than on someone's laptop.""" + tracked = set(_tracked_files()) + stray = sorted(p for p in derived_population() if p not in tracked) + assert not stray, f"population contains untracked path(s): {stray}"