Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
271 changes: 262 additions & 9 deletions pm-stack/lane-guard/lane_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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 = (
(
Expand All @@ -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.

Expand All @@ -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
Expand All @@ -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"<!-- agent-note:v1 state={state} task={str(task).lstrip('#')} -->"
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"<!-- agent-note:v1 state={state} task={str(task).lstrip('#')}"
if verdict:
header += f" verdict={_norm_verdict(verdict)}"
if body is not None:
header += f" body_fp={body_fingerprint(body)}"
return header + " -->"


def _ts(value):
Expand All @@ -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"}

Expand Down Expand Up @@ -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:
Expand All @@ -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,
Expand Down
Loading