From 8e02b9961ddf932329f401ff447414484a4c4e54 Mon Sep 17 00:00:00 2001 From: Timothy Date: Sun, 16 Aug 2026 14:15:24 +0200 Subject: [PATCH] =?UTF-8?q?fix(778):=20round=203=20=E2=80=94=20fix=20the?= =?UTF-8?q?=20overclaim=20I=20left=20in=20the=20code,=20and=20defer=20the?= =?UTF-8?q?=20pre-existing=20ones=20to=20#803?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fourth cold review: no Blockers, 2 High / 2 Medium / 2 Low. It independently re-derived the population (59 files, 59 sites, 69 rows, 3 PINNED) and verified every numeric and factual claim in the diff, including the corrected confinement rationale. THE ONE THAT STINGS. The grant reason string still said a commit pushed before Gitea merges "will clear it and block the merge" — the exact sentence the new decision record quotes as THE overclaim this issue exists to remove. I documented it in three files and left it in the code a human actually reads. It now states the guarantee and its condition: the required check was confirmed rather than assumed, and it holds while that branch protection stands. FIXED HERE (all in files this PR already touches): - enable_status_check is validated as a BOOLEAN. `"true"` is not `true`, and comparing the string to `true` produced a confident deny from a payload never understood — the tri-state collapsing to two, the same defect as the contexts shape one line down. - `.statuses` members are validated, not just the array (see the honest caveat below). - the docs-reminder N/A rationale said "the job cannot fail and never reaches the combined status", which is false — any job's status joins the combined state. The true, narrower reason is that its fetch and diff are failure-swallowed, so the remote read can only change the warning's wording. - docs/README names the scripts/tests exclusion in BOTH statements. A VACUOUS TEST, CAUGHT BY ITS OWN MUTATION PROOF. The regression case for the `.statuses` member validation stays GREEN against the predecessor: the #632 base-retarget block runs first and already validates every member it consumes, so it catches the payload before the scheduled branch is reached. The two guards overlap — duplicate guards masking each other, again — which makes that finding LATENT, not live, and my added clause defence-in-depth rather than a fix. The test now asserts the observable contract (a decision is always emitted) and says plainly that it is not a mutation proof of the newer clause. Shipping it as one would have been the exact grade inflation round 2 rejected. DEFERRED to #803, with the reason stated rather than implied: a head-ABA (force-push H1 -> H2 -> H1 during pagination) defeats pr-changed-files.sh, and three OLDER contracts still assert more than the new inventory rows do. That residual predates #778 and lives in #707's mechanism; correcting another active decision record inside a PR already at four review rounds is how a scoped change stops being reviewable. The inventory rows are accurate today and now point at #803. refs #778 Co-Authored-By: Claude Opus 5 (1M context) --- .claude/hooks/pretooluse-merge-consent.sh | 24 ++++++++-- docs/README.md | 11 ++--- docs/remote-state-inventory.md | 4 +- .../test_merge_consent_required_check.py | 45 +++++++++++++++++++ 4 files changed, 73 insertions(+), 11 deletions(-) diff --git a/.claude/hooks/pretooluse-merge-consent.sh b/.claude/hooks/pretooluse-merge-consent.sh index f2063883b..f3744fb03 100755 --- a/.claude/hooks/pretooluse-merge-consent.sh +++ b/.claude/hooks/pretooluse-merge-consent.sh @@ -312,8 +312,19 @@ else # status decide this. Here the fallthrough happens to land on `vstate=""` -> deny (fail-CLOSED, # so this was never a hole), but it would have surfaced the wrong message — a "BLOCKED, no # verdict" deny instead of the "could not read the status" ask this branch exists to give. - if [ -z "${vjson//[[:space:]]/}" ] || ! printf '%s' "$vjson" | jq -e '.statuses | type == "array"' >/dev/null 2>&1; then - decide ask "H6/H10 merge gate: could not read the 'review-verdict/h10' status for PR #$pr head ${sha:0:7} (Gitea unreachable or an unexpected response). Confirm the current head is reviewed before scheduling an auto-merge." + # Validate the MEMBERS, not just the array. `.statuses | type == "array"` passes for + # `{"statuses":[1]}`, and the extraction below then errors with "Cannot index number with string" + # and exits 5 — which, under `set -e`, aborts this hook with NO JSON on stdout at all. A consent + # hook that emits nothing has violated its own contract: it neither grants, denies nor asks. Same + # one-level-down swallow as the #632 base-change guard and the branch-protection shape check + # below; the validation domain must match the CONSUMPTION domain (ersatztv#778). + if [ -z "${vjson//[[:space:]]/}" ] \ + || ! printf '%s' "$vjson" \ + | jq -e '(.statuses | type == "array") + and all(.statuses[]; type == "object" + and ((.context | type) == "string") + and ((.status | type) == "string"))' >/dev/null 2>&1; then + decide ask "H6/H10 merge gate: could not read the 'review-verdict/h10' status for PR #$pr head ${sha:0:7} (Gitea unreachable, or a response whose status rows are not the expected shape). Confirm the current head is reviewed before scheduling an auto-merge." fi vstate=$(printf '%s' "$vjson" | jq -r '[.statuses[] | select(.context == "review-verdict/h10")] | first | .status // ""') case "$vstate" in @@ -388,10 +399,15 @@ else # So `"status_check_contexts": false` — a malformed shape — became `[]` and answered "no", i.e. a # confident DENY derived from a payload that was never understood. Absent and null are defaulted # explicitly; every other non-array is "unknown". + # `enable_status_check` is validated as a BOOLEAN before it is trusted, for the same reason the + # contexts list is: `"true"` (the string) is not `true`, and comparing it to `true` yields a + # confident "no" -> deny derived from a payload never understood. Every malformed shape on this + # endpoint has to reach the same "unknown" -> ask arm, or the tri-state is only two states. guarded=$(printf '%s' "$bp" \ | jq -r 'def ctxs: if (has("status_check_contexts") | not) or .status_check_contexts == null then [] else .status_check_contexts end; - if (ctxs | type) != "array" or any(ctxs[]; type != "string") then "unknown" + if (.enable_status_check | type) != "boolean" then "unknown" + elif (ctxs | type) != "array" or any(ctxs[]; type != "string") then "unknown" elif (.enable_status_check == true) and any(ctxs[]; . == "review-verdict/h10") then "yes" else "no" end' 2>/dev/null || true) case "$guarded" in @@ -453,7 +469,7 @@ if [ "$class" = "positive" ]; then # path this hook never read the CI status at all (it is delegated to Gitea), so saying "CI green" # there was a plain falsehood in the one message a human reads to decide whether to trust the gate. if [ "$mwcs" = "true" ]; then - decide grant "H6/H10 merge gate: satisfied — all Done-when boxes ticked, and both a positive Review-verdict comment and the 'review-verdict/h10' status cover the current head ($short). CI is gated by Gitea (merge_when_checks_succeed), and because the verdict status is bound to this sha, a commit pushed before Gitea merges will clear it and block the merge (ersatztv#622). Auto-granted." + decide grant "H6/H10 merge gate: satisfied — all Done-when boxes ticked, and both a positive Review-verdict comment and the 'review-verdict/h10' status cover the current head ($short). CI is gated by Gitea (merge_when_checks_succeed). A commit pushed before Gitea merges clears the sha-bound verdict status and is blocked by the 'review-verdict/h10' required check (ersatztv#622) — which this hook has just CONFIRMED is still required on '$base_ref' rather than assuming it. That guarantee holds while that branch protection stands; if it is weakened after this check, nothing here would see it (ersatztv#778). Auto-granted." fi decide grant "H6/H10 merge gate: satisfied — CI green, all Done-when boxes ticked, and a positive Review-verdict references the current head ($short). Auto-granted (no separate confirmation needed)." fi diff --git a/docs/README.md b/docs/README.md index 946158df5..17cbd3724 100644 --- a/docs/README.md +++ b/docs/README.md @@ -26,7 +26,7 @@ doc below, or that changes which sections a task signal points to.** | CI / release pipeline work | `docs/ci-cd.md` + `docs/decisions/release-ci-governance.md` | | Proposing a new guard / CI check / regression test convention | `docs/defect-shapes-773.md` §4 (detector menu + the classes where no detector is plausible), then the two rules every guard must satisfy: `docs/decisions/records/testing/guard-derives-population-from-source.md` and `…/guard-ships-with-mutation-proof.md` | | Adding / changing / deleting a guard file | `docs/guard-inventory.md` — every guard's row is machine-checked by `scripts/tests/test_guard_inventory.py`, so a new guard must acquire a row before the suite goes green | -| Writing code that reads live Gitea/remote state and then acts on it | `docs/decisions/records/process/check-and-use-pins-a-version.md`, then `docs/remote-state-inventory.md` — a new executable that talks to a remote service must acquire a row there before `scripts/tests/test_remote_state_inventory.py` goes green | +| Writing code that reads live Gitea/remote state and then acts on it | `docs/decisions/records/process/check-and-use-pins-a-version.md`, then `docs/remote-state-inventory.md` — a new executable under `scripts/` (**excluding `scripts/tests/`**), `.claude/hooks/`, `.husky/` or `.gitea/workflows/` must acquire a row there before `scripts/tests/test_remote_state_inventory.py` goes green | | Finding every site that references a symbol (multi-site fix/sweep) | `docs/local-lsp-tooling.md` — which surface answers, and why a delegated agent must be pointed at the `csharp-lsp` MCP tools rather than the `LSP` tool | | Live local run / Playwright-MCP verification | `docs/e2e-local.md` + `scripts/e2e-local.sh` | | Adding/changing a UI-E2E browser flow | `docs/e2e-local.md` → "UI-E2E harness" + `scripts/e2e-ui.sh` | @@ -113,10 +113,11 @@ bounds, what's mined per issue): `docs/handoffs/chicorytv-issue-queue.md` → "K and an audit of which configured hooks/MCP servers/LSPs are actually invoked. Read it before proposing a new guard or CI check — §4 is the detector menu, and it argues against enumerating cases one incident at a time. -- **`docs/remote-state-inventory.md`** — every executable **in `scripts/`, `.claude/hooks/`, - `.husky/` and `.gitea/workflows/`** that reads live remote state and acts on that read, classified - `PINNED` / `CAS` / `UNSAFE-KNOWN` / `N/A` with the window and what bounds it. Code outside those - four directories is out of scope and the doc says so. +- **`docs/remote-state-inventory.md`** — every executable in `scripts/` (**excluding + `scripts/tests/`**), `.claude/hooks/`, `.husky/` and `.gitea/workflows/` that reads live remote + state and acts on that read, classified `PINNED` / `CAS` / `UNSAFE-KNOWN` / `N/A` with the window + and what bounds it. Code outside those directories — C#/TypeScript guards, `web/`, and the test + suites themselves — is out of scope, and the doc states that rather than implying coverage. The population is derived from the filesystem and compared for set equality by `scripts/tests/test_remote_state_inventory.py`, so a new script that talks to a remote service cannot ship unclassified. Read it with `process.check-and-use-pins-a-version`; it is that record's diff --git a/docs/remote-state-inventory.md b/docs/remote-state-inventory.md index d45c94fbd..9182b6d52 100644 --- a/docs/remote-state-inventory.md +++ b/docs/remote-state-inventory.md @@ -78,7 +78,7 @@ classifications differ; otherwise the strictest applies and the Note names the e | Site | Class | Note | |---|---|---| | `scripts/post-review-verdict.sh` — commit-status write | `PINNED` | Re-reads the PR and compares **both** `.head.sha` and `.base.ref` immediately before the POST, and `die`s (exit 1, no status written) on a mismatch **or on a field it cannot read**. That last clause is new: both comparisons were guarded by `[ -n "$x" ] &&`, so a well-formed 2xx body that merely omitted the field made the check a no-op and the status was posted having confirmed nothing — found by cold review on #778 and regression-tested against the real predecessor, since the redundant `-z` arm alone mutates green. Closes #706 and #632 for this path by read-compare-refuse, not by CAS: Gitea's status API offers no conditional write. Residual: the **comment** is posted *before* the re-read, so a head that moves in between leaves a verdict comment with no status — the comment is not the gate, but the mismatch is confusing and is tracked in **#792**. | -| `scripts/pr-changed-files.sh` — paged file enumeration | `UNSAFE-KNOWN` | #707's fix, graded honestly after cold review: `.base.ref`, `.base.sha` and `.head.sha` are captured before paging and re-checked after, and any *observed* movement fails the whole enumeration closed rather than emitting a short list. But before-and-after equality is **ABA-vulnerable** — a `main → scratch → main` retarget during paging can return the same ref and, if nothing merged meanwhile, the same base sha, while the pages in between were diffed against the scratch base. The script's own comment says it narrows rather than erases; this row previously said "any movement fails", which was stronger than the code. Accepted here because the enumerator cannot close it alone, but be exact about what the caller-side fence does and does not cover: `ci.verdict-write-retarget-fence` counts `change_target_branch` events, so it catches the BASE alias and **nothing else**. A HEAD alias is not covered by anything — a force-push `H1 -> H2 -> H1` during pagination leaves the final `.head.sha` comparison equal while the middle pages were enumerated against `H2`, and no counter moves. That residual is real, unfenced, and stated here rather than papered over; closing it needs a monotonic head-mutation fence or enumeration bound to an immutable tree, neither of which exists today. | +| `scripts/pr-changed-files.sh` — paged file enumeration | `UNSAFE-KNOWN` | #707's fix, graded honestly after cold review: `.base.ref`, `.base.sha` and `.head.sha` are captured before paging and re-checked after, and any *observed* movement fails the whole enumeration closed rather than emitting a short list. But before-and-after equality is **ABA-vulnerable** — a `main → scratch → main` retarget during paging can return the same ref and, if nothing merged meanwhile, the same base sha, while the pages in between were diffed against the scratch base. The script's own comment says it narrows rather than erases; this row previously said "any movement fails", which was stronger than the code. Accepted here because the enumerator cannot close it alone, but be exact about what the caller-side fence does and does not cover: `ci.verdict-write-retarget-fence` counts `change_target_branch` events, so it catches the BASE alias and **nothing else**. A HEAD alias is not covered by anything — a force-push `H1 -> H2 -> H1` during pagination leaves the final `.head.sha` comparison equal while the middle pages were enumerated against `H2`, and no counter moves. That residual is real, unfenced, and stated here rather than papered over; closing it needs a monotonic head-mutation fence or enumeration bound to an immutable tree, neither of which exists today — tracked in **#803**, which also carries the three older contracts that still assert more than this row does. | | `scripts/select-queue.sh` — issue list, then per-issue `/dependencies` | `UNSAFE-KNOWN` | The open-issue list (labels, milestone, priority) is snapshotted once; per-candidate dependency reads happen seconds later and never re-read the issue's own labels, so an issue claimed `in-progress` in that gap still appears on the shortlist. Accepted: the script authorizes **no write**. The real gate is the four-way claim check in `process.parallel-session-claim`, which runs after selection and re-reads live state by construction. Tightening this would move a check that must be adversarial into a tool that is advisory. | | `scripts/ci-detect-already-validated.sh` — prior-head combined status | `UNSAFE-KNOWN` | Reads the PR head's status and emits `skip=true`, with nothing re-checking before the consuming job runs. Accepted and narrow: the skip elides only **re-running** test/migrations on a tree already validated; the `build` job still builds and pushes unconditionally, so no image ever ships from unvalidated source. | | `scripts/issue-qualification-audit.sh` | `N/A` | Pure read-and-report; exits 0/1 with a list. Authorizes no write and no merge. | @@ -129,7 +129,7 @@ classifications differ; otherwise the strictest applies and the Note names the e | `.gitea/workflows/ci-image.yml` — verify the pushed image | `UNSAFE-KNOWN` | Pulls back the `:` tag it pushed in the immediately preceding step. Same demotion and same reason as the two rows above: a registry tag is not a digest, and anything able to write to the registry can repoint it between the push and the verify, which would make the verification confirm an image other than the one built. Accepted on the same terms — the exposure requires registry write access, i.e. an actor already inside the trust boundary — and the same fix applies. | | `.gitea/workflows/pr-checks.yml` — `prove-fix` | `PINNED` | `base`/`head` are full shas from the event payload, immune to later PR mutation. | | `.gitea/workflows/pr-checks.yml` — `ci-image-pin` | `N/A` | A purely local comparison — `git log` over the checked-out tree against a literal in `docker-build.yml`. It never queries the registry, which is exactly why it cannot bound the retagging the image rows above describe. | -| `.gitea/workflows/pr-checks.yml` — `docs-reminder` base fetch | `N/A` | Fetches the live base tip, but the result only selects the text of a non-blocking warning: the job cannot fail and never reaches the combined status. It reads remote state and draws no authorization from it, which is this file's second `N/A` clause. Grouping it with `decisions-guard` over-demoted it, and the two have different classifications, so per the rule above they get separate rows. | +| `.gitea/workflows/pr-checks.yml` — `docs-reminder` base fetch | `N/A` | Fetches the live base tip, but the result only selects the text of a non-blocking warning. The rationale has to be narrower than the first draft's "the job cannot fail and never reaches the combined status", which is false — any job's status joins the combined state, and runner or checkout failure can redden it. What is true, and is what earns the `N/A`: the fetch and diff are failure-swallowed, so the remote read cannot change this job's outcome, only the warning's wording. It draws no authorization from what it reads, this file's second `N/A` clause. Grouping it with `decisions-guard` over-demoted it, and the two have different classifications, so per the rule above they get separate rows. | | `.gitea/workflows/pr-checks.yml` — `decisions-guard` base fetch | `UNSAFE-KNOWN` | Fetches the live base tip and diffs against it, unpinned, and unlike `docs-reminder` this job CAN fail — so its answer reaches the combined status the merge hook reads and therefore participates in consent. Accepted on the same grounds as the `api-docs`/`format` row: a base that moved mid-job produces a spurious FAILURE and a re-run, never a spurious pass, and it re-fetches fresh on every trigger with no state carried between runs. | | `.gitea/workflows/renovate.yml` — `renovate/renovate:43` | `N/A` | Out of this class, in scope for a different one — see the limits below. | | `.gitea/workflows/dependency-scan.yml` — NuGet advisory query | `N/A` | `dotnet list package --vulnerable` queries a live advisory database and fails the job on the report marker in the same step, so there is no check-then-act split. Worth one line anyway: a green here means "no advisories **as of this run**", which is a dated claim about mutable remote data rather than a property of the tree — which is why the scan runs on a weekly schedule instead of only on PRs. | diff --git a/scripts/tests/test_merge_consent_required_check.py b/scripts/tests/test_merge_consent_required_check.py index 11ce19740..b48802e30 100644 --- a/scripts/tests/test_merge_consent_required_check.py +++ b/scripts/tests/test_merge_consent_required_check.py @@ -86,6 +86,9 @@ if "/branch_protections/" in url: # string is substring search, so the naive membership test answers "yes" here. respond('{"enable_status_check": true,' ' "status_check_contexts": "prefix-review-verdict/h10-suffix"}') + if mode == "STRING-ENABLE": + respond('{"enable_status_check": "true",' + ' "status_check_contexts": ["review-verdict/h10"]}') if mode == "FALSE-CONTEXTS": # jq's `//` alternative fires on FALSE as well as null, so `// []` silently turned this # malformed shape into an empty list and produced a confident deny. @@ -121,6 +124,12 @@ if "/pulls/" in url and "/files" in url: 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 + # with no JSON at all. + if (state / "bp").read_text().strip() == "SCALAR-STATUS-ROW": + print('{"state":"success","statuses":[1]}') + sys.exit(0) print(json.dumps({"state": "success", "statuses": [ {"context": "review-verdict/h10", "status": "success", "description": "Review-verdict: MERGEABLE @ %s (base: main)" % os.environ["STUB_SHORT"]}]})) @@ -349,3 +358,39 @@ def test_an_IMMEDIATE_merge_is_not_subjected_to_this_check(hook): reason = hook.reason(scheduled=False) assert "NOT a required status check" not in reason, ( "the required-check deny fired on an immediate merge, which has no post-scheduling window") + + +def test_a_NON_BOOLEAN_enable_status_check_asks(hook): + """`"true"` is not `true`. Comparing the string to `true` yields a confident "no" -> deny from a + payload never understood, which collapses the documented tri-state into two states. Every + malformed shape on this endpoint has to reach the same ask arm.""" + hook.set_branch_protection("STRING-ENABLE") + reason = hook.reason() + assert "ask" in reason, "a string enable_status_check produced a decision instead of a question" + assert "NOT a required status check" not in reason + + +def test_a_SCALAR_status_row_asks_instead_of_killing_the_hook(hook): + """The consent hook's contract is that it always emits exactly one of grant/deny/ask, and + `{"statuses":[1]}` is the payload that can break it: it passes an `.statuses | type == "array"` + check, after which indexing a number errors and exits 5, which under `set -e` aborts the hook + with NO JSON at all. A gate that emits nothing has not failed closed; it has failed to decide. + + WHAT THIS TEST DOES *NOT* PROVE, stated because the mutation showed it. Restoring the + scheduled-branch validation to its predecessor leaves this test GREEN, because the #632 + base-retarget block runs FIRST and already validates every member it consumes — so it catches + this payload and asks before the scheduled branch is ever reached. The two guards overlap, which + is the masking shape `duplicate guards mask each other` describes, and it means the member + validation added to the scheduled branch is DEFENCE IN DEPTH against a reordering or a removal + of the earlier block, not a fix for a reachable live defect. + + So this asserts the OBSERVABLE contract — a decision is always emitted for this payload — which + is true and worth pinning whichever guard supplies it. It is deliberately not offered as a + mutation proof of the newer clause, because it is not one. + """ + hook.set_branch_protection("SCALAR-STATUS-ROW") + decision = hook.decision() + assert decision is not None, ( + "the hook emitted no decision at all for a malformed statuses payload — it neither granted, " + "denied nor asked") + assert decision["hookSpecificOutput"]["permissionDecision"] == "ask"