fix(622): bind H10 merge consent to the reviewed sha via a required commit status
review-verdict/h10 Awaiting review verdict for 628ae46
Review verdict / Set review-verdict status (pull_request) Successful in 9s
PR Gates / CI image pin matches docker/ci (pull_request) Successful in 11s
PR Gates / Docs update reminder (pull_request) Successful in 15s
PR Gates / decisions lifecycle (pull_request) Successful in 26s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Failing after 1m28s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 9s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Successful in 7s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 16m59s
Build ErsatzTV Image / Functional E2E (curl + UI contracts) (pull_request) Successful in 19m5s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped

`pretooluse-merge-consent.sh` proves all three consent conditions at the moment
the merge tool is called. With `merge_when_checks_succeed=true`, condition (a) is
delegated to Gitea, which then merges whatever head is green at ITS merge time —
while (b) Done-when and (c) the head-referencing verdict were proven against the
head at SCHEDULING time. Every commit pushed in between merges unreviewed. The
gate is not bypassed; it is satisfied against a snapshot that stops being true.

Demonstrated as a controlled A/B rather than inferred, with a CI check left
pending so Gitea waits as it really does:

  without a required verdict context: unreviewed commit B MERGED
  with it:                            same sequence REFUSED
  after reviewing B and posting it:   merges — blocked, not deadlocked

NOTE the anecdote in #622 is wrong and is corrected in the docs rather than
repeated: PR #619 does carry `Review-verdict: MERGEABLE @ 02c82b35`, posted six
seconds before the merge, explicitly re-reviewing the follow-up commits. #622 was
filed off a lagging API read. The hole is real regardless, and structural —
nothing FORCED that re-review inside the window Gitea would have merged in. This
turns a property that held by diligence into one that holds by construction.

The fix is the sha, not a smarter check. A Gitea commit status belongs to exactly
one commit, so a status written for a parent cannot be inherited by a child that
did not exist yet. `review-verdict/h10` becomes a REQUIRED status check on main:
push a new head and the context is simply absent, which Gitea reads as
not-passing (verified against 1.25.4: missing AND pending both block, and
auto-merge re-checks the current head). It also covers merge paths the hook never
sees — Gitea UI, raw API, another agent's session.

- scripts/post-review-verdict.sh writes the comment and the status together so
  they cannot drift, and re-reads head after commenting: if a commit landed
  mid-flight it writes NO status and exits non-zero rather than retargeting the
  verdict at a commit nobody read.
- .gitea/workflows/review-verdict.yml auto-passes the two exempt classes that
  would otherwise deadlock — Renovate-authored (platformAutomerge) and docs-only
  — and marks everything else pending. Exemptions are void when the PR touches
  .claude/, .gitea/, .husky/, scripts/ or docker/ci/.
- The hook refuses to SCHEDULE an auto-merge unless that status is green on head,
  and no longer claims "CI green" on the mwcs path, where it never read CI.

Two silent false negatives in the exemption path, both found by verifying rather
than reasoning, both fixed at BOTH call sites (workflow and the hook's
pre-existing docs-only carve-out):

- The files endpoint caps at 50 rows and IGNORES a larger `limit` — PR #619 has
  194 changed files and `?limit=100` returns 50. A single page saw ZERO protected
  paths there where the full enumeration finds ten. Both now page to exhaustion
  and withhold the exemption if they cannot complete.
- A rename is ONE row whose `filename` is the destination, the source only in
  `previous_filename`. Verified live: `.gitea/workflows/renovate.yml` ->
  `docs/innocuous-note.md` presented as docs-only with no protected path visible.
  Both now read BOTH sides.

Limits are documented, not papered over: base changes leave the head sha (and so
the verdict) unchanged, and a PR editing the workflow is judged by its own edited
copy — so PROTECTED is a guardrail against accident, not a tamper-proof control.

