From 766a7a61759ba9efb5199549fac222cb397840e8 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 13:12:16 +0000 Subject: [PATCH 1/3] feat(pm-stack): lane-guard skips a repeated triage verdict (F2a, #12233) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extend lane_guard.py note with a verdict path: a triage verdict (state triaged, with a recorded --verdict token in the canonical note header) is skipped when the newest agent note on the issue already records the same verdict — across task ids, with no time window — and nothing has changed since: no human comment, and no commit, label or body change on the issue (read from its timeline via changes_from_timeline). Park/pick-up dedupe is unchanged, and the timeline is only fetched for verdict requests. This is the recorded-verdict format F2b coverage will read: the verdict token lives in the agent-note header, so it is machine-checkable instead of free-form prose (#1062 collected four identical verdicts as prose). Tests: 47 offline tests pass (16 new), including the F2a done-test — two tasks, one unchanged issue, second note skipped; a third after a new commit is posted. Mutation check: inverting the change-time comparison fails 5 freshness tests. Refs #12233 --- pm-stack/lane-guard/lane_guard.py | 178 ++++++++++++++++++++- pm-stack/lane-guard/test_lane_guard.py | 209 +++++++++++++++++++++++++ 2 files changed, 380 insertions(+), 7 deletions(-) diff --git a/pm-stack/lane-guard/lane_guard.py b/pm-stack/lane-guard/lane_guard.py index 101152c361..f78aff8603 100755 --- a/pm-stack/lane-guard/lane_guard.py +++ b/pm-stack/lane-guard/lane_guard.py @@ -27,12 +27,23 @@ DEDUPE_WINDOW ago, with no human comment since. Progress notes (pr_opened, blocked, completed, ...) always post. + A triage verdict (state `triaged`, ideally with a recorded + `--verdict` token) is skipped when the newest agent note on + the item already records the same verdict — across task + ids, with no time window — and nothing has changed since: + no human comment, and no commit, label or body change on + the issue (read from its timeline). A verdict stands until + the issue changes; re-posting it is the repeat-triage churn + #12233 removes (#1062 collected four identical verdicts). + Usage (exit 0 = go ahead, 3 = held / skip the note, 2 = usage or I/O error; JSON verdict on stdout either way): lane_guard.py hold --repo developing-today/code --issue 7616 lane_guard.py note --repo developing-today/code --issue 7616 \ --task 20028 --state parked + lane_guard.py note --repo developing-today/code --issue 1062 \ + --task 2334 --state triaged --verdict still_blocked """ from __future__ import annotations @@ -57,6 +68,10 @@ # the churn this guard removes. QUIET_STATES = frozenset({"parked", "picked_up", "picked-up"}) +# States that record a triage verdict. A verdict note is deduped by its +# verdict, not by task or age: see note_verdict's verdict path. +VERDICT_STATES = frozenset({"triaged"}) + DEDUPE_WINDOW = timedelta(hours=24) EXIT_GO = 0 @@ -123,6 +138,10 @@ def hold_verdict(item: dict) -> dict: re.IGNORECASE | re.MULTILINE, ) _TASK_RE = re.compile(r"\btask(?:_id)?\s*[:=]?\s*#?(\d{3,})", re.IGNORECASE) +# The recorded verdict of a triage note: `verdict: still_blocked` / +# `verdict=still_blocked` in the header area. A short token, so two +# lanes recording the same outcome produce the same key. +_VERDICT_RE = re.compile(r"\bverdict\s*[:=]\s*([A-Za-z0-9][\w -]*)", re.IGNORECASE) # Lanes write notes free-form; these map the words they use to states. _STATE_WORDS = ( ( @@ -148,6 +167,12 @@ def _norm_state(raw: str) -> str: return word.group(0).lower().replace("-", "_") if word else "" +def _norm_verdict(raw: str) -> str: + """Canonical verdict key: `Still blocked!` and `still_blocked` are + the same verdict.""" + return re.sub(r"[^a-z0-9]+", "_", str(raw).lower()).strip("_") + + def parse_note(body: str) -> dict | None: """{"state", "task"} for an agent note body, None for other comments. @@ -157,6 +182,8 @@ def parse_note(body: str) -> dict | None: (`transition: picked-up -> parked`), and free-form first lines (`**Pickup — queue task 20028**`). State is None when nothing recognisable is present; such a note never counts as a duplicate. + A triage note that records a `verdict:`/`verdict=` field also + carries a normalised "verdict" key. """ if not isinstance(body, str) or not _MARKER.search(body): return None @@ -175,13 +202,23 @@ def parse_note(body: str) -> dict | None: first = lines[0] if lines else "" state = next((s for s, pat in _HEAD_WORDS if pat.search(first)), None) m_task = _TASK_RE.search(head) - return {"state": state or None, "task": m_task.group(1) if m_task else None} + note = {"state": state or None, "task": m_task.group(1) if m_task else None} + m_verdict = _VERDICT_RE.search(head) + if m_verdict: + verdict = _norm_verdict(m_verdict.group(1)) + if verdict: + note["verdict"] = verdict + return note -def note_header(task: str, state: str) -> str: +def note_header(task: str, state: str, verdict: str | None = None) -> str: """Canonical first line for a lane's agent note, so later dedupe - checks parse it exactly.""" - return f"" + checks parse it exactly. A triage note passes its verdict so the + next lane's check can match it.""" + header = f"" def _ts(value): @@ -190,14 +227,119 @@ def _ts(value): return datetime.fromisoformat(str(value).replace("Z", "+00:00")) -def note_verdict(comments: list, task: str, state: str, now=None) -> dict: +# Timeline event -> the kind of issue change it proves, for verdict +# freshness. `commented` is deliberately absent: comments are judged +# from the comment list itself, where human vs bot is visible. +_TIMELINE_CHANGES = {"labeled": "label", "unlabeled": "label", "edited": "body"} + + +def changes_from_timeline(events: list) -> list: + """[{"kind", "at"}] for the issue changes a verdict must not + outlive: a commit referenced on the issue, a label change, a body + edit. Input is REST timeline JSON (oldest first); a `referenced` + event only counts as a commit when it carries a commit_id (a + cross-reference from another issue is not one). + """ + out = [] + for e in events or []: + if not isinstance(e, dict): + continue + kind = _TIMELINE_CHANGES.get(e.get("event")) + if e.get("event") == "referenced" and e.get("commit_id"): + kind = "commit" + if kind and e.get("created_at"): + out.append({"kind": kind, "at": e["created_at"]}) + return out + + +def _verdict_key(state, verdict) -> str: + """The comparable key of a verdict: the recorded verdict token + when there is one, else the state it was recorded under. A note + with a recorded verdict never matches one without (or vice + versa): the recorded form is what later checks — and coverage — + read.""" + if verdict: + return f"verdict:{verdict}" + return f"state:{state}" + + +def _is_verdict_request(state, verdict) -> bool: + if verdict: + return True + state = str(state).lower().replace("-", "_") + return state in VERDICT_STATES or _norm_state(state) in VERDICT_STATES + + +def _verdict_note_verdict(comments, state, verdict, changes, now) -> dict: + """The verdict path of note_verdict (#12233 F2a): a triage verdict + is skipped when the newest agent note already records the same + verdict — for any task id, however long ago — and nothing has + changed since: no human comment, and no commit, label or body + change (from `changes`, see changes_from_timeline) after it. + """ + want = _verdict_key(state, verdict) + for c in reversed(comments or []): + note = parse_note(c.get("body")) + if note is None: + user = c.get("user") or {} + if user.get("type") == "Bot": + continue # bots (CI, sweepers) are not news + return { + "post": True, + "reason": "a non-agent comment arrived since the last agent note", + } + if note["state"] not in VERDICT_STATES and not note.get("verdict"): + return { + "post": True, + "reason": f"newest agent note is not a triage verdict (it was {note['state']})", + } + have = _verdict_key(note["state"], note.get("verdict")) + if have != want: + return { + "post": True, + "reason": f"newest recorded verdict is {have}, this is {want}", + } + since = _ts(c.get("created_at")) + for ch in changes or (): + if _ts(ch["at"]) > since: + return { + "post": True, + "reason": ( + f"the issue changed since the verdict: a {ch['kind']} " + f"change at {ch['at']}" + ), + } + age = now - since + return { + "post": False, + "reason": ( + f"duplicate verdict: newest agent note already records {want} " + f"for this issue (task {note['task']}, " + f"{int(age.total_seconds() // 60)} min ago) and no commit, " + "label, body or human comment has changed since; record " + "the outcome on the queue task instead of re-triaging" + ), + } + return {"post": True, "reason": "no earlier agent note"} + + +def note_verdict( + comments: list, task: str, state: str, now=None, verdict=None, changes=() +) -> dict: """Should a note of `state` for queue `task` be posted, given the item's comments (oldest first, REST shape: body, created_at, user.type)? + + A triage verdict (state `triaged`, or any note with a `verdict`) + takes the verdict path: `changes` is the issue's change list from + changes_from_timeline. Everything else takes the park path. """ now = _ts(now) if now is not None else datetime.now(timezone.utc) state = str(state).lower().replace("-", "_") task = str(task).lstrip("#") + verdict = _norm_verdict(verdict) if verdict else None + if _is_verdict_request(state, verdict): + return _verdict_note_verdict(comments, state, verdict, changes, now) if state not in {s.replace("-", "_") for s in QUIET_STATES}: return {"post": True, "reason": f"progress state {state} always posts"} @@ -262,6 +404,13 @@ def main(argv=None, gh=_gh_json, now=None) -> int: n.add_argument("--issue", required=True, type=int) n.add_argument("--task", required=True) n.add_argument("--state", required=True) + n.add_argument( + "--verdict", + default=None, + help="the triage verdict this note records (state triaged); " + "an unchanged issue with the same verdict already recorded " + "skips the note", + ) args = ap.parse_args(argv) try: @@ -273,8 +422,23 @@ def main(argv=None, gh=_gh_json, now=None) -> int: comments = gh( f"repos/{args.repo}/issues/{args.issue}/comments?per_page=100" ) - verdict = note_verdict(comments, args.task, args.state, now=now) - verdict["header"] = note_header(args.task, args.state) + changes = () + if _is_verdict_request(args.state, args.verdict): + timeline = gh( + f"repos/{args.repo}/issues/{args.issue}/timeline?per_page=100" + ) + changes = changes_from_timeline(timeline) + verdict = note_verdict( + comments, + args.task, + args.state, + now=now, + verdict=args.verdict, + changes=changes, + ) + verdict["header"] = note_header( + args.task, args.state, verdict=args.verdict + ) code = EXIT_GO if verdict["post"] else EXIT_STOP except ( OSError, diff --git a/pm-stack/lane-guard/test_lane_guard.py b/pm-stack/lane-guard/test_lane_guard.py index 71f53b2e09..7d94188bad 100644 --- a/pm-stack/lane-guard/test_lane_guard.py +++ b/pm-stack/lane-guard/test_lane_guard.py @@ -60,6 +60,21 @@ def comment(body, minutes_ago, user_type="User"): "lane: oc-code-07 task: 20028 summary: Fresh verification" ) PR_OPENED = "agent-note:v1\nstate: pr_opened\ntask: 20028\nlane: oc-code-04\n\nOpened PR #12100." +# Triage verdict notes (#12233 F2a): the same verdict recorded by two +# different queue tasks, in the HTML and YAML shapes. +HTML_TRIAGED = ( + "\n" + "Triaged: still blocked on F12.4 (#1061)." +) +YAML_TRIAGED = ( + "agent-note:v1\nstate: triaged\ntask: 22222\nverdict: still_blocked\n\n" + "Verdict: still blocked on F12.4 (#1061)." +) +TRIAGED_NO_VERDICT = "agent-note:v1\nstate: triaged\ntask: 22222\n\nStill live." + + +def at(minutes_ago): + return (NOW - timedelta(minutes=minutes_ago)).isoformat().replace("+00:00", "Z") class HoldVerdict(unittest.TestCase): @@ -155,6 +170,22 @@ def test_canonical_header_round_trips(self): {"state": "parked", "task": "20028"}, ) + def test_verdict_field_is_parsed_and_normalised(self): + body = "agent-note:v1\nstate: triaged\ntask: 22222\nverdict: Still Blocked!\n" + self.assertEqual( + lg.parse_note(body), + {"state": "triaged", "task": "22222", "verdict": "still_blocked"}, + ) + + def test_canonical_header_with_verdict_round_trips(self): + self.assertEqual( + lg.parse_note( + lg.note_header("20028", "triaged", verdict="still blocked") + + "\nTriaged." + ), + {"state": "triaged", "task": "20028", "verdict": "still_blocked"}, + ) + def test_plain_comment_is_not_a_note(self): self.assertIsNone(lg.parse_note("Looks good, ship it.")) self.assertIsNone(lg.parse_note(None)) @@ -230,6 +261,117 @@ def test_7616_churn_collapses_to_one_note_per_day(self): self.assertEqual(len(posted), 1) +class VerdictNote(unittest.TestCase): + """#12233 F2a: a triage verdict is posted once per verdict per + unchanged issue, across task ids.""" + + def verdict(self, cs, task="99999", verdict="still_blocked", changes=()): + return lg.note_verdict( + cs, task, "triaged", now=NOW, verdict=verdict, changes=changes + ) + + def test_same_verdict_other_task_unchanged_issue_is_skipped(self): + # The F2a done-test: two tasks, one unchanged issue — the + # second task's identical verdict note is skipped. + for body in (HTML_TRIAGED, YAML_TRIAGED): + with self.subTest(body=body[:30]): + v = self.verdict([comment(body, 40)]) + self.assertFalse(v["post"]) + self.assertIn("duplicate verdict", v["reason"]) + + def test_verdict_spelling_is_normalised(self): + v = self.verdict([comment(HTML_TRIAGED, 40)], verdict="Still blocked!") + self.assertFalse(v["post"]) + + def test_new_commit_after_verdict_posts(self): + # The other half of the F2a done-test: a third note, after a + # new commit lands on the issue, is posted. + changes = [{"kind": "commit", "at": at(10)}] + v = self.verdict([comment(HTML_TRIAGED, 40)], changes=changes) + self.assertTrue(v["post"]) + self.assertIn("commit", v["reason"]) + + def test_label_and_body_changes_after_verdict_post(self): + for kind in ("label", "body"): + with self.subTest(kind=kind): + changes = [{"kind": kind, "at": at(10)}] + v = self.verdict([comment(HTML_TRIAGED, 40)], changes=changes) + self.assertTrue(v["post"]) + self.assertIn(kind, v["reason"]) + + def test_change_before_the_verdict_does_not_reopen_it(self): + changes = [{"kind": "commit", "at": at(50)}] + v = self.verdict([comment(HTML_TRIAGED, 40)], changes=changes) + self.assertFalse(v["post"]) + + def test_different_verdict_posts(self): + v = self.verdict([comment(HTML_TRIAGED, 40)], verdict="needs_slice") + self.assertTrue(v["post"]) + self.assertIn("needs_slice", v["reason"]) + + def test_verdict_has_no_dedupe_window(self): + # A verdict stands until the issue changes: three days on, + # the repeat is still skipped (park notes expire in 24h). + v = self.verdict([comment(HTML_TRIAGED, 3 * 24 * 60)]) + self.assertFalse(v["post"]) + + def test_human_comment_after_verdict_posts(self): + cs = [comment(HTML_TRIAGED, 40), comment("Drew: take another look.", 10)] + self.assertTrue(self.verdict(cs)["post"]) + + def test_bot_comment_after_verdict_still_skips(self): + cs = [comment(HTML_TRIAGED, 40), comment("CI summary", 10, user_type="Bot")] + self.assertFalse(self.verdict(cs)["post"]) + + def test_newest_note_not_a_verdict_posts(self): + v = self.verdict([comment(YAML_PARKED, 10)]) + self.assertTrue(v["post"]) + self.assertIn("not a triage verdict", v["reason"]) + + def test_state_only_verdicts_match_across_tasks(self): + # Notes recorded before --verdict existed carry only the + # state; two of those still dedupe. + v = lg.note_verdict( + [comment(TRIAGED_NO_VERDICT, 40)], "99999", "triaged", now=NOW + ) + self.assertFalse(v["post"]) + + def test_recorded_verdict_does_not_match_unrecorded(self): + v = lg.note_verdict( + [comment(HTML_TRIAGED, 40)], "99999", "triaged", now=NOW + ) + self.assertTrue(v["post"]) + + def test_first_verdict_posts(self): + self.assertTrue(self.verdict([])["post"]) + + +class ChangesFromTimeline(unittest.TestCase): + def test_maps_change_events(self): + events = [ + {"event": "labeled", "created_at": at(50)}, + {"event": "commented", "created_at": at(45)}, + {"event": "referenced", "commit_id": "abc123", "created_at": at(40)}, + {"event": "referenced", "created_at": at(35)}, # cross-ref, no commit + {"event": "edited", "created_at": at(30)}, + {"event": "unlabeled", "created_at": at(25)}, + {"event": "assigned", "created_at": at(20)}, + ] + self.assertEqual( + lg.changes_from_timeline(events), + [ + {"kind": "label", "at": at(50)}, + {"kind": "commit", "at": at(40)}, + {"kind": "body", "at": at(30)}, + {"kind": "label", "at": at(25)}, + ], + ) + + def test_junk_events_are_ignored(self): + self.assertEqual(lg.changes_from_timeline([]), []) + self.assertEqual(lg.changes_from_timeline([None, {}, {"event": "labeled"}]), []) + + class Cli(unittest.TestCase): def run_cli(self, argv, gh, now=NOW): buf = io.StringIO() @@ -279,6 +421,73 @@ def gh(path): out["header"], "" ) + def test_note_cli_verdict_fetches_timeline_and_skips_duplicate(self): + seen = [] + + def gh(path): + seen.append(path) + if "timeline" in path: + return [] + return [comment(HTML_TRIAGED, 5)] + + code, out = self.run_cli( + [ + "note", + "--repo", + "o/r", + "--issue", + "1062", + "--task", + "20028", + "--state", + "triaged", + "--verdict", + "still_blocked", + ], + gh=gh, + ) + self.assertEqual( + seen, + [ + "repos/o/r/issues/1062/comments?per_page=100", + "repos/o/r/issues/1062/timeline?per_page=100", + ], + ) + self.assertEqual(code, lg.EXIT_STOP) + self.assertFalse(out["post"]) + self.assertEqual( + out["header"], + "", + ) + + def test_note_cli_verdict_posts_after_a_commit(self): + def gh(path): + if "timeline" in path: + return [ + {"event": "referenced", "commit_id": "abc123", "created_at": at(1)} + ] + return [comment(HTML_TRIAGED, 5)] + + code, out = self.run_cli( + [ + "note", + "--repo", + "o/r", + "--issue", + "1062", + "--task", + "20028", + "--state", + "triaged", + "--verdict", + "still_blocked", + ], + gh=gh, + ) + self.assertEqual(code, lg.EXIT_GO) + self.assertTrue(out["post"]) + self.assertIn("commit", out["reason"]) + def test_gh_failure_is_exit_2(self): def boom(path): raise RuntimeError("HTTP 502") From df60d7cc77eda26b54700835becf46a0ba890c90 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 15:59:00 +0000 Subject: [PATCH 2/3] fix(pm-stack): detect issue body edits via a verdict body fingerprint The lane-guard verdict path mapped a timeline 'edited' event to a body change, but GitHub's REST timeline exposes no 'edited' event type, so a body edit after a triage verdict never invalidated it and the guard suppressed re-triage indefinitely. Verdict notes now record a body_fp (first 16 hex of the sha256 of the normalised issue body) in the canonical header, and the verdict check compares it with the issue's current body, fetched by the note CLI. A changed body posts; a verdict note with no fingerprint posts once so the new note records one. The dead 'edited' timeline mapping is removed, and the verdict regex no longer swallows a following header field into the verdict token. Fixes the Codex review thread on #12543 (comment 4658254256). --- pm-stack/lane-guard/lane_guard.py | 117 ++++++++++++++++++---- pm-stack/lane-guard/test_lane_guard.py | 131 +++++++++++++++++++++---- 2 files changed, 210 insertions(+), 38 deletions(-) diff --git a/pm-stack/lane-guard/lane_guard.py b/pm-stack/lane-guard/lane_guard.py index f78aff8603..d6672f0ae0 100755 --- a/pm-stack/lane-guard/lane_guard.py +++ b/pm-stack/lane-guard/lane_guard.py @@ -31,9 +31,11 @@ `--verdict` token) is skipped when the newest agent note on the item already records the same verdict — across task ids, with no time window — and nothing has changed since: - no human comment, and no commit, label or body change on - the issue (read from its timeline). A verdict stands until - the issue changes; re-posting it is the repeat-triage churn + no human comment, no commit or label change on the issue + (read from its timeline), and no body change (a fingerprint + of the body recorded in the verdict note, compared with the + issue's current body). A verdict stands until the issue + changes; re-posting it is the repeat-triage churn #12233 removes (#1062 collected four identical verdicts). Usage (exit 0 = go ahead, 3 = held / skip the note, 2 = usage or I/O @@ -49,6 +51,7 @@ from __future__ import annotations import argparse +import hashlib import json import re import subprocess @@ -140,8 +143,18 @@ def hold_verdict(item: dict) -> dict: _TASK_RE = re.compile(r"\btask(?:_id)?\s*[:=]?\s*#?(\d{3,})", re.IGNORECASE) # The recorded verdict of a triage note: `verdict: still_blocked` / # `verdict=still_blocked` in the header area. A short token, so two -# lanes recording the same outcome produce the same key. -_VERDICT_RE = re.compile(r"\bverdict\s*[:=]\s*([A-Za-z0-9][\w -]*)", re.IGNORECASE) +# lanes recording the same outcome produce the same key. The value is +# a run of words; a word followed by `=` or `:` ends it, so a later +# header field (`body_fp=...`, `task=...`) is never swallowed into +# the verdict — the old greedy `[\w -]*` did exactly that once +# `body_fp` followed the verdict. +_VERDICT_RE = re.compile( + r"\bverdict\s*[:=]\s*([A-Za-z0-9][\w-]*(?:\s+(?![\w-]+\s*[:=])[\w-]+)*)", + re.IGNORECASE, +) +# The body fingerprint of a triage note: `body_fp: <16 hex>` / +# `body_fp=<16 hex>` in the header area. See body_fingerprint. +_BODY_FP_RE = re.compile(r"\bbody_fp\s*[:=]\s*([0-9a-f]{16})\b", re.IGNORECASE) # Lanes write notes free-form; these map the words they use to states. _STATE_WORDS = ( ( @@ -173,6 +186,18 @@ def _norm_verdict(raw: str) -> str: return re.sub(r"[^a-z0-9]+", "_", str(raw).lower()).strip("_") +def body_fingerprint(body: str) -> str: + """First 16 hex chars of the sha256 of the issue body, normalised + for line endings and surrounding whitespace. The fingerprint is + what a verdict note records, so a later lane can tell whether the + body changed without the timeline ever saying so (GitHub's REST + timeline exposes no `edited` event: see + https://docs.github.com/en/rest/using-the-rest-api/issue-event-types, + which lists no such event type).""" + text = str(body).replace("\r\n", "\n").strip() + return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16] + + def parse_note(body: str) -> dict | None: """{"state", "task"} for an agent note body, None for other comments. @@ -183,7 +208,8 @@ def parse_note(body: str) -> dict | None: (`**Pickup — queue task 20028**`). State is None when nothing recognisable is present; such a note never counts as a duplicate. A triage note that records a `verdict:`/`verdict=` field also - carries a normalised "verdict" key. + carries a normalised "verdict" key, and one that records a + `body_fp:`/`body_fp=` field carries a "body_fp" key. """ if not isinstance(body, str) or not _MARKER.search(body): return None @@ -208,16 +234,24 @@ def parse_note(body: str) -> dict | None: verdict = _norm_verdict(m_verdict.group(1)) if verdict: note["verdict"] = verdict + m_body_fp = _BODY_FP_RE.search(head) + if m_body_fp: + note["body_fp"] = m_body_fp.group(1).lower() return note -def note_header(task: str, state: str, verdict: str | None = None) -> str: +def note_header(task: str, state: str, verdict: str | None = None, + body: str | None = None) -> str: """Canonical first line for a lane's agent note, so later dedupe checks parse it exactly. A triage note passes its verdict so the - next lane's check can match it.""" + next lane's check can match it, and — when the issue body is + known — its body fingerprint, so a later lane can tell whether + the body changed since the verdict was recorded.""" header = f"" @@ -230,15 +264,20 @@ def _ts(value): # Timeline event -> the kind of issue change it proves, for verdict # freshness. `commented` is deliberately absent: comments are judged # from the comment list itself, where human vs bot is visible. -_TIMELINE_CHANGES = {"labeled": "label", "unlabeled": "label", "edited": "body"} +# There is deliberately no body entry here: GitHub's REST timeline +# exposes no `edited` event (see body_fingerprint), so body changes +# are detected by fingerprint, not from the timeline. +_TIMELINE_CHANGES = {"labeled": "label", "unlabeled": "label"} def changes_from_timeline(events: list) -> list: """[{"kind", "at"}] for the issue changes a verdict must not - outlive: a commit referenced on the issue, a label change, a body - edit. Input is REST timeline JSON (oldest first); a `referenced` - event only counts as a commit when it carries a commit_id (a - cross-reference from another issue is not one). + outlive: a commit referenced on the issue, a label change. Input + is REST timeline JSON (oldest first); a `referenced` event only + counts as a commit when it carries a commit_id (a cross-reference + from another issue is not one). Body edits are not in this list: + they are detected by comparing body fingerprints (see + _verdict_note_verdict), because the timeline never reports them. """ out = [] for e in events or []: @@ -270,14 +309,22 @@ def _is_verdict_request(state, verdict) -> bool: return state in VERDICT_STATES or _norm_state(state) in VERDICT_STATES -def _verdict_note_verdict(comments, state, verdict, changes, now) -> dict: +def _verdict_note_verdict(comments, state, verdict, changes, now, body=None) -> dict: """The verdict path of note_verdict (#12233 F2a): a triage verdict is skipped when the newest agent note already records the same verdict — for any task id, however long ago — and nothing has - changed since: no human comment, and no commit, label or body - change (from `changes`, see changes_from_timeline) after it. + changed since: no human comment, no commit or label change (from + `changes`, see changes_from_timeline) after it, and no body + change. Body changes are detected by fingerprint: `body` is the + issue's current body text, compared with the `body_fp` recorded + in the verdict note. When `body` is not supplied the fingerprint + check is skipped (the timeline cannot supply it); a recorded + verdict with no fingerprint cannot prove the body unchanged, so + with a current body supplied it posts once, and the new note + records a fingerprint. """ want = _verdict_key(state, verdict) + current_fp = body_fingerprint(body) if body is not None else None for c in reversed(comments or []): note = parse_note(c.get("body")) if note is None: @@ -299,6 +346,25 @@ def _verdict_note_verdict(comments, state, verdict, changes, now) -> dict: "post": True, "reason": f"newest recorded verdict is {have}, this is {want}", } + if current_fp is not None: + stored_fp = note.get("body_fp") + if stored_fp is None: + return { + "post": True, + "reason": ( + "the recorded verdict carries no body fingerprint, " + "so a body edit since the verdict cannot be ruled " + "out; re-triage once to record one" + ), + } + if stored_fp != current_fp: + return { + "post": True, + "reason": ( + "the issue body changed since the verdict " + f"(body fingerprint {stored_fp} -> {current_fp})" + ), + } since = _ts(c.get("created_at")) for ch in changes or (): if _ts(ch["at"]) > since: @@ -324,7 +390,8 @@ def _verdict_note_verdict(comments, state, verdict, changes, now) -> dict: def note_verdict( - comments: list, task: str, state: str, now=None, verdict=None, changes=() + comments: list, task: str, state: str, now=None, verdict=None, changes=(), + body=None, ) -> dict: """Should a note of `state` for queue `task` be posted, given the item's comments (oldest first, REST shape: body, created_at, @@ -332,14 +399,16 @@ def note_verdict( A triage verdict (state `triaged`, or any note with a `verdict`) takes the verdict path: `changes` is the issue's change list from - changes_from_timeline. Everything else takes the park path. + changes_from_timeline, and `body` is the issue's current body + text when known, fingerprinted against the verdict note (see + _verdict_note_verdict). Everything else takes the park path. """ now = _ts(now) if now is not None else datetime.now(timezone.utc) state = str(state).lower().replace("-", "_") task = str(task).lstrip("#") verdict = _norm_verdict(verdict) if verdict else None if _is_verdict_request(state, verdict): - return _verdict_note_verdict(comments, state, verdict, changes, now) + return _verdict_note_verdict(comments, state, verdict, changes, now, body) if state not in {s.replace("-", "_") for s in QUIET_STATES}: return {"post": True, "reason": f"progress state {state} always posts"} @@ -423,7 +492,14 @@ def main(argv=None, gh=_gh_json, now=None) -> int: f"repos/{args.repo}/issues/{args.issue}/comments?per_page=100" ) changes = () + body = None if _is_verdict_request(args.state, args.verdict): + # The issue body, for the verdict fingerprint: the + # timeline never reports body edits, so the verdict + # note records a fingerprint of the body it was + # triaged against, and this check compares it. + item = gh(f"repos/{args.repo}/issues/{args.issue}") + body = item.get("body") if isinstance(item, dict) else None timeline = gh( f"repos/{args.repo}/issues/{args.issue}/timeline?per_page=100" ) @@ -435,9 +511,10 @@ def main(argv=None, gh=_gh_json, now=None) -> int: now=now, verdict=args.verdict, changes=changes, + body=body, ) verdict["header"] = note_header( - args.task, args.state, verdict=args.verdict + args.task, args.state, verdict=args.verdict, body=body ) code = EXIT_GO if verdict["post"] else EXIT_STOP except ( diff --git a/pm-stack/lane-guard/test_lane_guard.py b/pm-stack/lane-guard/test_lane_guard.py index 7d94188bad..5f5c802551 100644 --- a/pm-stack/lane-guard/test_lane_guard.py +++ b/pm-stack/lane-guard/test_lane_guard.py @@ -61,15 +61,25 @@ def comment(body, minutes_ago, user_type="User"): ) PR_OPENED = "agent-note:v1\nstate: pr_opened\ntask: 20028\nlane: oc-code-04\n\nOpened PR #12100." # Triage verdict notes (#12233 F2a): the same verdict recorded by two -# different queue tasks, in the HTML and YAML shapes. +# different queue tasks, in the HTML and YAML shapes. Each records a +# fingerprint of the issue body it was triaged against (see +# body_fingerprint); ISSUE_BODY is that body. +ISSUE_BODY = "Triage me: still blocked on F12.4 (#1061).\n\nDetails here." HTML_TRIAGED = ( - "\n" - "Triaged: still blocked on F12.4 (#1061)." + lg.note_header("11111", "triaged", verdict="still_blocked", body=ISSUE_BODY) + + "\nTriaged: still blocked on F12.4 (#1061)." ) YAML_TRIAGED = ( - "agent-note:v1\nstate: triaged\ntask: 22222\nverdict: still_blocked\n\n" + "agent-note:v1\nstate: triaged\ntask: 22222\nverdict: still_blocked\n" + f"body_fp: {lg.body_fingerprint(ISSUE_BODY)}\n\n" "Verdict: still blocked on F12.4 (#1061)." ) +# A verdict note recorded before body fingerprints existed: no +# body_fp field, so a body edit since it cannot be ruled out. +HTML_TRIAGED_LEGACY = ( + "\n" + "Triaged: still blocked on F12.4 (#1061)." +) TRIAGED_NO_VERDICT = "agent-note:v1\nstate: triaged\ntask: 22222\n\nStill live." @@ -186,6 +196,32 @@ def test_canonical_header_with_verdict_round_trips(self): {"state": "triaged", "task": "20028", "verdict": "still_blocked"}, ) + def test_body_fingerprint_round_trips_in_header(self): + header = lg.note_header( + "20028", "triaged", verdict="still blocked", body=ISSUE_BODY + ) + parsed = lg.parse_note(header + "\nTriaged.") + self.assertEqual( + parsed, + { + "state": "triaged", + "task": "20028", + "verdict": "still_blocked", + "body_fp": lg.body_fingerprint(ISSUE_BODY), + }, + ) + + def test_body_fingerprint_is_stable(self): + # 16 hex chars; surrounding whitespace and CRLF do not change + # the fingerprint, so a trivial reformat does not re-triage. + fp = lg.body_fingerprint(ISSUE_BODY) + self.assertRegex(fp, r"^[0-9a-f]{16}$") + self.assertEqual(lg.body_fingerprint(" " + ISSUE_BODY + "\n\n"), fp) + self.assertEqual( + lg.body_fingerprint(ISSUE_BODY.replace("\n", "\r\n")), fp + ) + self.assertNotEqual(lg.body_fingerprint(ISSUE_BODY + " edited"), fp) + def test_plain_comment_is_not_a_note(self): self.assertIsNone(lg.parse_note("Looks good, ship it.")) self.assertIsNone(lg.parse_note(None)) @@ -265,9 +301,11 @@ class VerdictNote(unittest.TestCase): """#12233 F2a: a triage verdict is posted once per verdict per unchanged issue, across task ids.""" - def verdict(self, cs, task="99999", verdict="still_blocked", changes=()): + def verdict(self, cs, task="99999", verdict="still_blocked", changes=(), + body=ISSUE_BODY): return lg.note_verdict( - cs, task, "triaged", now=NOW, verdict=verdict, changes=changes + cs, task, "triaged", now=NOW, verdict=verdict, changes=changes, + body=body, ) def test_same_verdict_other_task_unchanged_issue_is_skipped(self): @@ -291,13 +329,34 @@ def test_new_commit_after_verdict_posts(self): self.assertTrue(v["post"]) self.assertIn("commit", v["reason"]) - def test_label_and_body_changes_after_verdict_post(self): - for kind in ("label", "body"): - with self.subTest(kind=kind): - changes = [{"kind": kind, "at": at(10)}] - v = self.verdict([comment(HTML_TRIAGED, 40)], changes=changes) - self.assertTrue(v["post"]) - self.assertIn(kind, v["reason"]) + def test_label_change_after_verdict_posts(self): + changes = [{"kind": "label", "at": at(10)}] + v = self.verdict([comment(HTML_TRIAGED, 40)], changes=changes) + self.assertTrue(v["post"]) + self.assertIn("label", v["reason"]) + + def test_body_edit_after_verdict_posts(self): + # The review finding: the timeline never reports body edits, + # so the fingerprint is the signal. A changed body re-opens + # the verdict even with no comment, label or commit since. + v = self.verdict( + [comment(HTML_TRIAGED, 40)], body=ISSUE_BODY + "\nEdited: new scope." + ) + self.assertTrue(v["post"]) + self.assertIn("body", v["reason"]) + + def test_body_unchanged_after_verdict_skips(self): + v = self.verdict([comment(HTML_TRIAGED, 40)], body=ISSUE_BODY) + self.assertFalse(v["post"]) + self.assertIn("duplicate verdict", v["reason"]) + + def test_verdict_without_body_fingerprint_posts_once(self): + # A legacy verdict note records no fingerprint, so a body + # edit since it cannot be ruled out: post once, and the new + # note (via the CLI header) records one. + v = self.verdict([comment(HTML_TRIAGED_LEGACY, 40)]) + self.assertTrue(v["post"]) + self.assertIn("fingerprint", v["reason"]) def test_change_before_the_verdict_does_not_reopen_it(self): changes = [{"kind": "commit", "at": at(50)}] @@ -348,12 +407,15 @@ def test_first_verdict_posts(self): class ChangesFromTimeline(unittest.TestCase): def test_maps_change_events(self): + # No `edited` event: GitHub's REST timeline exposes no such + # event type, so a body edit must never be expected here — + # it is detected by body fingerprint instead. events = [ {"event": "labeled", "created_at": at(50)}, {"event": "commented", "created_at": at(45)}, {"event": "referenced", "commit_id": "abc123", "created_at": at(40)}, {"event": "referenced", "created_at": at(35)}, # cross-ref, no commit - {"event": "edited", "created_at": at(30)}, + {"event": "edited", "created_at": at(30)}, # not a real timeline event {"event": "unlabeled", "created_at": at(25)}, {"event": "assigned", "created_at": at(20)}, ] @@ -362,7 +424,6 @@ def test_maps_change_events(self): [ {"kind": "label", "at": at(50)}, {"kind": "commit", "at": at(40)}, - {"kind": "body", "at": at(30)}, {"kind": "label", "at": at(25)}, ], ) @@ -428,7 +489,9 @@ def gh(path): seen.append(path) if "timeline" in path: return [] - return [comment(HTML_TRIAGED, 5)] + if "comments" in path: + return [comment(HTML_TRIAGED, 5)] + return {"body": ISSUE_BODY} code, out = self.run_cli( [ @@ -450,6 +513,7 @@ def gh(path): seen, [ "repos/o/r/issues/1062/comments?per_page=100", + "repos/o/r/issues/1062", "repos/o/r/issues/1062/timeline?per_page=100", ], ) @@ -457,7 +521,8 @@ def gh(path): self.assertFalse(out["post"]) self.assertEqual( out["header"], - "", + "", ) def test_note_cli_verdict_posts_after_a_commit(self): @@ -466,7 +531,9 @@ def gh(path): return [ {"event": "referenced", "commit_id": "abc123", "created_at": at(1)} ] - return [comment(HTML_TRIAGED, 5)] + if "comments" in path: + return [comment(HTML_TRIAGED, 5)] + return {"body": ISSUE_BODY} code, out = self.run_cli( [ @@ -488,6 +555,34 @@ def gh(path): self.assertTrue(out["post"]) self.assertIn("commit", out["reason"]) + def test_note_cli_verdict_posts_after_a_body_edit(self): + def gh(path): + if "timeline" in path: + return [] + if "comments" in path: + return [comment(HTML_TRIAGED, 5)] + return {"body": ISSUE_BODY + "\nEdited: new scope."} + + code, out = self.run_cli( + [ + "note", + "--repo", + "o/r", + "--issue", + "1062", + "--task", + "20028", + "--state", + "triaged", + "--verdict", + "still_blocked", + ], + gh=gh, + ) + self.assertEqual(code, lg.EXIT_GO) + self.assertTrue(out["post"]) + self.assertIn("body", out["reason"]) + def test_gh_failure_is_exit_2(self): def boom(path): raise RuntimeError("HTTP 502") From 2b49d80fa10de56950be2870c93bcf748746c20f Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 16:12:03 +0000 Subject: [PATCH 3/3] fix(pm-stack): stop verdict parsing at end of line; null body is empty Two follow-ups from the Codex review of the body-fingerprint fix: - The verdict regex's multi-word continuation used \s+, which crossed blank lines: a YAML note whose verdict was the last field swallowed the narrative below it into the verdict key (still_blocked_still_blocked_on_f12), so the next identical verdict posted again on an unchanged issue. Whitespace inside the verdict value is now horizontal only. - A body cleared to null was passed to the verdict check as None (body unavailable), so the fingerprint comparison was skipped and the identical verdict was suppressed despite the change. A fetched null body is now normalised to an empty string, so deletions invalidate the stored fingerprint and initially empty bodies still get one recorded. --- pm-stack/lane-guard/lane_guard.py | 26 +++++++--- pm-stack/lane-guard/test_lane_guard.py | 72 +++++++++++++++++++++++++- 2 files changed, 89 insertions(+), 9 deletions(-) diff --git a/pm-stack/lane-guard/lane_guard.py b/pm-stack/lane-guard/lane_guard.py index d6672f0ae0..d13b132034 100755 --- a/pm-stack/lane-guard/lane_guard.py +++ b/pm-stack/lane-guard/lane_guard.py @@ -144,12 +144,13 @@ def hold_verdict(item: dict) -> dict: # The recorded verdict of a triage note: `verdict: still_blocked` / # `verdict=still_blocked` in the header area. A short token, so two # lanes recording the same outcome produce the same key. The value is -# a run of words; a word followed by `=` or `:` ends it, so a later -# header field (`body_fp=...`, `task=...`) is never swallowed into -# the verdict — the old greedy `[\w -]*` did exactly that once -# `body_fp` followed the verdict. +# a run of words on ONE line: whitespace inside it is horizontal +# only, so a YAML note whose verdict is the last field never swallows +# the blank line and narrative below it into the verdict. A word +# followed by `=` or `:` ends the value, so a later header field +# (`body_fp=...`, `task=...`) is never swallowed into it either. _VERDICT_RE = re.compile( - r"\bverdict\s*[:=]\s*([A-Za-z0-9][\w-]*(?:\s+(?![\w-]+\s*[:=])[\w-]+)*)", + r"\bverdict[ \t]*[:=][ \t]*([A-Za-z0-9][\w-]*(?:[ \t]+(?![\w-]+\s*[:=])[\w-]+)*)", re.IGNORECASE, ) # The body fingerprint of a triage note: `body_fp: <16 hex>` / @@ -497,9 +498,20 @@ def main(argv=None, gh=_gh_json, now=None) -> int: # The issue body, for the verdict fingerprint: the # timeline never reports body edits, so the verdict # note records a fingerprint of the body it was - # triaged against, and this check compares it. + # triaged against, and this check compares it. A + # null body is a known-empty body, not an unknown + # one: normalise it to "" so clearing the body + # invalidates the stored fingerprint (and an + # initially empty body still gets one). None stays + # for a response that carries no body at all. item = gh(f"repos/{args.repo}/issues/{args.issue}") - body = item.get("body") if isinstance(item, dict) else None + body = None + if isinstance(item, dict): + # A null body is a known-empty body, not an + # unknown one: normalise it to "" so clearing the + # body invalidates the stored fingerprint (and an + # initially empty body still gets one). + body = item.get("body") or "" timeline = gh( f"repos/{args.repo}/issues/{args.issue}/timeline?per_page=100" ) diff --git a/pm-stack/lane-guard/test_lane_guard.py b/pm-stack/lane-guard/test_lane_guard.py index 5f5c802551..d4aba92a88 100644 --- a/pm-stack/lane-guard/test_lane_guard.py +++ b/pm-stack/lane-guard/test_lane_guard.py @@ -74,8 +74,14 @@ def comment(body, minutes_ago, user_type="User"): f"body_fp: {lg.body_fingerprint(ISSUE_BODY)}\n\n" "Verdict: still blocked on F12.4 (#1061)." ) -# A verdict note recorded before body fingerprints existed: no -# body_fp field, so a body edit since it cannot be ruled out. +# A YAML verdict note whose verdict is the last metadata field, +# followed by narrative: the verdict value must stop at the end of +# its line, not swallow the narrative below it into the verdict. +YAML_TRIAGED_VERDICT_LAST = ( + "agent-note:v1\nstate: triaged\ntask: 22222\n" + f"body_fp: {lg.body_fingerprint(ISSUE_BODY)}\nverdict: still_blocked\n\n" + "Still blocked on F12.4 (#1061)." +) HTML_TRIAGED_LEGACY = ( "\n" "Triaged: still blocked on F12.4 (#1061)." @@ -222,6 +228,19 @@ def test_body_fingerprint_is_stable(self): ) self.assertNotEqual(lg.body_fingerprint(ISSUE_BODY + " edited"), fp) + def test_verdict_value_stops_at_end_of_line(self): + # The verdict is the last metadata field; the narrative + # below it must not become part of the verdict key. + self.assertEqual( + lg.parse_note(YAML_TRIAGED_VERDICT_LAST), + { + "state": "triaged", + "task": "22222", + "verdict": "still_blocked", + "body_fp": lg.body_fingerprint(ISSUE_BODY), + }, + ) + def test_plain_comment_is_not_a_note(self): self.assertIsNone(lg.parse_note("Looks good, ship it.")) self.assertIsNone(lg.parse_note(None)) @@ -350,6 +369,20 @@ def test_body_unchanged_after_verdict_skips(self): self.assertFalse(v["post"]) self.assertIn("duplicate verdict", v["reason"]) + def test_verdict_last_field_still_dedupes(self): + # The verdict is the last metadata field with narrative + # below it; the unchanged issue still dedupes. + v = self.verdict([comment(YAML_TRIAGED_VERDICT_LAST, 40)]) + self.assertFalse(v["post"]) + self.assertIn("duplicate verdict", v["reason"]) + + def test_cleared_body_after_verdict_posts(self): + # A body cleared to null is a known-empty body, not an + # unknown one: it invalidates the stored fingerprint. + v = self.verdict([comment(HTML_TRIAGED, 40)], body="") + self.assertTrue(v["post"]) + self.assertIn("body", v["reason"]) + def test_verdict_without_body_fingerprint_posts_once(self): # A legacy verdict note records no fingerprint, so a body # edit since it cannot be ruled out: post once, and the new @@ -583,6 +616,41 @@ def gh(path): self.assertTrue(out["post"]) self.assertIn("body", out["reason"]) + def test_note_cli_verdict_posts_after_body_cleared(self): + def gh(path): + if "timeline" in path: + return [] + if "comments" in path: + return [comment(HTML_TRIAGED, 5)] + return {"body": None} + + code, out = self.run_cli( + [ + "note", + "--repo", + "o/r", + "--issue", + "1062", + "--task", + "20028", + "--state", + "triaged", + "--verdict", + "still_blocked", + ], + gh=gh, + ) + self.assertEqual(code, lg.EXIT_GO) + self.assertTrue(out["post"]) + self.assertIn("body", out["reason"]) + # A null body is known-empty: the new note still records a + # fingerprint, of the empty body. + self.assertEqual( + out["header"], + "", + ) + def test_gh_failure_is_exit_2(self): def boom(path): raise RuntimeError("HTTP 502")