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
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:
@@ -94,13 +94,20 @@ body=$(printf '%s' "$prjson" | jq -r '.body // ""' 2>/dev/null || true)
|
||||
files=""; files_complete=no; page=1
|
||||
while [ "$page" -le 40 ]; do
|
||||
raw=$(gq "repos/$owner/$repo/pulls/$pr/files?limit=50&page=$page")
|
||||
# A transport/parse failure must not look like a legitimate short final page: `gq` returns empty
|
||||
# on any error, which counts as zero rows and would set files_complete=yes over a PARTIAL list —
|
||||
# failing OPEN into the exemption. Require a real JSON array before trusting the page.
|
||||
if ! printf '%s' "$raw" | jq -e 'type == "array"' >/dev/null 2>&1; then
|
||||
files_complete=no; break
|
||||
fi
|
||||
# BOTH sides of a rename: Gitea reports a `git mv` as ONE row whose `filename` is the DESTINATION,
|
||||
# with the source in `previous_filename`. Reading only `filename` would let a PR move code into
|
||||
# docs/ and claim the docs-only exemption. Page size is measured in ROWS, not paths.
|
||||
n=$(printf '%s' "$raw" | jq -r '.[].filename // empty' 2>/dev/null | grep -c . || true)
|
||||
chunk=$(printf '%s' "$raw" | jq -r '.[] | (.filename // empty), (.previous_filename // empty)' 2>/dev/null || true)
|
||||
# docs/ and claim the docs-only exemption. Page size is measured in ROWS, not paths — one renamed
|
||||
# row is one row but two paths.
|
||||
n=$(printf '%s' "$raw" | jq -r 'length')
|
||||
chunk=$(printf '%s' "$raw" | jq -r '.[] | (.filename // empty), (.previous_filename // empty)')
|
||||
[ -n "$chunk" ] && files=$(printf '%s\n%s' "$files" "$chunk")
|
||||
if [ "${n:-0}" -lt 50 ]; then files_complete=yes; break; fi
|
||||
if [ "$n" -lt 50 ]; then files_complete=yes; break; fi
|
||||
page=$((page + 1))
|
||||
done
|
||||
files=$(printf '%s\n' "$files" | grep -v '^$' || true)
|
||||
@@ -163,8 +170,15 @@ else
|
||||
# the server enforces, and only the latter survives a new push. Deny rather than ask: the remedy
|
||||
# is a single documented command, so there is nothing here for a human to adjudicate.
|
||||
[ -n "$sha" ] || decide ask "H6 merge gate: could not resolve PR #$pr head sha to check the review-verdict status. Verify the review covered the latest commit before scheduling an auto-merge."
|
||||
vstate=$(gq "repos/$owner/$repo/statuses/$sha?limit=100" \
|
||||
| jq -r '[.[] | select(.context == "review-verdict/h10")] | first | .status // ""' 2>/dev/null || true)
|
||||
# Read the COMBINED endpoint, not `/statuses/{sha}`: the latter returns one row per status POST
|
||||
# rather than per context and pages at 50, so a head with a few CI reruns can push the verdict off
|
||||
# the first page and read as absent — a confusing false deny. The combined endpoint returns
|
||||
# latest-per-context, which is exactly the question being asked.
|
||||
vjson=$(gq "repos/$owner/$repo/commits/$sha/status?limit=100")
|
||||
if ! 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."
|
||||
fi
|
||||
vstate=$(printf '%s' "$vjson" | jq -r '[.statuses[] | select(.context == "review-verdict/h10")] | first | .status // ""')
|
||||
case "$vstate" in
|
||||
success) : ;;
|
||||
"") decide deny "H6/H10 merge gate: BLOCKED — PR #$pr has no 'review-verdict/h10' commit status on head ${sha:0:7}, so scheduling an auto-merge would freeze consent at a head Gitea may not be the one to merge (ersatztv#622). Review the current head and run: scripts/post-review-verdict.sh $pr MERGEABLE" ;;
|
||||
|
||||
@@ -88,8 +88,22 @@ jobs:
|
||||
# A human/agent verdict for this exact head may already exist (the reviewer ran the
|
||||
# script before this workflow finished, or a rerun). Re-posting `pending` over it would
|
||||
# un-approve a reviewed head and stall the PR.
|
||||
existing=$(gh "$BASE_URL/repos/$REPO/statuses/$SHA?limit=100" \
|
||||
| jq -r --arg c "$CONTEXT" '[.[] | select(.context == $c)] | first | .status // ""' 2>/dev/null || true)
|
||||
#
|
||||
# Read the COMBINED endpoint, not `/statuses/{sha}`: the latter returns one row per
|
||||
# status POST (not per context) and pages at 50, so a head with a few CI reruns can push
|
||||
# an earlier verdict off the first page. Missing it here is NOT harmless — we would post
|
||||
# `pending` (or worse, an exemption `success`) over a real human verdict. The combined
|
||||
# endpoint returns latest-per-context, which is both what we mean and ~11 rows.
|
||||
#
|
||||
# An unreadable/unparseable response must NOT be read as "no verdict exists": fail the
|
||||
# job WITHOUT posting anything, so a transient API error can never overwrite a verdict.
|
||||
statusjson=$(gh "$BASE_URL/repos/$REPO/commits/$SHA/status?limit=100") || statusjson=""
|
||||
if ! printf '%s' "$statusjson" | jq -e '.statuses | type == "array"' >/dev/null 2>&1; then
|
||||
echo "::error::Could not read existing commit statuses for ${SHA:0:7}. Refusing to post anything rather than risk overwriting an existing verdict."
|
||||
exit 1
|
||||
fi
|
||||
existing=$(printf '%s' "$statusjson" \
|
||||
| jq -r --arg c "$CONTEXT" '[.statuses[] | select(.context == $c)] | first | .status // ""')
|
||||
if [ "$existing" = "success" ] || [ "$existing" = "failure" ]; then
|
||||
echo "${CONTEXT} is already '${existing}' on ${SHA:0:7} — leaving the existing verdict alone."
|
||||
exit 0
|
||||
@@ -107,17 +121,25 @@ jobs:
|
||||
page=1
|
||||
complete=no
|
||||
while [ "$page" -le "$MAX_PAGES" ]; do
|
||||
raw=$(gh "$BASE_URL/repos/$REPO/pulls/$PR/files?limit=${PAGE_SIZE}&page=${page}" || true)
|
||||
# BOTH sides of a rename. Gitea reports a `git mv` as ONE row with status=renamed,
|
||||
# `filename` = the DESTINATION and `previous_filename` = the source. Reading only
|
||||
# `filename` therefore lets a PR move a protected file INTO docs/ and be classified
|
||||
# docs-only: verified live — `.gitea/workflows/renovate.yml` -> `docs/innocuous-note.md`
|
||||
# showed no protected path at all. Counting rows (not paths) keeps the page-size test
|
||||
# honest, since one renamed row contributes two paths.
|
||||
n=$(printf '%s' "$raw" | jq -r '.[].filename // empty' 2>/dev/null | grep -c . || true)
|
||||
chunk=$(printf '%s' "$raw" | jq -r '.[] | (.filename // empty), (.previous_filename // empty)' 2>/dev/null || true)
|
||||
raw=$(gh "$BASE_URL/repos/$REPO/pulls/$PR/files?limit=${PAGE_SIZE}&page=${page}") || raw=""
|
||||
# A transport/parse failure must NOT masquerade as a legitimate short final page.
|
||||
# Empty output counts as zero rows, which would otherwise read as "end of list" and set
|
||||
# complete=yes over a PARTIAL enumeration — failing OPEN at the exact point this guard
|
||||
# exists to fail closed. Validate the response really is a JSON array before counting.
|
||||
if ! printf '%s' "$raw" | jq -e 'type == "array"' >/dev/null 2>&1; then
|
||||
complete=no; break
|
||||
fi
|
||||
# Page-size termination is measured in ROWS; the path set collects BOTH sides of a
|
||||
# rename. Gitea reports a `git mv` as ONE row whose `filename` is the DESTINATION, with
|
||||
# the source only in `previous_filename` — so reading `filename` alone lets a PR move a
|
||||
# protected file INTO docs/ and pass as docs-only (verified live:
|
||||
# `.gitea/workflows/renovate.yml` -> `docs/innocuous-note.md` showed no protected path).
|
||||
# One renamed row thus contributes ONE to `n` and TWO to the path set, which is why
|
||||
# these two counts are deliberately computed differently.
|
||||
n=$(printf '%s' "$raw" | jq -r 'length')
|
||||
chunk=$(printf '%s' "$raw" | jq -r '.[] | (.filename // empty), (.previous_filename // empty)')
|
||||
[ -n "$chunk" ] && files=$(printf '%s\n%s' "$files" "$chunk")
|
||||
if [ "${n:-0}" -lt "$PAGE_SIZE" ]; then complete=yes; break; fi
|
||||
if [ "$n" -lt "$PAGE_SIZE" ]; then complete=yes; break; fi
|
||||
page=$((page + 1))
|
||||
done
|
||||
files=$(printf '%s\n' "$files" | grep -v '^$' || true)
|
||||
|
||||
@@ -102,10 +102,22 @@ described as one:
|
||||
workflow and the hook now read **both** sides. Noting the near-miss: an initial check against #619
|
||||
suggested Gitea exposed no rename data at all, which was a false negative — that PR simply contained
|
||||
no renames. A constructed positive case settled it; an arbitrary sample did not.
|
||||
2. **The file list must be paged.** The endpoint caps at 50 rows and silently ignores a larger `limit`
|
||||
(PR #619: 194 changed files, `?limit=100` returns 50). A single-page read is a silent false negative —
|
||||
on #619 it saw **zero** protected paths where the full enumeration finds ten. Both call sites now page
|
||||
to exhaustion and withhold the exemption if they cannot.
|
||||
2. **The file list must be paged, and the paging must fail closed.** The endpoint caps at 50 rows and
|
||||
silently ignores a larger `limit` (PR #619: 194 changed files, `?limit=100` returns 50). A
|
||||
single-page read is a silent false negative — on #619 it saw **zero** protected paths where the full
|
||||
enumeration finds ten. Both call sites now page to exhaustion. Critically, each page is validated as
|
||||
a JSON array *before* its rows are counted: an errored or non-array page yields zero rows, which
|
||||
would otherwise read as "end of list" and complete the enumeration from a **partial** list — failing
|
||||
open at precisely the point the guard exists to fail closed. That defect lives only on the failure
|
||||
path, so every happy-path run looked correct; it is covered by tests that error a page mid-pagination
|
||||
rather than only by tests that return data.
|
||||
|
||||
2b. **Status reads use the combined endpoint.** `GET /statuses/{sha}` returns one row per status *post*
|
||||
(not per context) and pages at 50, so a head with a few CI reruns can push an earlier verdict off the
|
||||
first page. In the hook that would be a confusing false deny; in the workflow it would be worse — it
|
||||
would post `pending` (or an exemption `success`) **over** a real human verdict. Both now read
|
||||
`GET /commits/{sha}/status`, which returns latest-per-context, and the workflow refuses to post
|
||||
anything at all when that read fails or is unparseable, rather than treating it as "no verdict yet".
|
||||
3. **Changing a PR's base does not change its head sha**, so a verdict status keeps applying to a diff
|
||||
that has materially changed. Not currently handled; low exposure here because base changes are rare
|
||||
and manual.
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user