fixes #622
This commit is contained in:
2026-07-25 21:51:02 +02:00
parent 8e84191a03
commit 628ae46f7f
9 changed files with 789 additions and 9 deletions
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env bash
# post-review-verdict.sh — post an H10 review verdict as BOTH a PR comment and a per-sha commit
# status, so merge consent is bound to the exact commit that was reviewed (ersatztv#622).
#
# WHY THIS EXISTS. `pretooluse-merge-consent.sh` evaluates all three consent conditions at the
# moment the merge tool is called. When that call passes `merge_when_checks_succeed=true`, condition
# (a) is deliberately delegated to Gitea — but Gitea then merges whatever head is green at ITS merge
# time, which may be several commits past the head that conditions (b) and (c) were proven against.
# The gate reports satisfied and the newest code merges with no review verdict covering it. That is
# not a bypass: the gate is *satisfied against a snapshot that stops being true* (ersatztv#622).
# Shown by a controlled A/B: with a slow CI check still pending so Gitea waits, a commit pushed after
# scheduling MERGED unreviewed without the required verdict context, and was REFUSED with it.
#
# THE FIX IS THE SHA, NOT THE SCRIPT. A Gitea commit status is attached to ONE sha. Making
# `review-verdict/h10` a REQUIRED status check on `main` therefore makes the H10 invariant
# self-invalidating by construction: push a new commit and the new head simply has no such status,
# so Gitea's own auto-merge refuses to fire until someone re-reviews THAT head and posts a fresh
# verdict. No re-evaluation hook, no polling, no snapshot to go stale — a status cannot be inherited
# by a commit that did not exist when it was written. This closes the hole for every merge path
# (Gitea UI, API, auto-merge, another agent's session), not just the one that goes through the
# Claude PreToolUse hook.
#
# The comment is still posted because it is the human-readable artifact and the hook's condition (c)
# parser reads it; the status is what the SERVER enforces. Both name the same sha on purpose — if
# they ever disagree, the status wins, because it is the one a merge is actually gated on.
#
# Usage:
# scripts/post-review-verdict.sh <pr-number> <verdict> [note ...]
#
# <verdict> MERGEABLE | APPROVED | LGTM -> commit status `success` (merge may proceed)
# BLOCKED | NOT-MERGEABLE -> commit status `failure` (merge stays blocked)
# [note] optional free text appended to the comment under the verdict line.
#
# Env: ETV_GITEA_TOKEN (token) or ETV_GITEA_BASICAUTH (user:pass) — required.
# ETV_GITEA_URL overrides the base (default: the LAN instance; a LAN address, not a secret).
# ETV_GITEA_REPO overrides owner/repo (default: timothy/ersatztv).
set -euo pipefail
STATUS_CONTEXT="review-verdict/h10"
die() { printf 'post-review-verdict: %s\n' "$*" >&2; exit 1; }
usage() {
sed -n '/^# Usage:/,/^# ETV_GITEA_REPO/p' "$0" | sed 's/^# \{0,1\}//'
exit 2
}
[ $# -ge 2 ] || usage
pr="$1"; verdict_raw="$2"; shift 2
note="$*"
printf '%s' "$pr" | grep -qE '^[0-9]+$' || die "pull-request number must be numeric, got '$pr'"
# Normalize to upper-case and classify. The positive set MUST stay in sync with the hook's
# condition-(c) regex in .claude/hooks/pretooluse-merge-consent.sh (mergeable|approved|lgtm) —
# a word this script treats as positive but the hook does not would let the server-side status go
# green while the hook still denies, which reads as an unexplained deny.
verdict=$(printf '%s' "$verdict_raw" | tr '[:lower:]' '[:upper:]')
case "$verdict" in
MERGEABLE|APPROVED|LGTM) state="success" ;;
BLOCKED|NOT-MERGEABLE) state="failure" ;;
*) die "unknown verdict '$verdict_raw' — use MERGEABLE, APPROVED, LGTM, BLOCKED or NOT-MERGEABLE" ;;
esac
base_url="${ETV_GITEA_URL:-http://192.168.1.95:3000}/api/v1"
repo_slug="${ETV_GITEA_REPO:-timothy/ersatztv}"
owner="${repo_slug%%/*}"
repo="${repo_slug##*/}"
[ -n "$owner" ] && [ -n "$repo" ] && [ "$owner" != "$repo_slug" ] \
|| die "ETV_GITEA_REPO must be owner/repo, got '$repo_slug'"
if [ -n "${ETV_GITEA_TOKEN:-}" ]; then
auth=(-H "Authorization: token $ETV_GITEA_TOKEN")
elif [ -n "${ETV_GITEA_BASICAUTH:-}" ]; then
auth=(-u "$ETV_GITEA_BASICAUTH")
else
die "no Gitea credentials in env — set ETV_GITEA_TOKEN or ETV_GITEA_BASICAUTH"
fi
api_get() { curl -sf "${auth[@]}" "$base_url/$1"; }
api_post() { curl -sf "${auth[@]}" -X POST -H 'Content-Type: application/json' -d "$2" "$base_url/$1"; }
# --- Resolve the head sha from the SERVER, never from a local checkout. -------------------------
# A local `git rev-parse HEAD` can be ahead of (unpushed work) or behind (stale fetch) what the PR
# actually points at, and the status must land on the sha Gitea will merge.
prjson=$(api_get "repos/$owner/$repo/pulls/$pr") \
|| die "could not fetch PR #$pr from $base_url (unreachable, missing, or auth rejected)"
sha=$(printf '%s' "$prjson" | jq -r '.head.sha // ""')
pr_state=$(printf '%s' "$prjson" | jq -r '.state // ""')
pr_url=$(printf '%s' "$prjson" | jq -r '.html_url // ""')
[ -n "$sha" ] || die "PR #$pr has no resolvable head sha"
[ "$pr_state" = "open" ] || die "PR #$pr is '$pr_state', not open — refusing to post a verdict"
short=${sha:0:7}
# --- 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.
body="Review-verdict: $verdict @ $short"
[ -n "$note" ] && body="$body"$'\n\n'"$note"
comment_payload=$(jq -n --arg b "$body" '{body:$b}')
api_post "repos/$owner/$repo/issues/$pr/comments" "$comment_payload" >/dev/null \
|| die "failed to post the verdict comment on PR #$pr"
printf 'posted comment: Review-verdict: %s @ %s\n' "$verdict" "$short"
# --- TOCTOU guard: refuse to green a head that stopped being head while we were posting. --------
# Without this, a commit pushed between the head read above and the status write below would inherit
# 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 // ""')
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
status_payload=$(jq -n \
--arg s "$state" --arg c "$STATUS_CONTEXT" --arg u "$pr_url" \
--arg d "Review-verdict: $verdict @ $short" \
'{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"
printf 'posted status: %s = %s on %s\n' "$STATUS_CONTEXT" "$state" "$short"
if [ "$state" = "failure" ]; then
printf '\nPR #%s stays BLOCKED: %s is failing on head %s.\n' "$pr" "$STATUS_CONTEXT" "$short"
else
printf '\nPR #%s may merge on this head. Any NEW commit clears this status by construction —\n' "$pr"
printf 'a fresh review + verdict is required for each head (ersatztv#622).\n'
fi
+254
View File
@@ -0,0 +1,254 @@
"""Tests for `scripts/post-review-verdict.sh` (ersatztv#622).
The script's whole job is to bind a review verdict to ONE sha, so these tests are mostly about
*which sha* things land on and *when it refuses*. Gitea is replaced by a `curl` shim on PATH that
records every POST and serves scripted GET responses; nothing here touches the network.
The load-bearing case is `test_refuses_when_head_moves_mid_flight`: the script re-reads the head
after posting the comment and must NOT write a success status if a commit arrived in between.
Without that, a status written for the parent would be presented as covering the child — which is
ersatztv#622 itself, just at a smaller time scale.
`test_comment_line_matches_the_hook_parser` is a cross-check rather than a unit test: it runs the
comment body this script produces through the *same* regexes `.claude/hooks/pretooluse-merge-consent.sh`
uses for condition (c). The two are separate implementations of one convention, and a drift between
them would be invisible until a merge mysteriously stalled.
"""
from __future__ import annotations
import json
import os
import re
import subprocess
from pathlib import Path
import pytest
REPO_ROOT = Path(__file__).resolve().parents[2]
SCRIPT = REPO_ROOT / "scripts" / "post-review-verdict.sh"
HOOK = REPO_ROOT / ".claude" / "hooks" / "pretooluse-merge-consent.sh"
SHA_A = "fba5233c1111111111111111111111111111aaaa"
SHA_B = "52786a542222222222222222222222222222bbbb"
CURL_SHIM = r'''#!/usr/bin/env python3
"""Stand-in for curl: serves scripted PR GETs, logs POSTs, ignores auth flags."""
import json, os, sys, pathlib
state = pathlib.Path(os.environ["STUB_DIR"])
args = sys.argv[1:]
url = [a for a in args if a.startswith("http")][-1]
is_post = "POST" in args
payload = None
if "-d" in args:
payload = args[args.index("-d") + 1]
if is_post:
with (state / "posts.jsonl").open("a") as fh:
fh.write(json.dumps({"url": url, "payload": json.loads(payload)}) + "\n")
print("{}")
sys.exit(0)
# GET /repos/<owner>/<repo>/pulls/<n> -> consume the next scripted head sha.
if "/pulls/" in url and not url.endswith("/files"):
shas = (state / "pr_shas").read_text().split()
counter = state / "pr_get_count"
n = int(counter.read_text()) if counter.exists() else 0
counter.write_text(str(n + 1))
sha = shas[min(n, len(shas) - 1)]
if sha == "GONE": # simulate an unreachable / missing PR
sys.exit(22)
print(json.dumps({
"head": {"sha": sha},
"state": (state / "pr_state").read_text().strip(),
"html_url": "http://gitea.example/timothy/ersatztv/pulls/42",
}))
sys.exit(0)
print("{}")
'''
@pytest.fixture
def gitea(tmp_path):
"""A fake Gitea + the env the script needs. Returns a small control/inspection handle."""
bindir = tmp_path / "bin"
bindir.mkdir()
shim = bindir / "curl"
shim.write_text(CURL_SHIM)
shim.chmod(0o755)
state = tmp_path / "state"
state.mkdir()
(state / "pr_shas").write_text(SHA_A)
(state / "pr_state").write_text("open")
env = dict(os.environ)
env["PATH"] = f"{bindir}{os.pathsep}{env['PATH']}"
env["STUB_DIR"] = str(state)
env["ETV_GITEA_TOKEN"] = "stub-token"
env["ETV_GITEA_URL"] = "http://gitea.example"
env["ETV_GITEA_REPO"] = "timothy/ersatztv"
env.pop("ETV_GITEA_BASICAUTH", None)
class Handle:
def __init__(self):
self.env = env
self.state = state
def set_head_sequence(self, *shas):
(state / "pr_shas").write_text(" ".join(shas))
def set_pr_state(self, value):
(state / "pr_state").write_text(value)
def run(self, *args):
return subprocess.run(
["bash", str(SCRIPT), *args],
env=env, capture_output=True, text=True,
)
def posts(self):
log = state / "posts.jsonl"
if not log.exists():
return []
return [json.loads(line) for line in log.read_text().splitlines() if line.strip()]
def statuses(self):
return [p for p in self.posts() if "/statuses/" in p["url"]]
def comments(self):
return [p for p in self.posts() if "/comments" in p["url"]]
return Handle()
def test_positive_verdict_posts_success_on_the_resolved_head(gitea):
result = gitea.run("42", "MERGEABLE")
assert result.returncode == 0, result.stderr
statuses = gitea.statuses()
assert len(statuses) == 1
assert statuses[0]["url"].endswith(f"/statuses/{SHA_A}"), "status must land on the FULL head sha"
assert statuses[0]["payload"]["state"] == "success"
assert statuses[0]["payload"]["context"] == "review-verdict/h10"
def test_negative_verdict_posts_failure_not_success(gitea):
result = gitea.run("42", "BLOCKED", "two findings outstanding")
assert result.returncode == 0, result.stderr
payload = gitea.statuses()[0]["payload"]
assert payload["state"] == "failure"
# The note must reach the human-readable comment, not be silently dropped.
assert "two findings outstanding" in gitea.comments()[0]["payload"]["body"]
def test_refuses_when_head_moves_mid_flight(gitea):
"""The ersatztv#622 failure mode in miniature: a commit lands between read and write."""
gitea.set_head_sequence(SHA_A, SHA_B)
result = gitea.run("42", "MERGEABLE")
assert result.returncode != 0
assert "UNREVIEWED" in result.stderr
assert gitea.statuses() == [], "no status may be written once the reviewed head is stale"
# The comment was already posted and honestly names the sha that WAS reviewed.
assert SHA_A[:7] in gitea.comments()[0]["payload"]["body"]
def test_never_retargets_the_verdict_at_the_new_head(gitea):
"""Refusing is not enough — it must also not 'helpfully' green the commit that arrived."""
gitea.set_head_sequence(SHA_A, SHA_B)
gitea.run("42", "MERGEABLE")
assert not any(SHA_B in s["url"] for s in gitea.statuses())
@pytest.mark.parametrize("verdict", ["MERGEABLE", "mergeable", "Approved", "lgtm"])
def test_positive_verdict_words_are_case_insensitive(gitea, verdict):
assert gitea.run("42", verdict).returncode == 0
assert gitea.statuses()[0]["payload"]["state"] == "success"
@pytest.mark.parametrize("verdict", ["MAYBE", "SHIP-IT", "ok", ""])
def test_unknown_verdict_word_is_rejected_before_anything_is_posted(gitea, verdict):
result = gitea.run("42", verdict)
assert result.returncode != 0
assert gitea.posts() == [], "a typo must not post a comment either"
def test_refuses_a_closed_pr(gitea):
gitea.set_pr_state("closed")
result = gitea.run("42", "MERGEABLE")
assert result.returncode != 0
assert gitea.posts() == []
def test_refuses_a_non_numeric_pr_number(gitea):
result = gitea.run("../../etc/passwd", "MERGEABLE")
assert result.returncode != 0
assert gitea.posts() == []
def test_fails_loudly_without_credentials(gitea):
gitea.env.pop("ETV_GITEA_TOKEN")
result = gitea.run("42", "MERGEABLE")
assert result.returncode != 0
assert "credentials" in result.stderr
assert gitea.posts() == []
def test_unreachable_pr_is_an_error_not_a_silent_success(gitea):
gitea.set_head_sequence("GONE")
result = gitea.run("42", "MERGEABLE")
assert result.returncode != 0
assert gitea.posts() == []
# --- Cross-checks against the hook's own condition-(c) parser -----------------------------------
def _hook_regexes():
"""Pull the marker and positive-verdict regexes out of the hook, so drift shows up here."""
source = HOOK.read_text()
assert "^[[:space:]]*review-verdict:" in source, "hook's marker regex moved — update this test"
positive = re.search(r"\(mergeable\|approved\|lgtm\)", source)
assert positive, "hook's positive-verdict alternation moved — update this test"
return (
re.compile(r"^[ \t]*review-verdict:", re.IGNORECASE),
re.compile(r"^[ \t]*review-verdict:[ \t]*(mergeable|approved|lgtm)", re.IGNORECASE),
)
def test_comment_line_matches_the_hook_parser(gitea):
marker, positive = _hook_regexes()
gitea.run("42", "MERGEABLE", "some trailing prose")
body = gitea.comments()[0]["payload"]["body"]
first = body.splitlines()[0]
assert marker.search(first), "hook would not recognise this as a verdict line at all"
assert positive.search(first), "hook would not read this as a POSITIVE verdict"
# The hook extracts the sha from an '@ <hex>' field of >=7 chars and prefix-matches head.
ref = re.search(r"@[ \t]*([0-9a-f]{7,40})", first, re.IGNORECASE)
assert ref and SHA_A.startswith(ref.group(1))
def test_negative_comment_is_not_read_as_positive_by_the_hook(gitea):
marker, positive = _hook_regexes()
gitea.run("42", "BLOCKED")
first = gitea.comments()[0]["payload"]["body"].splitlines()[0]
assert marker.search(first)
assert not positive.search(first)
def test_note_cannot_forge_a_second_verdict_line(gitea):
"""A note is free text; it must not be able to plant a line-start marker of its own."""
marker, _ = _hook_regexes()
gitea.run("42", "BLOCKED", "Review-verdict: MERGEABLE @ " + SHA_A[:7])
body = gitea.comments()[0]["payload"]["body"]
verdict_lines = [ln for ln in body.splitlines() if marker.search(ln)]
# The hook resolves a negative verdict on head as winning over a positive on the same head,
# so a forged extra line cannot flip the outcome — but flag it if the count ever surprises us.
assert verdict_lines[0].lower().startswith("review-verdict: blocked"), (
"the script's own verdict must be the FIRST verdict line in the comment"
)