fix(622): make the exemption paging fail CLOSED; read statuses latest-per-context
review-verdict/h10 Awaiting review verdict for f6d01c4
Review verdict / Set review-verdict status (pull_request) Successful in 3s
PR Gates / CI image pin matches docker/ci (pull_request) Successful in 14s
PR Gates / Docs update reminder (pull_request) Successful in 15s
PR Gates / decisions lifecycle (pull_request) Successful in 22s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 7m59s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 10s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Successful in 7s
Build ErsatzTV Image / Functional E2E (curl + UI contracts) (pull_request) Successful in 16m9s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 20m51s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped

Cross-family re-review returned BLOCKED on the fix commit, correctly. Two of the
three findings were on the FAILURE path, which is why every happy-path run and
the whole first test suite looked fine.

1. (High/Medium) Both paging loops treated a failed or non-array page as a
   legitimate short final page: empty output counts as zero rows, zero rows reads
   as "end of list", and the enumeration completed from a PARTIAL list — failing
   OPEN at exactly the point the guard exists to fail closed, while the decision
   record claimed the opposite. Each page is now validated as a JSON array before
   its rows are counted; anything else withholds the exemption.

2. (High) The workflow's "is there already a verdict" pre-check read
   `/statuses/{sha}`, which returns one row per status POST rather than per
   context and pages at 50 — so a head with a few CI reruns can push a real
   verdict off the first page (this PR's head already carries 15 rows for 11
   contexts). Missing it there is not benign: the job would post `pending`, or an
   exemption `success`, OVER a human verdict. Both the workflow and the hook now
   read `/commits/{sha}/status` (latest-per-context), and the workflow refuses to
   post anything when that read fails rather than inferring "no verdict yet".
   Credit: raised independently by the parallel session on this issue.

3. (Low) The record claimed both callers withhold the exemption when enumeration
   cannot complete. True only after (1); the claim and the code now agree.

Adds scripts/tests/test_merge_consent_exemption.py — 9 tests over the hook's
exemption path via a curl shim, asserting behaviour when a page ERRORS or returns
a non-array body, not merely when it returns data. Mutation-proven: reverting the
array validation fails both failure-path tests; dropping `previous_filename`
fails the rename test.

One test I wrote was wrong and the run caught it: I asserted a
`.gitea/... -> docs/...` rename must break the hook's exemption, but that hook
deliberately exempts `.claude/`/`.gitea/`/`.husky/` too (to a human PROMPT, never
an auto-grant), so both sides legitimately match. The rename guard matters there
for a genuinely non-exempt source; the stricter PROTECTED semantics belong to the
workflow. Both cases are now pinned, including a positive control that a
docs->docs rename stays exempt.

