fix(629): close three false-opens in the H10 verdict grammar, and give it tests

The H10 classification lived inline in `pretooluse-merge-consent.sh` with no tests. Three
protections the `release.review-verdict-gate` record described were never actually
implemented, and each graded an unreviewed head as approved. All three reproduced first:

  1 MERGEABLE-LATER   -> positive     the token was prefix-matched, so any word STARTING
                                      with mergeable/approved/lgtm passed
  2 fenced code block -> positive     the line-start anchor is satisfied inside ```, so
                                      documentation showing the convention was a verdict
  3 URL-borne sha     -> positive     the sha came from the first `@<hex>` ANYWHERE on the
                                      line, so a markdown link could supply it

Fixes: whole-word token matching, with a token in neither vocabulary classified `unknown`
(never positive, and not guessed into a block either — it goes to a human); fenced blocks
stripped with fence state reset per comment body; the sha read from the verdict's OWN
`@ <sha>` field, which also makes multi-`@` lines unambiguous.

The grammar moves to `scripts/check-review-verdict.sh` so it can be tested at all — 38 tests,
and each fix mutation-verified: restoring the old regex/extraction makes exactly the
corresponding test fail, control green.

#629's fourth reported item is NOT a defect and is not claimed as a fix. A later `@ <head>`
on a BLOCKED line was reported as "masking a negative"; under the documented grammar that
line is a verdict for the sha in its own field, so `stale` is correct — and was correct
before this change too. Kept as a characterization test.

`test_post_review_verdict.py`'s cross-check re-implemented the hook's regexes in Python and
asserted the shell still contained them. That mirror is removed: it is the same duplication
that let these three survive, and a Python copy would keep passing while the shell drifted.
It now runs the real classifier.

The decision record is corrected — it asserted the URL protection this commit actually adds.

Note: the active corpus is 5637 lines against a 5600 budget, so the validator emits its
consolidation warning (non-blocking). That is #620's subject, not regressed here.

fixes #629

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

Decisions-Edit: yes
This commit is contained in:
2026-07-25 23:46:23 +02:00
co-authored by Claude Opus 5
parent 98f9e6ec34
commit 38a96f47cc
6 changed files with 445 additions and 84 deletions
+216
View File
@@ -0,0 +1,216 @@
"""H10 verdict-classification grammar (`scripts/check-review-verdict.sh`).
Before #629 this logic lived inline in `pretooluse-merge-consent.sh` with NO tests, and three
false-opens survived in it — each making an unreviewed head read as approved. Every
`test_falseopen_*` below fails against the pre-#629 grammar; that is what makes them regression
tests rather than descriptions.
#629 reported a fourth item. It turned out not to be a defect — see
`test_a_later_at_token_does_not_retarget_the_verdict`, kept as characterization.
"""
import json
import subprocess
from pathlib import Path
import pytest
SCRIPT = Path(__file__).resolve().parents[1] / "check-review-verdict.sh"
HEAD = "02c82b35eafd715380ddd6b8ba03cb63f0966a3f"
SHORT = HEAD[:7]
OTHER = "fba5233caf44f41bf6601352f1c1b9f46e829262"
def classify(bodies, head=HEAD):
"""Run the classifier over comment bodies; return (stdout_word, returncode)."""
payload = json.dumps([{"body": b} for b in bodies])
p = subprocess.run(["bash", str(SCRIPT), "--head", head], input=payload, capture_output=True, text=True)
return p.stdout.strip(), p.returncode
def verdict(word, sha):
return f"Review-verdict: {word} @ {sha}"
# --- the three #629 false-opens ---------------------------------------------------------------
@pytest.mark.parametrize("token", ["MERGEABLE-LATER", "APPROVED-PENDING-QA", "LGTMish", "MERGEABLEISH"])
def test_falseopen_token_must_be_a_whole_word(token):
"""#629(1): the old test prefix-matched, so any token STARTING with a positive word passed.
An unrecognized token is `unknown` — never positive, and never guessed into a block either.
"""
assert classify([verdict(token, HEAD)]) == ("unknown", 0)
def test_falseopen_fenced_code_block_is_not_a_verdict():
"""#629(2): inside a fence the marker IS at line start, so docs showing the convention counted."""
body = f"Post it like this:\n\n```\n{verdict('MERGEABLE', HEAD)}\n```\n"
assert classify([body]) == ("absent", 0)
def test_falseopen_sha_may_not_come_from_a_url():
"""#629(3): the old rule took the first `@<hex>` ANYWHERE on the line, so a link supplied it."""
line = f"Review-verdict: MERGEABLE [x](https://e.invalid/@{HEAD[:12]})"
assert classify([line]) == ("no-sha", 0)
def test_a_later_at_token_does_not_retarget_the_verdict():
"""CHARACTERIZATION, not a regression test — #629's fourth reported item was NOT a false-open.
The report framed a later `@ <head>` on a BLOCKED line as "masking a negative". It isn't: under
the documented grammar the line is a verdict for `deadbeef1234`, so `stale` is correct, and it was
correct before #629 too (the old first-`@`-anywhere rule picked the same token here). No false-open
exists — the line never grants on head either way.
Kept because it pins the grammar the anchored field now guarantees: the sha is the verdict's OWN
field, and trailing `@` tokens cannot re-target it.
"""
line = f"Review-verdict: BLOCKED @ deadbeef1234 correction @ {HEAD}"
assert classify([line]) == ("stale", 0)
def test_fence_state_does_not_leak_between_comments():
"""An unclosed fence in one comment must not swallow a real verdict in the next."""
assert classify(["Example:\n```\nnot a verdict", verdict("MERGEABLE", HEAD)]) == ("positive", 0)
# --- the happy paths -------------------------------------------------------------------------
@pytest.mark.parametrize("word", ["MERGEABLE", "APPROVED", "LGTM", "mergeable", "Approved"])
def test_positive_verdict_on_head(word):
assert classify([verdict(word, HEAD)]) == ("positive", 0)
@pytest.mark.parametrize("word", ["BLOCKED", "NOT-MERGEABLE", "blocked", "not-mergeable"])
def test_negative_verdict_on_head(word):
assert classify([verdict(word, HEAD)]) == ("negative", 0)
def test_short_sha_prefix_is_accepted():
assert classify([verdict("MERGEABLE", SHORT)]) == ("positive", 0)
def test_leading_indent_is_tolerated():
assert classify([f" {verdict('MERGEABLE', HEAD)}"]) == ("positive", 0)
def test_verdict_among_ordinary_prose_in_the_same_comment():
body = f"Reviewed the fix commit; findings resolved.\n\n{verdict('MERGEABLE', HEAD)}\n"
assert classify([body]) == ("positive", 0)
# --- precedence ------------------------------------------------------------------------------
def test_negative_wins_over_positive_on_the_same_head():
assert classify([verdict("MERGEABLE", HEAD), verdict("BLOCKED", HEAD)]) == ("negative", 0)
assert classify([verdict("BLOCKED", HEAD), verdict("MERGEABLE", HEAD)]) == ("negative", 0)
def test_staleness_is_symmetric_old_negative_does_not_block_a_fresh_positive():
"""A pre-fix `BLOCKED @ oldsha` must not block forever once the fix changes the sha."""
assert classify([verdict("BLOCKED", OTHER), verdict("MERGEABLE", HEAD)]) == ("positive", 0)
def test_a_real_verdict_outranks_an_unknown_token():
assert classify([verdict("MERGEABLE-LATER", HEAD), verdict("MERGEABLE", HEAD)]) == (
"positive",
0,
)
# --- the stale-review case #242 targets ------------------------------------------------------
def test_verdict_only_for_an_older_commit_is_stale():
assert classify([verdict("MERGEABLE", OTHER)]) == ("stale", 0)
def test_old_sha_containing_the_head_prefix_does_not_match():
contains_head_prefix = "abcdef" + SHORT + "1234567890abcdef1234567890abcdef"
assert classify([verdict("MERGEABLE", contains_head_prefix)]) == ("stale", 0)
def test_a_mid_string_substring_of_head_is_not_a_prefix_match():
"""The discriminating case for prefix-vs-substring matching.
`interior` is a genuine substring of head but NOT a prefix, so `*"$ref"*` instead of `"$ref"*`
would wrongly match. The sibling test above cannot catch that: its fixture is LONGER than a
40-char sha, so it fails a substring test for the wrong reason.
"""
interior = HEAD[5:15]
assert interior in HEAD and not HEAD.startswith(interior)
assert classify([verdict("MERGEABLE", interior)]) == ("stale", 0)
def test_trailing_url_does_not_change_a_valid_verdicts_target():
line = f"Review-verdict: MERGEABLE @ {OTHER} (see http://ci.example/build/{HEAD})"
assert classify([line]) == ("stale", 0)
# --- false-open guards -----------------------------------------------------------------------
def test_quoted_template_mid_sentence_is_not_a_verdict():
assert classify([f"Please post: {verdict('MERGEABLE', HEAD)} when you are done"]) == (
"absent",
0,
)
def test_blockquoted_verdict_is_not_a_verdict():
assert classify([f"> {verdict('MERGEABLE', HEAD)}"]) == ("absent", 0)
def test_trailing_mergeable_substring_cannot_flip_a_blocked_line():
line = f"Review-verdict: BLOCKED @ {HEAD} — do not post review-verdict: mergeable until fixed"
assert classify([line]) == ("negative", 0)
def test_marker_without_a_sha_is_undecidable():
assert classify(["Review-verdict: MERGEABLE"]) == ("no-sha", 0)
def test_too_short_a_sha_is_not_a_reference():
assert classify([verdict("MERGEABLE", HEAD[:6])]) == ("no-sha", 0)
def test_no_marker_at_all_is_absent():
assert classify(["LGTM, nice work", "ship it"]) == ("absent", 0)
def test_empty_comment_list_is_absent():
assert classify([]) == ("absent", 0)
# --- fail-closed on bad input ----------------------------------------------------------------
def test_malformed_json_is_an_input_error_not_absent():
"""Must NOT degrade to `absent` — that reads as "not adopted" and downgrades a block to an ask."""
p = subprocess.run(["bash", str(SCRIPT), "--head", HEAD], input="{not json", capture_output=True, text=True)
assert p.returncode == 2, p.stdout
def test_empty_stdin_is_an_input_error():
p = subprocess.run(["bash", str(SCRIPT), "--head", HEAD], input="", capture_output=True, text=True)
assert p.returncode == 2
def test_missing_head_argument_is_an_input_error():
p = subprocess.run(["bash", str(SCRIPT)], input="[]", capture_output=True, text=True)
assert p.returncode == 2
def test_non_hex_head_is_an_input_error():
p = subprocess.run(
["bash", str(SCRIPT), "--head", "refs/heads/main"],
input="[]",
capture_output=True,
text=True,
)
assert p.returncode == 2
+38 -34
View File
@@ -9,17 +9,21 @@ after posting the comment and must NOT write a success status if a commit arrive
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.
`test_comment_matches_the_hook_parser` is a cross-check rather than a unit test: it runs the comment
body this script produces through the *actual* H10 classifier the hook uses for condition (c),
`scripts/check-review-verdict.sh`. A drift between the two would be invisible until a merge
mysteriously stalled.
It originally re-implemented the hook's regexes in Python and asserted the shell source still
contained them. #629 removed that mirror: three false-opens had survived precisely because the
grammar existed in two places, and a Python copy would have kept passing while the shell drifted.
The grammar now lives in one tested script, so this calls it.
"""
from __future__ import annotations
import json
import os
import re
import subprocess
from pathlib import Path
@@ -28,6 +32,7 @@ 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"
CLASSIFIER = REPO_ROOT / "scripts" / "check-review-verdict.sh"
SHA_A = "fba5233c1111111111111111111111111111aaaa"
SHA_B = "52786a542222222222222222222222222222bbbb"
@@ -208,47 +213,46 @@ def test_unreachable_pr_is_an_error_not_a_silent_success(gitea):
# --- 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 _classify(body: str, head: str) -> str:
"""Run the REAL H10 classifier over a comment body — no Python mirror of the grammar.
This used to scrape the hook's regexes and re-implement them here (#622). Since #629 the grammar
lives in one tested place, `scripts/check-review-verdict.sh`, and the hook calls it — so the
cross-check can execute the actual thing. That matters: a Python copy of a shell regex is exactly
the duplication that let three false-opens survive in the first place, and it would have kept
passing here while the shell drifted.
"""
payload = json.dumps([{"body": body}])
p = subprocess.run(
["bash", str(CLASSIFIER), "--head", head], input=payload, capture_output=True, text=True
)
assert p.returncode == 0, f"classifier errored: {p.stderr}"
return p.stdout.strip()
def test_comment_line_matches_the_hook_parser(gitea):
marker, positive = _hook_regexes()
def test_comment_matches_the_hook_parser(gitea):
"""The comment this script posts must classify as a positive verdict for the sha it names."""
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))
assert _classify(body, SHA_A) == "positive"
# ...and it must NOT be read as covering a different head.
assert _classify(body, SHA_B) == "stale"
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)
body = gitea.comments()[0]["payload"]["body"]
assert _classify(body, SHA_A) == "negative"
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()
"""A note is free text; it must not be able to plant a verdict of its own.
Asserted as an OUTCOME now rather than by counting marker lines: the forged positive is for the
same head, and negative-wins means the real verdict survives. Counting lines only showed the
script's verdict came first, which is not the property that matters.
"""
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"
)
assert _classify(body, SHA_A) == "negative"