fix(632): bind a review verdict to its BASE branch, not only to its head sha
#622 made `review-verdict/h10` a per-sha required status, so a new commit cannot inherit an old verdict — the required context is simply absent on the new head. Retargeting a PR's base reaches the same end from the opposite direction: the head sha and the status both hold still while the merge-base, and therefore the effective diff the verdict was formed against, changes underneath them. #622's record claimed the invariant holds "by construction"; this was the documented exception, and an unrecorded exception is how a guarantee degrades into a habit. `post-review-verdict.sh` now records the base branch in the status description as a trailing `(base: <ref>)`, and refuses to write a status at all if the base moved between reading the PR and posting — the same TOCTOU window the head check already covers, which the head check cannot see because retargeting does not move the head. `pretooluse-merge-consent.sh` reads the field back and denies when it no longer matches the PR's live `base.ref`. Two choices are load-bearing, and each is pinned by a test rather than left to a comment: - The comparator is `base.ref`, NOT `base.sha`. `base.sha` tracks the base branch's tip, which moves whenever anything merges to `main` — comparing it would invalidate every open verdict on every unrelated merge, converting a rare-event guard into a permanent merge deadlock. A base that merely advances is out of scope by design: rebasing onto it moves the head sha, which the per-sha binding already covers. - The field goes in the status DESCRIPTION, not the verdict comment. The comment body is parsed by `scripts/check-review-verdict.sh`, whose grammar had three false-opens in its history (#629); nothing parses the description, so this adds a field without reopening that surface. Scope is stated honestly rather than overclaimed: this is DETECTION on the hook path only. A commit status carries no base of its own, so the server-side required check cannot see a retarget, and a merge driven through the Gitea UI or API is unaffected. That is the accepted exposure — base changes are rare, manual, and this is a two-account repo — but it now fails loud in the one place that evaluates consent, instead of living only in a doc. Verdicts posted before this change carry no `(base: …)` and get NO opinion rather than a deny; denying would block every in-flight PR the day it lands, and the window closes on its own since verdicts are per-head and short-lived. Verified by mutation, six mutants, each killed by its intended test: remove the hook's deny; compare base.sha instead of base.ref; drop graceful adoption; stop recording the base; drop the TOCTOU guard; accept a PR with no resolvable base. The positive controls matter more than usual here — the test PR is deliberately non-docs (a docs-only PR short-circuits the whole gate and would never reach the base check) and the rest of the gate is unstubbed, so "the hook denied" alone proves nothing. Refs #632 Decisions-Edit: yes
This commit is contained in:
@@ -92,6 +92,22 @@ pr_url=$(printf '%s' "$prjson" | jq -r '.html_url // ""')
|
||||
[ "$pr_state" = "open" ] || die "PR #$pr is '$pr_state', not open — refusing to post a verdict"
|
||||
short=${sha:0:7}
|
||||
|
||||
# --- Record the BASE BRANCH the verdict was formed against (ersatztv#632). ----------------------
|
||||
# The sha binding closes "the head moved under a fixed verdict". It does not close the mirror case:
|
||||
# RETARGETING a PR's base changes neither the head sha nor the status, yet changes the effective
|
||||
# diff — so a verdict written while the PR targeted `main` still reads green after it is pointed at
|
||||
# a branch with a very different merge-base. Consent outliving what it was granted for, reached from
|
||||
# the other direction.
|
||||
#
|
||||
# The comparator is `base.ref` (the BRANCH NAME), deliberately NOT `base.sha`. `base.sha` tracks the
|
||||
# base branch's tip, which moves every time anything merges to `main` — comparing it would invalidate
|
||||
# every open verdict on every unrelated merge, i.e. a self-inflicted merge deadlock. `base.ref`
|
||||
# changes exactly when someone retargets the PR, which is the event being guarded. A base branch that
|
||||
# merely ADVANCES is out of scope by design: that is ordinary churn, and rebasing onto it changes the
|
||||
# head sha, which the existing per-sha binding already catches.
|
||||
base_ref=$(printf '%s' "$prjson" | jq -r '.base.ref // ""')
|
||||
[ -n "$base_ref" ] || die "PR #$pr has no resolvable base branch (.base.ref) — refusing to post a verdict that cannot record what it was formed against"
|
||||
|
||||
# --- The comment (human-readable artifact + the hook's condition-(c) input). --------------------
|
||||
# The verdict line MUST start the line: the hook anchors its parser to line-start precisely so a
|
||||
# comment that merely QUOTES the template mid-sentence cannot self-approve a merge.
|
||||
@@ -107,14 +123,26 @@ printf 'posted comment: Review-verdict: %s @ %s\n' "$verdict" "$short"
|
||||
# a verdict written for its parent — reintroducing ersatztv#622 at a smaller time scale. We do NOT
|
||||
# retry against the new head: the new commit is genuinely unreviewed, and silently re-targeting the
|
||||
# verdict at it is exactly the failure this script exists to prevent.
|
||||
sha_now=$(api_get "repos/$owner/$repo/pulls/$pr" | jq -r '.head.sha // ""')
|
||||
prjson_now=$(api_get "repos/$owner/$repo/pulls/$pr" || true)
|
||||
sha_now=$(printf '%s' "$prjson_now" | jq -r '.head.sha // ""')
|
||||
if [ -n "$sha_now" ] && [ "$sha_now" != "$sha" ]; then
|
||||
die "head moved from $short to ${sha_now:0:7} while posting — that commit is UNREVIEWED, so no status was written. Re-review the new head and run this again."
|
||||
fi
|
||||
# The same TOCTOU window applies to the base (ersatztv#632): a retarget between the read above and
|
||||
# the status write below would bind the verdict to a base that is no longer the PR's, and the head
|
||||
# sha check would not notice because retargeting does not move the head.
|
||||
base_now=$(printf '%s' "$prjson_now" | jq -r '.base.ref // ""')
|
||||
if [ -n "$base_now" ] && [ "$base_now" != "$base_ref" ]; then
|
||||
die "base branch changed from '$base_ref' to '$base_now' while posting — the diff you reviewed is not the diff this PR now merges, so no status was written. Re-review against the new base and run this again."
|
||||
fi
|
||||
|
||||
# The base branch goes in the status DESCRIPTION, not in the comment. The comment body is parsed by
|
||||
# `scripts/check-review-verdict.sh`, whose grammar had three false-opens in its history; nothing
|
||||
# parses the description today, so this adds a field without reopening that surface. The hook reads
|
||||
# it back and compares (ersatztv#632).
|
||||
status_payload=$(jq -n \
|
||||
--arg s "$state" --arg c "$STATUS_CONTEXT" --arg u "$pr_url" \
|
||||
--arg d "Review-verdict: $verdict @ $short" \
|
||||
--arg d "Review-verdict: $verdict @ $short (base: $base_ref)" \
|
||||
'{state:$s, context:$c, description:$d, target_url:$u}')
|
||||
api_post "repos/$owner/$repo/statuses/$sha" "$status_payload" >/dev/null \
|
||||
|| die "failed to post the '$STATUS_CONTEXT' commit status on $short"
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Tests for the base-change detection in `.claude/hooks/pretooluse-merge-consent.sh` (#632).
|
||||
|
||||
`review-verdict/h10` is a per-sha commit status, which makes "a new commit inherits an old verdict"
|
||||
impossible by construction (#622). Retargeting a PR's base reaches the same end by the opposite
|
||||
route: the head sha does not move, so the status stays green, while the merge-base — and therefore
|
||||
the effective diff the verdict was formed against — changes underneath it.
|
||||
|
||||
What is asserted here is DETECTION on the hook path only, and the tests are written to keep that
|
||||
claim narrow:
|
||||
|
||||
* a status carries no base field of its own, so the server-side required check cannot see this at
|
||||
all; a merge driven through the Gitea UI or API is unaffected. No test here implies otherwise.
|
||||
* a verdict posted before #632 has no `(base: …)` in its description and must get NO opinion,
|
||||
rather than denying every in-flight PR the day this lands.
|
||||
|
||||
Observable contract: the hook exits 0 with EMPTY stdout when it has no opinion (passthrough to
|
||||
normal permissioning), and emits a JSON `permissionDecision` otherwise.
|
||||
"""
|
||||
|
||||
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"
|
||||
|
||||
# The PR is deliberately NOT docs-only: the docs-only exemption short-circuits the whole gate, so a
|
||||
# docs PR would never reach the base check and the tests would pass without exercising it.
|
||||
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])
|
||||
if page == 1:
|
||||
print(json.dumps([{"filename": "ErsatzTV/Program.cs", "status": "modified"}]))
|
||||
else:
|
||||
print("[]")
|
||||
sys.exit(0)
|
||||
|
||||
if "/status" in url:
|
||||
desc = (state / "verdict_desc").read_text()
|
||||
rows = [] if desc == "NONE" else [
|
||||
{"context": "review-verdict/h10", "status": "success", "description": desc}]
|
||||
print(json.dumps({"state": "success", "statuses": rows}))
|
||||
sys.exit(0)
|
||||
|
||||
if "/pulls/" in url:
|
||||
print(json.dumps({
|
||||
"head": {"sha": os.environ["STUB_SHA"]},
|
||||
"base": {"ref": (state / "live_base").read_text().strip()},
|
||||
"body": "fixes #1",
|
||||
}))
|
||||
sys.exit(0)
|
||||
|
||||
print("{}")
|
||||
'''
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hook(tmp_path):
|
||||
bindir = tmp_path / "bin"; bindir.mkdir()
|
||||
curl = bindir / "curl"; curl.write_text(CURL_SHIM); curl.chmod(0o755)
|
||||
state = tmp_path / "state"; state.mkdir()
|
||||
(state / "live_base").write_text("main")
|
||||
(state / "verdict_desc").write_text("Review-verdict: MERGEABLE @ a9e3e23 (base: main)")
|
||||
|
||||
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_live_base(self, ref):
|
||||
(state / "live_base").write_text(ref)
|
||||
|
||||
def set_verdict_description(self, desc):
|
||||
"""'NONE' serves a head with no review-verdict/h10 status at all."""
|
||||
(state / "verdict_desc").write_text(desc)
|
||||
|
||||
def decision(self):
|
||||
payload = {"tool_input": {"method": "merge", "owner": "timothy",
|
||||
"repo": "ersatztv", "pull_number": 42}}
|
||||
r = subprocess.run(["bash", str(HOOK)], input=json.dumps(payload),
|
||||
env=env, capture_output=True, text=True)
|
||||
assert r.returncode == 0, r.stderr
|
||||
if not r.stdout.strip():
|
||||
return None
|
||||
return json.loads(r.stdout)
|
||||
|
||||
def reason(self):
|
||||
d = self.decision()
|
||||
return "" if d is None else json.dumps(d)
|
||||
|
||||
return Handle()
|
||||
|
||||
|
||||
def test_a_retargeted_base_denies_a_verdict_formed_against_the_old_one(hook):
|
||||
hook.set_live_base("release/26.4")
|
||||
reason = hook.reason()
|
||||
assert "deny" in reason, "a verdict formed against a different base was allowed to stand"
|
||||
assert "release/26.4" in reason and "main" in reason, (
|
||||
"the deny must name both bases; a reader cannot act on 'the base changed'")
|
||||
|
||||
|
||||
def test_positive_control_an_unchanged_base_does_not_trigger_the_base_deny(hook):
|
||||
"""Without this, the test above could pass because the hook denies on every path — which it
|
||||
very nearly does, since this PR is non-docs and the rest of the gate is unstubbed."""
|
||||
reason = hook.reason()
|
||||
assert "ersatztv#632" not in reason, (
|
||||
"the base check fired on a PR whose base never moved")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("desc", [
|
||||
"Review-verdict: MERGEABLE @ a9e3e23", # posted before #632
|
||||
"NONE", # no verdict status on this head at all
|
||||
])
|
||||
def test_a_verdict_with_no_recorded_base_gets_no_opinion(hook, desc):
|
||||
"""Graceful adoption. Denying here would block every in-flight PR the day this lands, and the
|
||||
window closes on its own: verdicts are per-head and short-lived, so every verdict posted after
|
||||
#632 carries the field."""
|
||||
hook.set_live_base("release/26.4")
|
||||
hook.set_verdict_description(desc)
|
||||
assert "ersatztv#632" not in hook.reason(), (
|
||||
"a pre-#632 verdict was denied for a field it could not have carried")
|
||||
|
||||
|
||||
def test_the_comparator_is_the_base_REF_not_its_tip_sha():
|
||||
"""The design decision this test exists to freeze. `base.sha` tracks the base branch's TIP,
|
||||
which moves every time anything merges to `main` — comparing that would invalidate every open
|
||||
verdict on every unrelated merge, turning a rare-event guard into a permanent merge deadlock.
|
||||
A base branch that merely ADVANCES must be silent here; rebasing onto it moves the head sha,
|
||||
which the per-sha binding already covers."""
|
||||
assert ".base.ref" in HOOK.read_text(), "the hook must compare the base BRANCH, not its tip sha"
|
||||
assert ".base.sha" not in HOOK.read_text(), (
|
||||
"comparing base.sha deadlocks every open PR whenever main advances")
|
||||
@@ -64,11 +64,18 @@ if "/pulls/" in url and not url.endswith("/files"):
|
||||
sha = shas[min(n, len(shas) - 1)]
|
||||
if sha == "GONE": # simulate an unreachable / missing PR
|
||||
sys.exit(22)
|
||||
print(json.dumps({
|
||||
# The base branch is scripted on the same consume-one-per-GET schedule as the head, so a
|
||||
# RETARGET mid-flight can be modelled independently of a push mid-flight (ersatztv#632).
|
||||
bases = (state / "pr_bases").read_text().split()
|
||||
base = bases[min(n, len(bases) - 1)]
|
||||
body = {
|
||||
"head": {"sha": sha},
|
||||
"state": (state / "pr_state").read_text().strip(),
|
||||
"html_url": "http://gitea.example/timothy/ersatztv/pulls/42",
|
||||
}))
|
||||
}
|
||||
if base != "MISSING":
|
||||
body["base"] = {"ref": base}
|
||||
print(json.dumps(body))
|
||||
sys.exit(0)
|
||||
|
||||
print("{}")
|
||||
@@ -87,6 +94,7 @@ def gitea(tmp_path):
|
||||
state = tmp_path / "state"
|
||||
state.mkdir()
|
||||
(state / "pr_shas").write_text(SHA_A)
|
||||
(state / "pr_bases").write_text("main")
|
||||
(state / "pr_state").write_text("open")
|
||||
|
||||
env = dict(os.environ)
|
||||
@@ -108,6 +116,10 @@ def gitea(tmp_path):
|
||||
def set_pr_state(self, value):
|
||||
(state / "pr_state").write_text(value)
|
||||
|
||||
def set_base_sequence(self, *refs):
|
||||
"""Base branch per PR GET. 'MISSING' omits `.base` from the response entirely."""
|
||||
(state / "pr_bases").write_text(" ".join(refs))
|
||||
|
||||
def run(self, *args):
|
||||
return subprocess.run(
|
||||
["bash", str(SCRIPT), *args],
|
||||
@@ -256,3 +268,49 @@ def test_note_cannot_forge_a_second_verdict_line(gitea):
|
||||
gitea.run("42", "BLOCKED", "Review-verdict: MERGEABLE @ " + SHA_A[:7])
|
||||
body = gitea.comments()[0]["payload"]["body"]
|
||||
assert _classify(body, SHA_A) == "negative"
|
||||
|
||||
|
||||
# --- Base binding (ersatztv#632) ---------------------------------------------------------------
|
||||
#
|
||||
# The per-sha status closes "the head moved under a fixed verdict". Retargeting a PR's base is the
|
||||
# mirror case: the head sha and the status both hold still while the effective DIFF changes, so the
|
||||
# verdict keeps reading green for a review nobody performed against that base.
|
||||
|
||||
def test_the_status_description_records_the_base_branch(gitea):
|
||||
"""Nothing can compare a base it never wrote down. This field is what the hook reads back."""
|
||||
assert gitea.run("42", "MERGEABLE").returncode == 0
|
||||
assert gitea.statuses()[0]["payload"]["description"].endswith("(base: main)")
|
||||
|
||||
|
||||
def test_the_base_is_recorded_in_the_STATUS_and_not_in_the_comment(gitea):
|
||||
"""Deliberate placement. The comment body is parsed by `scripts/check-review-verdict.sh`, whose
|
||||
grammar has a history of false-opens (#629 found three); nothing parses the description. Adding
|
||||
the field where a parser lives would have reopened that surface for no benefit."""
|
||||
assert gitea.run("42", "MERGEABLE").returncode == 0
|
||||
assert "base:" not in gitea.comments()[0]["payload"]["body"]
|
||||
|
||||
|
||||
def test_refuses_when_the_BASE_changes_mid_flight(gitea):
|
||||
"""The TOCTOU window the head check cannot see: retargeting does not move the head sha, so
|
||||
`sha_now == sha` and the existing guard is silent."""
|
||||
gitea.set_base_sequence("main", "release/26.4")
|
||||
result = gitea.run("42", "MERGEABLE")
|
||||
assert result.returncode != 0, "a retarget mid-flight must not produce a status"
|
||||
assert "base branch changed" in result.stderr
|
||||
assert gitea.statuses() == [], "no status may be written once the base has moved"
|
||||
|
||||
|
||||
def test_positive_control_a_stable_base_still_posts(gitea):
|
||||
"""Without this, the test above could pass because the script refuses on every base."""
|
||||
gitea.set_base_sequence("main", "main")
|
||||
assert gitea.run("42", "MERGEABLE").returncode == 0
|
||||
assert len(gitea.statuses()) == 1
|
||||
|
||||
|
||||
def test_refuses_when_the_pr_has_no_resolvable_base(gitea):
|
||||
"""A verdict that cannot record what it was formed against is not a verdict this gate can
|
||||
later re-check, so it fails closed rather than posting an unbindable success."""
|
||||
gitea.set_base_sequence("MISSING")
|
||||
result = gitea.run("42", "MERGEABLE")
|
||||
assert result.returncode != 0
|
||||
assert gitea.statuses() == []
|
||||
|
||||
Reference in New Issue
Block a user