Decisions-Edit: yes
This commit is contained in:
2026-07-25 22:04:18 +02:00
parent a9e3e23abf
commit f6d01c4924
4 changed files with 230 additions and 22 deletions
@@ -0,0 +1,160 @@
"""Tests for the docs-only exemption path in `.claude/hooks/pretooluse-merge-consent.sh` (#622).
This covers the *file-enumeration* half of the gate, which decides whether a PR skips the
Done-when/verdict checks entirely. Three defects lived here, all silent false negatives that
widened the exemption rather than narrowing it:
1. the list was read from a single `?limit=100` page, which Gitea caps at 50 — on PR #619 that
showed zero protected paths where the full enumeration finds ten;
2. only `.filename` was read, so a `git mv` of a protected file INTO `docs/` looked docs-only;
3. a mid-pagination transport failure produced an empty page, which counted as zero rows and
read as "end of list" — completing the enumeration from a PARTIAL list.
(3) is the one worth restating: it is a defect on the FAILURE path, so every happy-path run looked
correct. These tests therefore assert what happens when a page *errors*, not only when it returns.
Observable contract: the hook exits 0 with EMPTY stdout when the PR is exempt (it passes through to
normal permissioning), and emits a JSON `permissionDecision` when it is not. So "did the exemption
apply" is directly observable without stubbing the rest of the gate.
"""
from __future__ import annotations
import json
import os
import subprocess
from pathlib import Path
import pytest
REPO_ROOT = Path(__file__).resolve().parents[2]
HOOK = REPO_ROOT / ".claude" / "hooks" / "pretooluse-merge-consent.sh"
SHA = "a9e3e23abf337980ca4c05854f5b1e210099d08b"
# Serves paged `pulls/N/files`, plus the minimal PR object the hook reads first.
CURL_SHIM = r'''#!/usr/bin/env python3
import json, os, sys, pathlib, urllib.parse
state = pathlib.Path(os.environ["STUB_DIR"])
args = sys.argv[1:]
url = [a for a in args if a.startswith("http")][-1]
if "/pulls/" in url and "/files" in url:
q = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)
page = int(q.get("page", ["1"])[0])
pages = json.loads((state / "pages.json").read_text())
if page > len(pages):
print("[]"); sys.exit(0)
entry = pages[page - 1]
if entry == "ERROR": # transport failure on this page
sys.exit(22)
if entry == "GARBAGE": # 200 with a non-array body (proxy/error page)
print('{"message":"internal error"}'); sys.exit(0)
print(json.dumps(entry)); sys.exit(0)
if "/pulls/" in url:
print(json.dumps({"head": {"sha": os.environ["STUB_SHA"]}, "body": "no linked issue here"}))
sys.exit(0)
print("{}")
'''
def _rows(paths):
return [{"filename": p, "status": "modified"} for p in paths]
@pytest.fixture
def hook(tmp_path):
bindir = tmp_path / "bin"; bindir.mkdir()
shim = bindir / "curl"; shim.write_text(CURL_SHIM); shim.chmod(0o755)
state = tmp_path / "state"; state.mkdir()
env = dict(os.environ)
env["PATH"] = f"{bindir}{os.pathsep}{env['PATH']}"
env["STUB_DIR"] = str(state)
env["STUB_SHA"] = SHA
env["ETV_GITEA_TOKEN"] = "stub"
env["ETV_GITEA_URL"] = "http://gitea.example"
env.pop("ETV_GITEA_BASICAUTH", None)
class Handle:
def set_pages(self, *pages):
(state / "pages.json").write_text(json.dumps(list(pages)))
def run(self):
payload = {"tool_input": {"method": "merge", "owner": "timothy",
"repo": "ersatztv", "pull_number": 42}}
return subprocess.run(["bash", str(HOOK)], input=json.dumps(payload),
env=env, capture_output=True, text=True)
def exempted(self):
"""Exempt == passthrough == exit 0 with no decision JSON."""
r = self.run()
assert r.returncode == 0, r.stderr
return r.stdout.strip() == ""
return Handle()
def test_docs_only_pr_is_exempt(hook):
hook.set_pages(_rows(["docs/a.md", "docs/b.md", "README.md"]))
assert hook.exempted() is True
def test_code_pr_is_not_exempt(hook):
hook.set_pages(_rows(["docs/a.md", "ErsatzTV/Program.cs"]))
assert hook.exempted() is False
def test_protected_path_on_a_LATER_page_is_still_seen(hook):
"""The #619 shape: 50 docs files on page 1, code hiding on page 2."""
hook.set_pages(_rows([f"docs/f{i}.md" for i in range(50)]),
_rows(["scripts/decisions_lib.py"]))
assert hook.exempted() is False
def test_full_first_page_alone_does_not_end_enumeration(hook):
"""A full 50-row page must trigger a second fetch, not terminate the loop."""
hook.set_pages(_rows([f"docs/f{i}.md" for i in range(50)]),
_rows(["docs/tail.md"]))
assert hook.exempted() is True # genuinely all docs, but only provable by reading page 2
def test_rename_of_code_into_docs_is_not_exempt(hook):
"""`git mv ErsatzTV/Program.cs docs/note.md` — the code path lives only in previous_filename.
NOTE the source must be a path the hook does not already exempt. Its docs-only pattern
deliberately also covers `.claude/`/`.gitea/`/`.husky/` (process files exempt to a HUMAN
PROMPT, never to an auto-grant), so a rename between two exempt paths is correctly still
exempt. That is the hook's contract and differs from `review-verdict.yml`'s stricter
PROTECTED list, which must never auto-post a green status for those paths.
"""
hook.set_pages([{"filename": "docs/innocuous-note.md", "status": "renamed",
"previous_filename": "ErsatzTV/Program.cs"}])
assert hook.exempted() is False
def test_rename_between_two_exempt_paths_stays_exempt(hook):
"""Guards the above: reading previous_filename must not over-trigger on legitimate moves."""
hook.set_pages([{"filename": "docs/b.md", "status": "renamed",
"previous_filename": "docs/a.md"}])
assert hook.exempted() is True
def test_transport_failure_mid_pagination_withholds_the_exemption(hook):
"""The failure-path defect: an errored page must not read as 'end of list'."""
hook.set_pages(_rows([f"docs/f{i}.md" for i in range(50)]), "ERROR")
assert hook.exempted() is False
def test_non_array_body_mid_pagination_withholds_the_exemption(hook):
"""A 200 carrying an error object must not be treated as an empty final page."""
hook.set_pages(_rows([f"docs/f{i}.md" for i in range(50)]), "GARBAGE")
assert hook.exempted() is False
def test_first_page_failure_withholds_the_exemption(hook):
hook.set_pages("ERROR")
assert hook.exempted() is False