classify.py

skills/pr-triage/scripts/classify.py239 lines, 9.5 KBView on GitHub
#!/usr/bin/env python3
"""Classify a pull-request wake-up for the pr-triage skill.

Reads the JSON from

    gh pr view <n> --json state,headRefOid,mergeStateStatus,mergeable,statusCheckRollup,reviews,comments

on stdin (or --file) and prints one line: `<class>: <reason>`, where class is
noise | ci-fail | rebase | finding | green | done. Priority when several apply:
done > rebase > ci-fail > finding > green > noise.

--last-handled STATE.json  skip events already handled (same head, comment, review, failed check)
--save STATE.json          write the current snapshot for the next wake (may be the same path)
--optional NAME            check that is not required (repeatable)
--json                     print the class, reason and every event as JSON

Stdlib only. Never calls the network.
"""
import argparse
import hashlib
import json
import re
import sys

# --- Bot lists: the one place to edit -------------------------------------------------
# Deploy-preview bots: their comments are noise unless they report a failed deployment.
DEPLOY_BOTS = {
    "vercel", "netlify", "cloudflare-pages", "cloudflare-workers-and-pages",
    "railway-app", "render", "fly-io", "pkg-pr-new",
}
# Summary bots: always noise. A blocking failure also shows up as a failing check.
SUMMARY_BOTS = {
    "codecov", "codecov-commenter", "changeset-bot", "sonarcloud", "sonarqubecloud",
    "dependabot", "dependabot-preview", "bundlewatch", "bundlemon", "relative-ci",
    "lighthouse-ci", "size-limit",
}
# Review bots: their comments and reviews are findings (named only for the reason text).
REVIEW_BOTS = {
    "coderabbitai", "greptile-apps", "macroscopeapp", "copilot-pull-request-reviewer",
    "copilot", "cursor", "claude",
}
# -------------------------------------------------------------------------------------

PREVIEW_BODY = re.compile(r"\[vc\]:|preview deployment (is )?(ready|updated)", re.I)
DEPLOY_WORDS = re.compile(r"\b(deploy(ment|ed|ing)?|preview)\b", re.I)
DEPLOY_FAILED = re.compile(
    r"(deploy(ment)?|build)\s+(has\s+)?(failed|errored)|\bfailed\b|\berror\b|❌|:x:", re.I
)
CHECK_FAIL = {"FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE", "ERROR"}
CHECK_OK = {"SUCCESS", "NEUTRAL", "SKIPPED"}
PRIORITY = ["done", "rebase", "ci-fail", "finding", "green", "noise"]


def login(obj):
    raw = ((obj or {}).get("author") or {}).get("login") or ""
    raw = raw.lower()
    if raw.startswith("app/"):
        raw = raw[4:]
    return raw[:-5] if raw.endswith("[bot]") else raw


def body_hash(body):
    return hashlib.sha1((body or "").encode("utf-8")).hexdigest()[:12]


def check_name(c):
    return c.get("name") or c.get("context") or "?"


def check_result(c):
    """Return 'fail', 'ok' or 'pending' for one statusCheckRollup entry."""
    typename = c.get("__typename")
    is_status = typename == "StatusContext" if typename else ("context" in c and "status" not in c)
    if is_status:
        state = (c.get("state") or "").upper()
        return "fail" if state in CHECK_FAIL else "ok" if state in CHECK_OK else "pending"
    if (c.get("status") or "").upper() != "COMPLETED":
        return "pending"
    concl = (c.get("conclusion") or "").upper()
    if concl in CHECK_FAIL:
        return "fail"
    return "ok" if concl in CHECK_OK or concl == "STALE" else "pending"


def classify_comment(c):
    """Return (class, reason) for one issue comment, ignoring handled-state."""
    who = login(c)
    body = c.get("body") or ""
    if c.get("viewerDidAuthor"):
        return "noise", f"own comment {c.get('id')}"
    if c.get("isMinimized"):
        return "noise", f"minimized comment by {who}"
    is_deploy = (
        who in DEPLOY_BOTS
        or PREVIEW_BODY.search(body)
        or (who == "github-actions" and DEPLOY_WORDS.search(body))
    )
    if is_deploy:
        if DEPLOY_FAILED.search(body):
            return "ci-fail", f"{who or 'deploy bot'} reports a failed deployment (comment {c.get('id')})"
        return "noise", f"deploy-preview comment by {who}"
    if who in SUMMARY_BOTS:
        return "noise", f"summary-bot comment by {who}"
    kind = "review bot" if who in REVIEW_BOTS else "comment"
    return "finding", f"{kind} {who} commented (comment {c.get('id')})"


