diff --git a/pm-stack/lane-guard/lane_guard.py b/pm-stack/lane-guard/lane_guard.py index 101152c361..d13b132034 100755 --- a/pm-stack/lane-guard/lane_guard.py +++ b/pm-stack/lane-guard/lane_guard.py @@ -27,17 +27,31 @@ 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, 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 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 import argparse +import hashlib import json import re import subprocess @@ -57,6 +71,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 +141,21 @@ 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. The value is +# 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[ \t]*[:=][ \t]*([A-Za-z0-9][\w-]*(?:[ \t]+(?![\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 = ( ( @@ -148,6 +181,24 @@ 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 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. @@ -157,6 +208,9 @@ 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, 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 @@ -175,13 +229,31 @@ 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} - - -def note_header(task: str, state: str) -> str: + 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 + 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, + body: 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, 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"" def _ts(value): @@ -190,14 +262,154 @@ 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. +# 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. 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 []: + 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, 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, 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: + 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}", + } + 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: + 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=(), + 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, 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, 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, body) if state not in {s.replace("-", "_") for s in QUIET_STATES}: return {"post": True, "reason": f"progress state {state} always posts"} @@ -262,6 +474,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 +492,42 @@ 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 = () + 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. 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 = 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" + ) + changes = changes_from_timeline(timeline) + verdict = note_verdict( + comments, + args.task, + args.state, + now=now, + verdict=args.verdict, + changes=changes, + body=body, + ) + verdict["header"] = note_header( + args.task, args.state, verdict=args.verdict, body=body + ) 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..d4aba92a88 100644 --- a/pm-stack/lane-guard/test_lane_guard.py +++ b/pm-stack/lane-guard/test_lane_guard.py @@ -60,6 +60,37 @@ 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. 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 = ( + 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" + f"body_fp: {lg.body_fingerprint(ISSUE_BODY)}\n\n" + "Verdict: still blocked on F12.4 (#1061)." +) +# 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)." +) +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 +186,61 @@ 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_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_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)) @@ -230,6 +316,156 @@ 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=(), + body=ISSUE_BODY): + return lg.note_verdict( + cs, task, "triaged", now=NOW, verdict=verdict, changes=changes, + body=body, + ) + + 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_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_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 + # 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)}] + 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): + # 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)}, # not a real timeline event + {"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": "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 +515,142 @@ 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 [] + if "comments" in path: + return [comment(HTML_TRIAGED, 5)] + return {"body": ISSUE_BODY} + + 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", + "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)} + ] + if "comments" in path: + return [comment(HTML_TRIAGED, 5)] + return {"body": ISSUE_BODY} + + 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_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_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")