def classify_review(r, head):
    who = login(r)
    oid = ((r.get("commit") or {}).get("oid")) or ""
    if oid and head and oid != head:
        return "noise", f"review by {who} on old commit {oid[:7]}"
    if (r.get("state") or "").upper() == "APPROVED" and not (r.get("body") or "").strip():
        return "noise", f"approval by {who}"
    if (r.get("state") or "").upper() in ("PENDING", "DISMISSED"):
        return "noise", f"{r.get('state').lower()} review by {who}"
    kind = "review bot" if who in REVIEW_BOTS else "review"
    return "finding", f"{kind} {who} {(r.get('state') or 'commented').lower()} (review {r.get('id')})"


def classify(pr, last=None, optional=()):
    """Return dict(cls, reason, events, snapshot)."""
    last = last or {}
    head = pr.get("headRefOid") or ""
    same_head = bool(head) and last.get("head") == head
    seen_comments = last.get("comments") or {}
    seen_reviews = set(last.get("reviews") or [])
    handled_fails = set(last.get("failed_checks") or []) if same_head else set()
    events = []

    def add(cls, reason):
        events.append({"class": cls, "reason": reason})

    state = (pr.get("state") or "").upper()
    if state in ("MERGED", "CLOSED"):
        add("done", f"PR {state.lower()}")

    merge_state = (pr.get("mergeStateStatus") or "").upper()
    if merge_state in ("BEHIND", "DIRTY") or (pr.get("mergeable") or "").upper() == "CONFLICTING":
        add("rebase", f"mergeStateStatus {merge_state or '?'}, mergeable {pr.get('mergeable') or '?'}")

    checks = [c for c in (pr.get("statusCheckRollup") or []) if check_name(c) not in optional]
    results = {check_name(c): check_result(c) for c in checks}
    failed = sorted(n for n, r in results.items() if r == "fail")
    for name in failed:
        if name in handled_fails:
            add("noise", f"check {name} failure already handled on {head[:7]}")
        else:
            add("ci-fail", f"check {name} failed on {head[:7]}")

    comments_snapshot = {}
    for c in pr.get("comments") or []:
        cid = str(c.get("id"))
        digest = body_hash(c.get("body"))
        comments_snapshot[cid] = digest
        if seen_comments.get(cid) == digest:
            add("noise", f"comment {cid} already handled")
            continue
        add(*classify_comment(c))

    reviews_snapshot = []
    for r in pr.get("reviews") or []:
        rid = str(r.get("id"))
        reviews_snapshot.append(rid)
        if rid in seen_reviews:
            add("noise", f"review {rid} already handled")
            continue
        add(*classify_review(r, head))

    pending = sorted(n for n, r in results.items() if r == "pending")
    if not failed and not pending and state == "OPEN":
        if head and last.get("class") == "green" and last.get("green_head", last.get("head")) == head:
            add("noise", f"green on {head[:7]} already handled")
        else:
            add("green", (f"all {len(results)} checks passed" if results else "no checks reported")
                + f" (head {head})")
    elif pending:
        add("noise", f"{len(pending)} check(s) still running: {', '.join(pending)}")

    if not events:
        add("noise", "nothing new")
    top = min(events, key=lambda e: PRIORITY.index(e["class"]))
    same = [e["reason"] for e in events if e["class"] == top["class"]]
    snapshot = {
        "head": head,
        "class": top["class"],
        "comments": comments_snapshot,
        "reviews": reviews_snapshot,
        "failed_checks": failed,
    }
    if top["class"] == "green":
        snapshot["green_head"] = head  # merge gate: current headRefOid must equal this
    return {"class": top["class"], "reason": "; ".join(same), "events": events, "snapshot": snapshot}


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("--file", help="gh pr view JSON (default: stdin)")
    ap.add_argument("--last-handled", metavar="STATE", help="snapshot saved by a previous --save")
    ap.add_argument("--save", metavar="STATE", help="write this wake's snapshot here")
    ap.add_argument("--optional", action="append", default=[], metavar="NAME",
                    help="check name that is not required (repeatable)")
    ap.add_argument("--json", action="store_true", help="print full result as JSON")
    args = ap.parse_args(argv)

    try:
        if args.file:
            with open(args.file, encoding="utf-8") as f:
                raw = f.read()
        else:
            raw = sys.stdin.read()
        pr = json.loads(raw)
    except (OSError, ValueError) as e:
        print(f"error: cannot read PR JSON: {e}", file=sys.stderr)
        return 2
    last = None
    if args.last_handled:
        try:
            with open(args.last_handled, encoding="utf-8") as f:
                last = json.load(f)
        except FileNotFoundError:
            last = None
        except (OSError, ValueError) as e:
            print(f"error: cannot read state: {e}", file=sys.stderr)
            return 2

    result = classify(pr, last, set(args.optional))
    if args.save:
        with open(args.save, "w", encoding="utf-8") as f:
            json.dump(result["snapshot"], f, indent=2)
    if args.json:
        print(json.dumps({k: result[k] for k in ("class", "reason", "events")}, indent=2))
    else:
        print(f"{result['class']}: {result['reason']}")
    return 0


if __name__ == "__main__":
    sys.exit(main())