From 0b15e4bac991d6a664d20b6209378837fec900f0 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Fri, 23 Oct 2026 11:10:07 -0700 Subject: [PATCH 01/22] Add Copilot Review Adapter with JSON Vocabulary Read a reviewer body into a small typed result: coverage, refusal kind, finding counts by section, verdict class, headline, and the file table. Every spelling the reader matches lives in scripts/reviewers/.json, so a Copilot wording change is a data edit plus one fixture. The body is parsed with markdown-it-py, and an unrecognized shape returns unknown fields and a note rather than raising. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 5 + scripts/pr_review_copilot.py | 557 ++++++++++++++++++++++++++++++ scripts/reviewers/coderabbit.json | 26 ++ scripts/reviewers/copilot.json | 45 +++ scripts/reviewers/qodo.json | 23 ++ 5 files changed, 656 insertions(+) create mode 100755 scripts/pr_review_copilot.py create mode 100644 scripts/reviewers/coderabbit.json create mode 100644 scripts/reviewers/copilot.json create mode 100644 scripts/reviewers/qodo.json diff --git a/pyproject.toml b/pyproject.toml index cb14a2137..771b2b5fd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,6 +16,11 @@ files = ["spec", "host-setup", "scripts", "tests"] mypy_path = [".github/actions/prose-gate", ".github/actions/python-directories", ".github/actions/repo-gate"] exclude = 'scripts/(prose_lint|repo_gate)\.py' +# The review scripts declare markdown-it-py inline, and a type check run with no environment of its own does not install it. +[[tool.mypy.overrides]] +module = ["markdown_it", "markdown_it.*"] +ignore_missing_imports = true + [tool.pyright] pythonVersion = "3.13" # Matches [tool.mypy]'s platform pin above, for the same reason: Pylance in an editor otherwise flags the same POSIX-only attributes live on a Windows or macOS host. diff --git a/scripts/pr_review_copilot.py b/scripts/pr_review_copilot.py new file mode 100755 index 000000000..e3cdf79c8 --- /dev/null +++ b/scripts/pr_review_copilot.py @@ -0,0 +1,557 @@ +#!/usr/bin/env python3 +# /// script +# requires-python = ">=3.13" +# dependencies = ["markdown-it-py>=4"] +# /// +"""Read one reviewer's body into the small typed result the gate in `pr_review.py` decides on. + +The reviewer's wording and layout change without notice and with no programmatic API, so every +spelling this reads lives in `reviewers/.json` rather than here. A changed spelling is a +data edit plus one fixture. A body this cannot place returns `unknown` fields and a one-line note, +and `read` never raises, so a new shape reaches the digest as a note rather than the gate as a +crash. + +The body is parsed with markdown-it-py, so a code span, a fence, or an indented block is a token +of its own and never reads as markup. Only Copilot's current overview format, the one carrying the +`ccr-overview-v2` marker, is read. A Copilot body in any other layout reads as a note. + +Usage: pr_review_copilot.py [--help] [REVIEWER] < BODY +Prints the reading of the body on standard input, `copilot` by default. +""" + +from __future__ import annotations + +import functools +import json +import re +import sys +import unicodedata +from pathlib import Path +from typing import NamedTuple + +from markdown_it import MarkdownIt +from markdown_it.token import Token + +VOCABULARY = Path(__file__).resolve().parent / "reviewers" +REVIEWERS = ("copilot", "coderabbit", "qodo") +COVERAGE = ("full", "partial", "none", "unknown") +REFUSALS = ("none", "quota", "file_count", "error", "unknown") +VERDICTS = ("clean", "flagging", "unknown") +KINDS = ("open", "suppressed", "previously_missed") +# Every key a vocabulary file carries, and the shape each value takes. +# A test holds each file to this, so a key the reader uses cannot be missing from one. +KEYS = { + "login": str, + "vetted": bool, + "format_marker": str, + "comment_heading": str, + "refusal_openings": list, + "refusal_kinds": dict, + "rate_limit": list, + "verdicts": dict, + "headings": list, + "sections": dict, + "closed_badges": list, + "labels": list, + "finding_lists": list, + "effort": str, + "table_header": str, + "discussion_link": str, +} + +# The machine-readable coverage marker the fleet's own review instructions ask the reviewer for. +FLEET_REVIEW = re.compile( + r"", re.IGNORECASE +) +TAG = re.compile(r"<(/?)(details|summary)(?=[\s/>])[^>]*>", re.IGNORECASE) +ANY_TAG = re.compile(r"<[^<>]*>") +# A severity badge is a `picture` whose only text is its `img` alt, kept so a printed finding says it. +BADGE = re.compile( + r"", + re.DOTALL | re.IGNORECASE, +) +# A count longer than this is an identifier rather than anything a review states. +COUNT_DIGITS = 4 + +PARSER = MarkdownIt("commonmark").enable("table") + + +class Section(NamedTuple): + """One counted section: its kind, the count its label states, its title, and its text.""" + + kind: str + findings: int + title: str + text: str + + +class Reading(NamedTuple): + """What one body says, in the fields the gate reads. + + `open` is the count of open findings the body states, None where it states none. `unthreaded` + is how many findings it names that no thread on the pull request carries. `table` is the + paths the body's file table names, None where it carries no table. + """ + + coverage: str = "unknown" + coverage_line: str = "" + refusal: str = "unknown" + verdict: str = "unknown" + verdict_heading: str = "" + headline: str = "" + effort: str = "unknown" + effort_source: str = "unknown" + open: int | None = None + entries: int = 0 + unthreaded: int = 0 + sections: tuple[Section, ...] = () + table: tuple[str, ...] | None = None + rate_limited: str | None = None + marked: bool = False + notes: tuple[str, ...] = () + + def held(self, kind: str) -> int: + """The findings this body holds in sections of `kind`, by the counts their labels state.""" + return sum(s.findings for s in self.sections if s.kind == kind) + + @property + def counts(self) -> dict[str, int]: + """The findings by section: threaded, suppressed, and previously missed.""" + return { + "threaded": self.open or 0, + "suppressed": self.held("suppressed"), + "previously_missed": self.held("previously_missed"), + } + + +def load(name: str) -> dict: + """The vocabulary in `reviewers/.json`.""" + return json.loads((VOCABULARY / f"{name}.json").read_text(encoding="utf-8")) + + +def compiled(vocabulary: dict) -> dict: + """The vocabulary with every pattern compiled, case-insensitively, so a typo fails at import.""" + + def each(patterns: list[str]) -> list[re.Pattern[str]]: + return [re.compile(p, re.IGNORECASE) for p in patterns] + + return { + **vocabulary, + "refusal_openings": each(vocabulary["refusal_openings"]), + "refusal_kinds": {k: each(v) for k, v in vocabulary["refusal_kinds"].items()}, + "rate_limit": each(vocabulary["rate_limit"]), + "verdicts": {k: each(v) for k, v in vocabulary["verdicts"].items()}, + "headings": each(vocabulary["headings"]), + "sections": {k: each(v) for k, v in vocabulary["sections"].items()}, + "closed_badges": each(vocabulary["closed_badges"]), + "labels": each([re.escape(x) for x in vocabulary["labels"]]), + "finding_lists": each([re.escape(x) for x in vocabulary["finding_lists"]]), + "comment_heading": re.compile(vocabulary["comment_heading"] or r"(?!)", re.IGNORECASE), + "effort": re.compile(vocabulary["effort"] or r"(?!)", re.IGNORECASE), + "discussion_link": re.compile(vocabulary["discussion_link"] or r"(?!)"), + } + + +VOCABULARIES = {name: compiled(load(name)) for name in REVIEWERS} +LOGINS = {v["login"]: name for name, v in VOCABULARIES.items()} + + +def label(text: str) -> str: + """Text as the vocabulary matches it: tags, emphasis, and non-ASCII dropped, lower case.""" + text = ANY_TAG.sub(" ", text) + text = "".join(c for c in text if c.isascii()) + text = re.sub(r"[*_`]", "", text) + return " ".join(text.split()).lower() + + +def plain(text: str) -> str: + """Raw source as a person reads it, badges reduced to their alt text and other tags dropped.""" + text = BADGE.sub(lambda m: f"[{m.group(1) or m.group(2)}]", text) + text = ANY_TAG.sub("", text) + return text + + +def matched(patterns: list[re.Pattern[str]], text: str) -> re.Match[str] | None: + """The first pattern that matches the whole of `text`.""" + return next((m for p in patterns if (m := p.fullmatch(text))), None) + + +def stated(match: re.Match[str]) -> int: + """The count a matched label states: its `n` group, zero for a spelled none, one without one.""" + value = match.groupdict().get("n") + if value is None: + return 1 + if value.isdigit(): + return int(value) if len(value) <= COUNT_DIGITS else 0 + return 0 + + +class _Details: + """One `
` element as the token stream places it, in source lines.""" + + def __init__(self, parent: _Details | None, start: int) -> None: + self.parent = parent + self.start = start + self.summary: str | None = None + self.body = start + 1 + self.end: int | None = None + + +def details(tokens: list[Token]) -> list[_Details]: + """Every `
` element in the body, outermost first, with its summary and line range. + + A tag is read only from HTML tokens, so one quoted in a code span or a fence is text. A tag in + an inline token is placed by its block's first line plus the line breaks before it. + """ + stack: list[_Details] = [] + found: list[_Details] = [] + collecting: list[str] | None = None + + def feed(raw: str, line0: int) -> None: + nonlocal collecting + pos = 0 + for m in TAG.finditer(raw): + line = line0 + raw.count("\n", 0, m.start()) + if collecting is not None: + collecting.append(raw[pos : m.start()]) + closing, name = m.group(1), m.group(2).lower() + if name == "details" and not closing: + node = _Details(stack[-1] if stack else None, line) + stack.append(node) + found.append(node) + elif name == "details": + if stack: + stack.pop().end = line + elif not closing: + collecting = [] + else: + if collecting is not None and stack and stack[-1].summary is None: + stack[-1].summary = "".join(collecting) + stack[-1].body = line + 1 + collecting = None + pos = m.end() + if collecting is not None: + collecting.append(raw[pos:]) + + for token in tokens: + line0 = (token.map or [0])[0] + if token.type == "html_block": + feed(token.content, line0) + elif token.type == "inline": + breaks = 0 + for child in token.children or []: + if child.type in ("softbreak", "hardbreak"): + breaks += 1 + if child.type == "html_inline": + feed(child.content, line0 + breaks) + elif collecting is not None: + collecting.append(child.content or " ") + return found + + +def inline_text(token: Token) -> str: + """The text an inline token renders, code spans included, markup dropped.""" + parts = [] + for child in token.children or []: + if child.type in ("text", "code_inline"): + parts.append(child.content) + elif child.type in ("softbreak", "hardbreak"): + parts.append(" ") + return "".join(parts) + + +def paths(token: Token) -> list[str]: + """The paths a file table cell names: its code spans, or its whole text where it has none.""" + spans = [c.content for c in token.children or [] if c.type == "code_inline"] + named = spans or [inline_text(token)] + return [ + cleaned + for raw in named + if (cleaned := "".join(c for c in raw if unicodedata.category(c) != "Cf").strip()) + ] + + +def read(body: str, reviewer: str = "copilot", threads: tuple[str, ...] | None = None) -> Reading: + """The reading of one body by `reviewer`'s vocabulary, never raising. + + `threads` is the database id of each thread's first comment on the pull request, which an + open entry's link names. None counts every linked entry as threaded. + """ + try: + return _read(body or "", reviewer, threads) + # A shape the reader trips on is a note in the digest, never a crash in the gate. + except Exception as exc: # noqa: BLE001 + return Reading(notes=(f"the reader failed on this body ({type(exc).__name__})",)) + + +@functools.lru_cache(maxsize=512) +def _read(body: str, reviewer: str, threads: tuple[str, ...] | None) -> Reading: + vocab = VOCABULARIES[reviewer] + text = body.replace("\r\n", "\n") + lines = text.split("\n") + tokens = PARSER.parse(text) + notes: list[str] = [] + html = [t.content for t in tokens if t.type == "html_block"] + [ + c.content + for t in tokens + if t.type == "inline" + for c in t.children or [] + if c.type == "html_inline" + ] + marked = bool(vocab["format_marker"]) and any( + re.search(rf"", h) for h in html + ) + rate_limited = next( + (m.groupdict().get("service") or "" for p in vocab["rate_limit"] if (m := p.search(text))), + None, + ) + + refusal = "none" + first = next((t for t in tokens if t.type == "inline"), None) + if first is not None and any(p.search(first.content) for p in vocab["refusal_openings"]): + refusal = next( + (k for k, ps in vocab["refusal_kinds"].items() if any(p.search(text) for p in ps)), + "unknown", + ) + return Reading(refusal=refusal, coverage="none", marked=marked) + + coverage, coverage_line = "none", "" + rank = {"full": 0, "partial": 1, "unknown": 2} + for h in html: + for m in FLEET_REVIEW.finditer(h): + got, of = m.group(1), m.group(2) + if len(got) > COUNT_DIGITS or len(of) > COUNT_DIGITS or int(got) > int(of): + state = "unknown" + else: + state = "full" if got == of else "partial" + if coverage == "none" or rank[state] > rank[coverage]: + coverage, coverage_line = state, m.group(0) + + if vocab["vetted"] and vocab["format_marker"]: + if not text.strip(): + notes.append("the body is empty") + elif not marked: + notes.append( + f"the body carries no `` marker, the one format " + "this reader reads" + ) + + found = details(tokens) + sections: list[Section] = [] + claimed: list[tuple[int, int]] = [] + open_count: int | None = None + entries = linked = 0 + for node in found: + end = node.end if node.end is not None else len(lines) + if any(a <= node.start < b for a, b in claimed): + continue + summary = node.summary or "" + name = label(summary) + kind, match = next( + ((k, m) for k, ps in vocab["sections"].items() if (m := matched(ps, name))), + ("", None), + ) + if match is None: + if vocab["vetted"] and node.parent is None: + notes.append(f"a collapsed section this reader has no spelling for: `{name}`") + continue + claimed.append((node.start, end + 1)) + if kind == "vetted" or any(p.search(summary) for p in vocab["closed_badges"]): + continue + count = stated(match) + content = "\n".join( + ln.rstrip() + for raw in lines[node.body : end] + if (ln := plain(re.sub(r"^\s*(?:>\s?)+", "", raw))).strip() + ) + sections.append(Section(kind, count, " ".join(plain(summary).split()), content)) + if kind == "open": + open_count = (open_count or 0) + count + got, links = entries_in(tokens, node.body, end, found, vocab) + entries += got + linked += sum( + 1 for ids in links if ids and (threads is None or set(ids) & set(threads)) + ) + + verdict, verdict_heading, headline = "unknown", "", "" + effort, effort_source = "unknown", "unknown" + table: list[str] | None = None + listed = 0 + + def inside(token: Token) -> bool: + return any(a <= (token.map or [0])[0] < b for a, b in claimed) + + i = 0 + while i < len(tokens): + token = tokens[i] + if token.type == "heading_open" and not inside(token): + name = label(tokens[i + 1].content) + kind = next((k for k, ps in vocab["verdicts"].items() if matched(ps, name)), "") + if kind and verdict == "unknown": + verdict, verdict_heading = kind, name + headline = headline_after(tokens, i + 3, lines) + elif not kind and vocab["vetted"] and not matched(vocab["headings"], name): + notes.append(f"a heading this reader has no spelling for: `{name}`") + elif token.type == "paragraph_open": + inline = tokens[i + 1] + name = label(inline_text(inline)) + effort_match = vocab["effort"].fullmatch(name) + if effort_match: + level = effort_match.group("default") or effort_match.group("level") + effort = level.lower() + effort_source = "default" if effort_match.group("default") else "explicit" + elif not inside(token) and ( + found_kind := next( + ((k, m) for k, ps in vocab["sections"].items() if (m := matched(ps, name))), + None, + ) + ): + if found_kind[0] == "open": + open_count = (open_count or 0) + stated(found_kind[1]) + elif matched(vocab["finding_lists"], name): + listed += items_after(tokens, i + 3) + elif vocab["vetted"] and is_label(inline) and not matched(vocab["labels"], name): + notes.append(f"a label this reader has no spelling for: `{name}`") + elif token.type == "table_open" and vocab["table_header"]: + table = (table or []) + table_paths(tokens, i, vocab["table_header"]) + i += 1 + + named = max(open_count or 0, listed) + return Reading( + coverage=coverage, + coverage_line=coverage_line, + refusal=refusal, + verdict=verdict, + verdict_heading=verdict_heading, + headline=headline, + effort=effort, + effort_source=effort_source, + open=open_count, + entries=entries, + unthreaded=max(named - linked, 0), + sections=tuple(sections), + table=tuple(table) if table is not None else None, + rate_limited=rate_limited, + marked=marked, + notes=tuple(dict.fromkeys(notes)), + ) + + +def entries_in( + tokens: list[Token], start: int, end: int, found: list[_Details], vocab: dict +) -> tuple[int, list[list[str]]]: + """The entries at a section's margin and the thread ids each one links. + + An entry is a list item at the shallowest level in the section, outside any `
` + nested in it, so a back-reference inside an entry or a collapsed list is not one. + """ + nested = [(d.start, d.end or end) for d in found if start <= d.start < end] + items = [ + (n, t) + for n, t in enumerate(tokens) + if t.type == "list_item_open" + and t.map + and start <= t.map[0] < end + and not any(a <= t.map[0] <= b for a, b in nested) + ] + if not items: + return 0, [] + margin = min(t.level for _, t in items) + links = [] + for n, t in items: + if t.level != margin: + continue + ids = [] + for inner in tokens[n + 1 :]: + if inner.type == "list_item_close" and inner.level == margin: + break + for child in inner.children or []: + href = str(child.attrs.get("href", "")) if child.type == "link_open" else "" + if m := vocab["discussion_link"].search(href): + ids.append(m.group("id")) + links.append(ids) + return len(links), links + + +def headline_after(tokens: list[Token], start: int, lines: list[str]) -> str: + """The prose under a verdict heading, up to the next block that is not a plain paragraph.""" + said = [] + i = start + while i < len(tokens) and tokens[i].type == "paragraph_open" and tokens[i].level == 0: + inline = tokens[i + 1] + if is_label(inline) or (inline.children and inline.children[0].type == "strong_open"): + break + a, b = tokens[i].map or (0, 0) + said.append(" ".join(" ".join(lines[a:b]).split())) + i += 3 + return " ".join(said) + + +def is_label(inline: Token) -> bool: + """Whether a paragraph is a label line, a short text ending on a colon.""" + text = inline_text(inline).strip() + return text.endswith(":") and len(text.split()) <= 5 + + +def items_after(tokens: list[Token], start: int) -> int: + """The items of the list that opens at `start`, counted at its own margin.""" + if start >= len(tokens) or tokens[start].type != "bullet_list_open": + return 0 + level = tokens[start].level + 1 + count = 0 + for token in tokens[start + 1 :]: + if token.type == "bullet_list_close" and token.level == level - 1: + break + if token.type == "list_item_open" and token.level == level: + count += 1 + return count + + +def table_paths(tokens: list[Token], start: int, header: str) -> list[str]: + """The paths in the first column of the table opening at `start`, where its header names one.""" + named: list[str] = [] + column = -1 + head = True + for token in tokens[start + 1 :]: + if token.type == "table_close": + break + if token.type == "tr_open": + column = -1 + elif token.type in ("th_open", "td_open"): + column += 1 + elif token.type == "tbody_open": + head = False + elif token.type == "inline" and column == 0: + if head and label(inline_text(token)) != header: + return [] + if not head: + named.extend(paths(token)) + return named + + +def html_lines(body: str) -> list[str]: + """Each line of raw HTML in the body, stripped, so a line quoted in code is never one.""" + return [ + line.strip() + for token in PARSER.parse((body or "").replace("\r\n", "\n")) + if token.type == "html_block" + for line in token.content.splitlines() + ] + + +def main(argv: list[str] | None = None) -> int: + args = sys.argv[1:] if argv is None else argv + if args and args[0] in ("-h", "--help"): + print(__doc__.strip()) + return 0 + if len(args) > 1 or (args and args[0] not in REVIEWERS): + print(f"pr_review_copilot.py: unrecognized argument: {args[-1]}", file=sys.stderr) + return 2 + reading = read(sys.stdin.read(), args[0] if args else "copilot") + print(json.dumps(reading._asdict(), indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/reviewers/coderabbit.json b/scripts/reviewers/coderabbit.json new file mode 100644 index 000000000..7c4e33f5e --- /dev/null +++ b/scripts/reviewers/coderabbit.json @@ -0,0 +1,26 @@ +{ + "login": "coderabbitai", + "vetted": false, + "format_marker": "", + "comment_heading": "", + "refusal_openings": [], + "refusal_kinds": {"quota": [], "error": [], "file_count": []}, + "rate_limit": [ + "auto-generated comment:\\s*rate limited by\\s*(?P\\S+?)\\s*-->", + "\\s*(?:\\s*)*
\\s*[^<\\n]*Action not completed\\s*\\s*Review rate limited\\." + ], + "verdicts": {"clean": [], "flagging": []}, + "headings": [], + "sections": { + "open": [], + "suppressed": [], + "previously_missed": ["outside diff range comments \\((?P\\d+)\\)"], + "vetted": [] + }, + "closed_badges": [], + "labels": [], + "finding_lists": [], + "effort": "", + "table_header": "", + "discussion_link": "" +} diff --git a/scripts/reviewers/copilot.json b/scripts/reviewers/copilot.json new file mode 100644 index 000000000..4ca11409d --- /dev/null +++ b/scripts/reviewers/copilot.json @@ -0,0 +1,45 @@ +{ + "login": "copilot-pull-request-reviewer", + "vetted": true, + "format_marker": "ccr-overview-v2", + "comment_heading": "", + "refusal_openings": ["wasn.t able to review", "was not able to review", "unable to review"], + "refusal_kinds": { + "quota": ["reached (?:their|its|his|her|your|my) quota limit"], + "error": ["encountered an error"], + "file_count": ["maximum number of files"] + }, + "rate_limit": [], + "verdicts": { + "clean": ["approval recommended", "ready to approve"], + "flagging": [ + "changes recommended", + "needs a closer look", + "not ready to approve", + "human review recommended" + ] + }, + "headings": ["copilot review overview"], + "sections": { + "open": ["(?P\\d+|no) open (?:findings?|issues?)", "open \\((?P\\d+)\\)"], + "suppressed": [ + "suppressed comments \\((?P\\d+)\\)", + "comments suppressed due to low confidence \\((?P\\d+)\\)" + ], + "previously_missed": [ + "previously missed \\((?P\\d+)\\)", + "(?P\\d+) previously missed (?:findings?|issues?)" + ], + "vetted": [ + "(?P\\d+) resolved since last review", + "resolved since last review \\((?P\\d+)\\)", + "what changed in this pr" + ] + }, + "closed_badges": [], + "labels": ["changes:", "review findings:", "findings:", "open findings remain:"], + "finding_lists": ["review findings:", "open findings remain:"], + "effort": "review effort(?: level)?:? *(?:default *\\( *(?Plite|balanced|max) *\\)|(?Plite|balanced|max))", + "table_header": "file", + "discussion_link": "#discussion_r(?P\\d+)$" +} diff --git a/scripts/reviewers/qodo.json b/scripts/reviewers/qodo.json new file mode 100644 index 000000000..afb27755e --- /dev/null +++ b/scripts/reviewers/qodo.json @@ -0,0 +1,23 @@ +{ + "login": "qodo-free-for-open-source-projects", + "vetted": false, + "format_marker": "", + "comment_heading": "

\\s*Code Review by Qodo\\s*

", + "refusal_openings": [], + "refusal_kinds": {"quota": [], "error": [], "file_count": []}, + "rate_limit": [], + "verdicts": {"clean": [], "flagging": []}, + "headings": [], + "sections": { + "open": ["\\d+\\. .+"], + "suppressed": [], + "previously_missed": [], + "vetted": [] + }, + "closed_badges": ["[^<]*(?:\u2713 Resolved|\u2717 Dismissed)[^<]*"], + "labels": [], + "finding_lists": [], + "effort": "", + "table_header": "", + "discussion_link": "" +} From 6853eb39f7c024796bfac05e247caeac9933d3db Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Fri, 23 Oct 2026 11:16:04 -0700 Subject: [PATCH 02/22] Split the Cleanup Command into pr_cleanup.py Move `cleanup` and `cleanup --sweep` with their queries into their own script and test module. `pr_review.py cleanup` forwards there, so the command lines the skills and the host-safety allow rule name keep working unchanged. Co-Authored-By: Claude Opus 5.5 --- scripts/pr_cleanup.py | 1239 +++++++++++++++++++++++++++++++ scripts/pr_review.py | 1219 +------------------------------ scripts/pr_review_copilot.py | 20 +- tests/test_cli_usage.py | 1 + tests/test_pr_cleanup.py | 1340 ++++++++++++++++++++++++++++++++++ tests/test_pr_review.py | 1318 +-------------------------------- 6 files changed, 2610 insertions(+), 2527 deletions(-) create mode 100755 scripts/pr_cleanup.py create mode 100755 tests/test_pr_cleanup.py diff --git a/scripts/pr_cleanup.py b/scripts/pr_cleanup.py new file mode 100755 index 000000000..d0eae7fdf --- /dev/null +++ b/scripts/pr_cleanup.py @@ -0,0 +1,1239 @@ +#!/usr/bin/env python3 +# /// script +# requires-python = ">=3.13" +# dependencies = ["markdown-it-py>=4"] +# /// +"""Delete a merged pull request's head branch, and sweep what interrupted sessions left behind. + +Usage: pr_cleanup.py NUMBER --repo OWNER/NAME [--checkout DIR] + pr_cleanup.py --sweep --repo OWNER/NAME --checkout DIR [--apply] [--min-age-hours H] + +`pr_review.py cleanup` forwards here, so a command line naming either script runs the same code. + +Delete a merged pull request's head branch, the verify-then-delete `drive-pr` and +`merge-and-release` prescribe, done here so it runs under the one allow rule the host-safety +installer registers for this script rather than as a hand-typed delete. That rule approves any +arguments, so every check lives here. It takes the pull request number, never a branch name, and +reads the branch from the pull request. It refuses unless the pull request is merged into `develop` +from a head in `--repo` itself, and the head branch is none of `develop`, `main`, or the default +branch read live. The owner is bound to `registry/repos.json`, and the repository must be +registered or a fork, by `handoff.py`'s own write-scope check. It refuses a branch any ruleset or +branch protection covers, since the write guard's per-branch check never sees a delete made in +here. It refuses a branch an open pull request in `--repo` has as its head or base, naming each. +The ref is read exactly, its tip is checked against the pull request's `headRefOid` before the +delete is sent, and the delete is confirmed by reading the ref back. The delete itself carries no +expected tip, so this is verify-then-delete rather than a compare-and-swap. With `--checkout +`, a local half follows a remote half that exited 0, on the pull request's own +branch and head commit. Every refusal is decided before anything is deleted, the remote branch +included. A re-check after the delete can still refuse when a concurrent session changed the branch +or a worktree in between. The output then names what already happened. A locked, dirty, or +mid-operation worktree refuses. So does a branch tip that is neither the merged head nor behind it. +So does a rebase or bisect paused on the branch in any worktree, the primary included. A worktree +entry whose directory is gone is removed. The primary leaves the merged branch before the remote +delete, and a failed checkout refuses. The local half removes the worktrees holding the branch. It +deletes the local branch only at the merged head or an ancestor of it, after a tip re-read shows it +unchanged. Then it fast-forwards the clone to current `develop`, never a reset, stash, or force. A +clone left behind is reported and does not fail the run. The clone must be a primary checkout whose +origin is `--repo`. + +`cleanup --sweep --checkout ` takes no pull request. It reports what is provably +finished, one `would-remove` or `keep ` line per worktree or branch, and removes it only +with `--apply`. The report fetches and prunes the remote-tracking refs of `origin` and writes +nothing else. An item must sit untouched for `--min-age-hours` (default 24) and be clean. A branch +is finished when a pull request from `--repo` merged it at its exact tip or past it. It is also +finished when `origin/develop` or `origin/main` contains it. A detached worktree is finished when +any `origin` ref contains its commit. For a merged develop pull request the sweep also deletes the +remote head branch through the same checks as `cleanup `. The report runs those checks and names +the result. The sweep never touches the primary checkout except to fast-forward a tracked-clean +`develop` to `origin/develop`, and the report names that step. Permanent branches, locked +worktrees, and worktrees mid-operation are never touched. + +Exit 0 = deleted and confirmed gone, or already gone, or a sweep that completed. Exit 1 = refused, +a moved tip naming both commits among them. Exit 2 = a read did not answer, a partial one included. +A delete or removal that could not be confirmed also exits 2, as does argparse's own usage error. +Exit 64 = the write scope could not be established or excludes the target, checked before the +registry and before any read. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +import sys +import time +from pathlib import Path +from typing import NamedTuple + +import gh_graphql as shared +import handoff +import pr_review as core + +Q_CLEANUP_TARGET = """ +query($o:String!,$r:String!,$n:Int!){ + repository(owner:$o,name:$r){ + defaultBranchRef{ name } + pullRequest(number:$n){ + merged baseRefName headRefName headRefOid headRepository{ nameWithOwner } } }} +""" +Q_CLEANUP_REF = """ +query($o:String!,$r:String!,$q:String!){ + repository(owner:$o,name:$r){ ref(qualifiedName:$q){ id target{ oid } } }} +""" +Q_CLEANUP_HEADS = """ +query($o:String!,$r:String!,$b:String!,$after:String){ + repository(owner:$o,name:$r){ + heads: pullRequests(states:OPEN,headRefName:$b,first:100,after:$after){ + pageInfo{ hasNextPage endCursor } nodes{ number headRepository{ nameWithOwner } } } }} +""" +Q_CLEANUP_BASES = """ +query($o:String!,$r:String!,$b:String!){ + repository(owner:$o,name:$r){ + bases: pullRequests(states:OPEN,baseRefName:$b,first:20){ totalCount nodes{ number } } }} +""" +Q_SWEEP_DEFAULT = """ +query($o:String!,$r:String!){ repository(owner:$o,name:$r){ defaultBranchRef{ name } }} +""" +Q_SWEEP_MERGED = """ +query($o:String!,$r:String!,$b:String!){ + repository(owner:$o,name:$r){ + merged: pullRequests(states:MERGED,headRefName:$b,first:50){ + totalCount nodes{ number baseRefName headRefOid headRepository{ nameWithOwner } } } }} +""" +M_DELETE_REF = """ +mutation($refId:ID!){ + deleteRef(input:{refId:$refId}){ clientMutationId }} +""" + + +class CleanupUnread(Exception): + """A read `cleanup` needed did not produce an answer, reported at exit 2.""" + + +def cleanup_read(query: str, **variables: object) -> dict: + """One GraphQL read for `cleanup`, raising rather than ending the run at exit 1. + + `gh_graphql` exits 1 on a failed read, which is `cleanup`'s refusal code, so a read that could + not answer would be reported as a refusal the caller can act on. + """ + try: + return shared.request(query, variables).data + except shared.GraphQLError as exc: + sys.stderr.write(exc.detail) + raise CleanupUnread(str(exc)) from exc + + +def cleanup_rest(path: str, what: str) -> object: + """One REST read for `cleanup`, retried, raising with its stderr where nothing parsed.""" + proc = core.reread(path, ".") + data = core.parsed_json(proc) + if data is None: + sys.stderr.write(proc.stderr) + raise CleanupUnread(f"the {what} read failed rc={proc.returncode} or printed no JSON") + return data + + +def cleanup_ref(owner: str, repo: str, branch: str) -> dict | None: + """The branch's ref node, or None where the branch does not exist. + + The read is by exact qualified name, so a branch sharing a suffix never answers for it. The + node id it returns goes straight to the delete, so no caller ever holds one to mistype. + """ + data = cleanup_read(Q_CLEANUP_REF, o=owner, r=repo, q=f"refs/heads/{branch}") + repository = data.get("repository") + if not isinstance(repository, dict): + raise CleanupUnread(f"{owner}/{repo} returned no repository for the ref read") + ref = repository.get("ref") + if ref is None: + return None + oid = (ref.get("target") or {}).get("oid") if isinstance(ref, dict) else None + if not isinstance(ref, dict) or not ref.get("id") or not oid: + raise CleanupUnread(f"the ref read for {branch!r} returned no id and tip: {ref!r}") + return ref + + +def branch_rules(owner: str, repo: str, branch: str) -> list[str]: + """What protects the branch, rulesets and classic protection alike, empty where nothing does. + + The branch travels inside a REST path, so a name that would change the path is not read, and + an unread rule set is never reported as no rules. + """ + if core.UNSAFE_REF.search(branch) or core.DOT_SEGMENT.search(branch): + raise CleanupUnread( + f"the head branch {branch!r} holds a character that changes a REST path, so the " + "rules applying to it cannot be read" + ) + rules = cleanup_rest(f"repos/{owner}/{repo}/rules/branches/{branch}", "branch rules") + if not isinstance(rules, list) or not all(isinstance(r, dict) for r in rules): + raise CleanupUnread(f"the branch rules read returned no list of rules: {rules!r}"[:400]) + found = [f"ruleset rule {r.get('type') or 'unnamed'}" for r in rules] + detail = cleanup_rest(f"repos/{owner}/{repo}/branches/{branch}", "branch protection") + protected = detail.get("protected") if isinstance(detail, dict) else None + if not isinstance(protected, bool): + raise CleanupUnread(f"the branch read returned no protected flag: {detail!r}"[:400]) + if protected: + found.append("branch protection") + return found + + +def in_repository(node: dict, owner: str, repo: str) -> bool: + """Whether a pull request's head lives in `owner/repo`, a fork's same-named branch being none.""" + name = (node.get("headRepository") or {}).get("nameWithOwner") or "" + return name.lower() == f"{owner}/{repo}".lower() + + +def local_heads(owner: str, repo: str, branch: str) -> list[object]: + """The number of each open pull request whose head is the branch in `owner/repo`. + + The connection also holds forks' pull requests on a same-named branch. So every page is read + and filtered to this repository's own before anything is decided, and a fork's is never + counted. A page that does not answer, or one that cannot be followed to the next, raises rather + than reading as no pull request. + """ + + def fetch(cursor: str | None) -> dict: + extra = {"after": cursor} if cursor else {} + return cleanup_read(Q_CLEANUP_HEADS, o=owner, r=repo, b=branch, **extra) + + numbers: list[object] = [] + try: + for parent in shared.walk(fetch, ("repository", "heads"), strict_page=True): + nodes = parent["heads"].get("nodes") + if not isinstance(nodes, list) or not all(isinstance(n, dict) for n in nodes): + raise CleanupUnread( + f"the open pull request read returned no heads list: {nodes!r}"[:400] + ) + numbers += [n.get("number") for n in nodes if in_repository(n, owner, repo)] + except shared.GraphQLError as exc: + raise CleanupUnread(str(exc)) from exc + return numbers + + +def branch_users(owner: str, repo: str, branch: str) -> list[str]: + """The open pull requests in this repository whose head or base is the branch. + + Deleting a branch closes every open pull request headed on it. It retargets or closes the ones + based on it, so each is named where one exists. Every head is read, per `local_heads`. A base + past the twenty read is counted rather than named, every one being this repository's own. An + unanswered read is never reported as no pull request. + """ + users = [f"#{number} (head)" for number in local_heads(owner, repo, branch)] + data = cleanup_read(Q_CLEANUP_BASES, o=owner, r=repo, b=branch) + repository = data.get("repository") + if not isinstance(repository, dict): + raise CleanupUnread(f"{owner}/{repo} returned no repository for the open pull request read") + found = repository.get("bases") + nodes = found.get("nodes") if isinstance(found, dict) else None + total = found.get("totalCount") if isinstance(found, dict) else None + if not isinstance(nodes, list) or not isinstance(total, int): + raise CleanupUnread(f"the open pull request read returned no bases list: {found!r}"[:400]) + users += [f"#{n.get('number')} (base)" for n in nodes if isinstance(n, dict)] + if total > len(nodes): + users.append(f"{total - len(nodes)} more with the branch as base") + return users + + +class CleanupPlan(NamedTuple): + branch: str + head: str + ref: dict | None + + +def cleanup_check(owner: str, repo: str, num: int) -> CleanupPlan: + """Every read-only check on pull request `num` and its remote branch, with no write. + + Raises `CleanupRefused` carrying the whole refusal text, and `CleanupUnread` on any + unanswered read. A branch anything protects is refused whatever that protection would allow. + The write guard's per-branch rule check never sees a delete made from inside this script. + """ + target = f"{owner}/{repo}" + data = cleanup_read(Q_CLEANUP_TARGET, o=owner, r=repo, n=num) + repository = data.get("repository") or {} + pr = repository.get("pullRequest") + default = (repository.get("defaultBranchRef") or {}).get("name") + if not isinstance(pr, dict) or not default: + raise CleanupUnread(f"{target} #{num} returned no pull request or no default branch") + branch = pr.get("headRefName") + head = pr.get("headRefOid") + if not branch or not head: + raise CleanupUnread(f"{target} #{num} returned no head branch or head commit") + head_repo = (pr.get("headRepository") or {}).get("nameWithOwner") or "" + refusals = [] + if pr.get("merged") is not True: + refusals.append("the pull request is not merged") + if pr.get("baseRefName") != "develop": + refusals.append(f"its base is {pr.get('baseRefName')!r}, not 'develop'") + if head_repo.lower() != target.lower(): + refusals.append(f"its head lives in {head_repo or 'no repository'}, not {target}") + if branch in ("develop", "main", default): + refusals.append(f"its head branch {branch!r} is a permanent branch") + if refusals: + raise CleanupRefused( + "REFUSED", f"nothing was deleted from {target} #{num}: {', and '.join(refusals)}" + ) + + ref = cleanup_ref(owner, repo, branch) + if ref is None: + return CleanupPlan(branch, head, None) + rules = branch_rules(owner, repo, branch) + if rules: + raise CleanupRefused( + "REFUSED", + f"nothing was deleted: {branch!r} on {target} is covered by " + f"{', '.join(rules)}, so its delete is the maintainer's call", + ) + users = branch_users(owner, repo, branch) + if users: + raise CleanupRefused( + "REFUSED", + f"nothing was deleted: open pull requests use {branch!r} on {target}, " + f"{', '.join(users)}, and deleting it would close or retarget them", + ) + tip = ref["target"]["oid"] + if tip != head: + raise CleanupRefused( + "TIP_MOVED", + f"nothing was deleted: {branch!r} on {target} is at {tip}, and #{num} merged " + f"{head}, so something reached the branch after the merge or the name was reused", + ) + return CleanupPlan(branch, head, ref) + + +def cleanup_fresh(owner: str, repo: str, plan: CleanupPlan) -> CleanupPlan: + """Read the remote branch again right before its delete, so the delete uses a fresh node id. + + The checks and the local preflight take time, and another session may have pushed since. + """ + if plan.ref is None: + return plan + ref = cleanup_ref(owner, repo, plan.branch) + if ref is None: + return CleanupPlan(plan.branch, plan.head, None) + tip = ref["target"]["oid"] + if tip != plan.head: + raise CleanupRefused( + "TIP_MOVED", + f"nothing was deleted: {plan.branch!r} on {owner}/{repo} is at {tip} just before " + f"its delete, and the pull request merged {plan.head}", + ) + return CleanupPlan(plan.branch, plan.head, ref) + + +def cleanup_remote_delete(owner: str, repo: str, plan: CleanupPlan) -> int: + """Delete the remote branch `plan` verified and read it back. + + A delete that reports a failure may still have landed, so the read back decides the outcome + either way. + """ + target = f"{owner}/{repo}" + branch = plan.branch + if plan.ref is None: + print(f"status=ALREADY_GONE branch={branch} is not on {target}, so nothing was deleted") + return 0 + tip = plan.ref["target"]["oid"] + print(f"deleting: {branch} on {target} at {tip}") + try: + response = shared.request(M_DELETE_REF, {"refId": plan.ref["id"]}).data + print(f" response: {json.dumps(response)[:400]}") + except shared.GraphQLError as exc: + print(f" the delete reported a failure: {exc}") + sys.stderr.write(exc.detail) + try: + after = cleanup_ref(owner, repo, branch) + except CleanupUnread as exc: + print( + f"status=DELETE_NOT_CONFIRMED the delete of {branch!r} on {target} was sent, and " + f"reading the ref back did not answer: {exc}" + ) + return 2 + if after is not None: + print( + f"status=DELETE_NOT_CONFIRMED {branch!r} on {target} still reads at " + f"{after['target']['oid']} after the delete" + ) + return 2 + print(f"status=DELETED branch={branch} oid={tip}, confirmed by reading the ref back") + return 0 + + +def _cleanup(owner: str, repo: str, num: int) -> int: + """The checks, the delete, and the read back, raising `CleanupUnread` on any unanswered read.""" + try: + plan = cleanup_check(owner, repo, num) + except CleanupRefused as exc: + print(f"status={exc.status} {exc}") + return 1 + return cleanup_remote_delete(owner, repo, plan) + + +def cleanup_scope(owner: str, repo: str) -> int | None: + """The exit code where the write scope refuses or cannot be established, else None.""" + ok, why = core.in_scope(owner) + if not ok: + print(f"status=OUT_OF_SCOPE nothing was deleted: {why}") + return 64 + try: + handoff.require_write_scope(argparse.Namespace(cmd="cleanup", repo=f"{owner}/{repo}")) + except handoff.Refusal as exc: + print(f"status=REFUSED nothing was deleted, refused by handoff.py's write scope: {exc}") + return 1 + except handoff.Execution as exc: + print(f"status=UNREAD nothing was deleted: {exc}") + return 2 + return None + + +def cleanup(owner: str, repo: str, num: int, checkout: str | None = None) -> int: + """Delete the head branch of merged pull request `num` once every check passes. + + Returns 0 where the branch is deleted and confirmed gone, or is already gone, and 1 on a + refusal. Returns 2 where a read did not answer or the delete could not be confirmed. Returns + 64 where the write scope `comment` and `reply` check excludes the target. Past that check, + the owner is bound to the fleet registry. The repository must be registered or a fork, by + `handoff.py`'s own write-scope check, reused rather than copied so the two cannot drift + apart. Its refusal text is printed as `handoff.py` words it. + + With `checkout`, the local half follows a remote half that exited 0. The checkout and every + local refusal are judged before the remote delete. A local refusal then means nothing at all + was deleted, the remote branch included. A re-check after the delete can still refuse when a + concurrent session changed the branch or a worktree. The output then names what happened. + """ + refused = cleanup_scope(owner, repo) + if refused is not None: + return refused + target = f"{owner}/{repo}" + primary = None + try: + if checkout is not None: + primary = cleanup_primary(checkout, target) + plan = cleanup_check(owner, repo, num) + if primary is not None: + cleanup_preflight(primary, plan.branch, plan.head) + cleanup_leave_branch(primary, plan.branch) + plan = cleanup_fresh(owner, repo, plan) + except CleanupRefused as exc: + if exc.status in ("REFUSED", "TIP_MOVED", "BAD_CHECKOUT"): + print(f"status={exc.status} {exc}") + else: + print(f"status={exc.status} nothing was deleted, remote branch included: {exc}") + return 1 + except CleanupUnread as exc: + print(f"status=UNREAD nothing was deleted: {exc}") + return 2 + code = cleanup_remote_delete(owner, repo, plan) + if code != 0 or primary is None: + return code + try: + return cleanup_local(primary, plan.branch, plan.head) + except CleanupRefused as exc: + print(f"status={exc.status} {exc}") + return 1 + except CleanupUnread as exc: + print(f"status=UNREAD the local half stopped: {exc}") + return 2 + + +ON_WINDOWS = os.name == "nt" + + +class CleanupRefused(Exception): + """A local check refused, carrying the `status=` name to print, reported at exit 1.""" + + def __init__(self, status: str, message: str) -> None: + super().__init__(message) + self.status = status + + +class Worktree(NamedTuple): + path: str + head: str + branch: str | None + locked: bool + prunable: bool + + +GITHUB_REMOTE = re.compile( + r"^(?:https?://(?:[^@/]+@)?github\.com/|ssh://[^@/]+@github\.com/|[^@/]+@github\.com:)" + r"([^/]+)/([^/]+?)(?:\.git)?/?$", + re.IGNORECASE, +) + + +def cleanup_git( + root: str, *args: str, ok: tuple[int, ...] = (0,) +) -> subprocess.CompletedProcess[str]: + """One git call in `root` as an argv list, raising with its stderr on an unexpected code. + + A return code the caller lists in `ok` is an answer it reads. Any other code is a call that + did not do what was asked, so it is shown and ends the step rather than swallowed. + """ + try: + proc = subprocess.run( + ["git", "-C", root, *args], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + timeout=300, + ) + except (OSError, subprocess.SubprocessError) as exc: + raise CleanupUnread(f"`git {' '.join(args)}` did not run: {exc}") from exc + if proc.returncode not in ok: + sys.stderr.write(proc.stderr) + raise CleanupUnread(f"`git {' '.join(args)}` failed rc={proc.returncode}") + return proc + + +def cleanup_primary(checkout: str, target: str) -> str: + """The real path of the primary checkout at `checkout`, refusing anything else. + + A linked worktree is refused, since removing worktrees and moving branches belongs to the + clone that owns them. So is an origin naming another repository, since every local step + here derives from a pull request in `target`. + """ + probe = cleanup_git( + checkout, + "rev-parse", + "--absolute-git-dir", + "--git-common-dir", + "--show-toplevel", + ok=(0, 128), + ) + lines = probe.stdout.splitlines() + if probe.returncode != 0 or len(lines) != 3: + raise CleanupRefused("BAD_CHECKOUT", f"{checkout!r} is not a git checkout with a work tree") + git_dir, common, top = lines + if os.path.realpath(git_dir) != os.path.realpath(os.path.join(checkout, common)): + raise CleanupRefused( + "BAD_CHECKOUT", f"{checkout!r} is a linked worktree, not a primary one" + ) + url = cleanup_git(top, "config", "--get", "remote.origin.url", ok=(0, 1)).stdout.strip() + found = GITHUB_REMOTE.match(url) + if found is None or f"{found[1]}/{found[2]}".lower() != target.lower(): + shown = re.sub(r"//[^/@]*@", "//", url) or "unset" + raise CleanupRefused("BAD_CHECKOUT", f"origin of {top} is {shown}, not {target}") + return os.path.realpath(top) + + +def cleanup_worktrees(primary: str) -> list[Worktree]: + """Every worktree git lists for the clone, the primary first.""" + out = cleanup_git(primary, "worktree", "list", "--porcelain").stdout + trees = [] + for block in out.split("\n\n"): + fields = dict(line.partition(" ")[::2] for line in block.splitlines()) + if "worktree" not in fields: + continue + branch = fields.get("branch") + trees.append( + Worktree( + path=os.path.realpath(fields["worktree"]), + head=fields.get("HEAD", ""), + branch=branch.removeprefix("refs/heads/") if branch else None, + locked="locked" in fields, + prunable="prunable" in fields, + ) + ) + return trees + + +def cleanup_tip(primary: str, ref: str) -> str | None: + """The commit `ref` names, or None where it does not exist.""" + proc = cleanup_git(primary, "rev-parse", "--verify", "--quiet", ref, ok=(0, 1)) + return proc.stdout.strip() or None + + +def cleanup_dirty(path: str, untracked: bool) -> bool: + """Whether the work tree at `path` has changes, without refreshing its index. + + `--no-optional-locks` keeps the read from rewriting the index, which would make an untouched + tree look touched to the age rule of `--sweep`. + """ + flag = "--untracked-files=all" if untracked else "--untracked-files=no" + out = cleanup_git(path, "--no-optional-locks", "status", "--porcelain", flag).stdout + return bool(out.strip()) + + +IN_PROGRESS = ( + "rebase-merge", + "rebase-apply", + "BISECT_LOG", + "MERGE_HEAD", + "CHERRY_PICK_HEAD", + "REVERT_HEAD", +) + + +def cleanup_admin(path: str) -> str | None: + """The git directory holding the worktree at `path`'s state, or None where unreadable. + + A linked worktree names it in its `.git` file, and a primary checkout's `.git` is it. + """ + if os.path.isdir(os.path.join(path, ".git")): + return os.path.join(path, ".git") + try: + text = Path(path, ".git").read_text(encoding="utf-8").strip() + except OSError: + return None + if not text.startswith("gitdir:"): + return None + return os.path.join(path, text.removeprefix("gitdir:").strip()) + + +def cleanup_in_progress(path: str) -> bool: + """Whether a rebase, bisect, merge, cherry-pick, or revert is paused in the worktree.""" + admin = cleanup_admin(path) + return admin is not None and any(os.path.exists(os.path.join(admin, n)) for n in IN_PROGRESS) + + +def cleanup_operation_names(path: str) -> set[str]: + """The branch names a rebase or bisect paused in the worktree at `path` is working on. + + Either detaches HEAD, so the worktree no longer lists the branch it will return to. + """ + admin = cleanup_admin(path) + names: set[str] = set() + if admin is None: + return names + for name in ("rebase-merge/head-name", "rebase-apply/head-name", "BISECT_START"): + try: + text = Path(admin, name).read_text(encoding="utf-8").strip() + except OSError: + continue + names.add(text.removeprefix("refs/heads/")) + return names + + +def cleanup_cwd_inside(path: str) -> bool: + """Whether this process's working directory is the worktree at `path` or inside it.""" + try: + here = os.path.realpath(os.getcwd()) + except OSError: + return False + return here == path or here.startswith(path + os.sep) + + +def cleanup_remove_worktree(primary: str, path: str) -> bool: + """Remove the worktree at `path` without force and read the list back for it. + + Returns whether this process was standing inside it. The process moves to the primary + checkout first. Windows cannot free a directory the parent shell holds, so callers refuse + there before the first removal. + """ + inside = cleanup_cwd_inside(path) + if inside: + os.chdir(primary) + try: + cleanup_git(primary, "worktree", "remove", path) + except CleanupUnread: + if any(w.path == path for w in cleanup_worktrees(primary)): + raise + if os.path.exists(path): + raise CleanupUnread(f"git failed to remove {path}, which is unlisted but still on disk") + print(f" git reported an error, yet {path} is no longer listed, so it is already gone") + return inside + if any(w.path == path for w in cleanup_worktrees(primary)): + raise CleanupUnread(f"the worktree {path} is still listed after its removal") + return inside + + +def cleanup_moved_note() -> None: + print(" note: the shell's directory was that worktree and is gone, so change directory") + + +def cleanup_delete_branch(primary: str, branch: str, tip: str) -> bool: + """Delete the local branch while it still names `tip`, and read it back. + + Returns whether this call deleted it, False where it was already gone. The tip is read again + just before the delete. Git's own refusal then covers a branch that is checked out, being + rebased, or being bisected in any worktree. It is raised as a refusal. + """ + ref = f"refs/heads/{branch}" + now = cleanup_tip(primary, ref) + if now is None: + return False + if now != tip: + raise CleanupRefused( + "LOCAL_TIP_MOVED", f"{ref} reads {now} just before its delete, and {tip} was expected" + ) + proc = cleanup_git(primary, "branch", "-D", "--", branch, ok=(0, 1)) + if proc.returncode != 0: + if cleanup_tip(primary, ref) is None: + return False + raise CleanupRefused("WORKTREE_KEPT", f"git kept {ref}: {proc.stderr.strip()}") + if cleanup_tip(primary, ref) is not None: + raise CleanupUnread(f"{ref} still exists after its delete") + return True + + +def cleanup_base(primary: str, apply: bool = True) -> bool: + """Fast-forward the primary checkout to current `develop`, never reset, stash, or force. + + Returns whether the clone is current, printing a status line for each way it is not. A clone + on another branch, with tracked changes, or that cannot fast-forward is left alone. No + outcome here is an error, so callers report it and never fail a run on it. Without `apply` + it only reports the fast-forward it would make. + """ + try: + current = cleanup_git(primary, "symbolic-ref", "--quiet", "--short", "HEAD", ok=(0, 1)) + on = current.stdout.strip() + if on != "develop": + print(f"keep base-not-on-develop {primary} is on {on or 'a detached head'}") + return False + if cleanup_dirty(primary, False): + print(f"status=BASE_DIRTY {primary} has tracked changes, so it was left where it is") + return False + behind = cleanup_git( + primary, "merge-base", "--is-ancestor", "HEAD", "origin/develop", ok=(0, 1) + ) + if behind.returncode == 1: + print(f"status=BASE_NOT_FF develop in {primary} cannot fast-forward to origin/develop") + return False + if not apply and cleanup_tip(primary, "HEAD") != cleanup_tip( + primary, "refs/remotes/origin/develop" + ): + print(f"would-fast-forward develop in {primary}") + return True + if apply: + try: + cleanup_git(primary, "merge", "--ff-only", "origin/develop") + except CleanupUnread: + if cleanup_tip(primary, "HEAD") != cleanup_tip( + primary, "refs/remotes/origin/develop" + ): + raise + except CleanupUnread as exc: + print(f"status=BASE_UNREAD develop in {primary} could not be brought current: {exc}") + return False + print(f" develop in {primary} is at origin/develop") + return True + + +def cleanup_behind(primary: str, tip: str, head: str) -> bool: + """Whether commit `tip` is an ancestor of `head`, so it holds nothing `head` lacks. + + A `head` object this clone lacks proves nothing, and reads as not behind. + """ + proc = cleanup_git(primary, "merge-base", "--is-ancestor", tip, head, ok=(0, 1, 128)) + return proc.returncode == 0 + + +def cleanup_preflight(primary: str, branch: str, head: str) -> tuple[str | None, list[Worktree]]: + """Fetch, then decide every local refusal, returning the branch tip and the worktrees to remove. + + Nothing is removed here, so a refusal leaves all of it in place. `head` is the commit the + merged pull request carried, read live by the remote half. + """ + cleanup_git(primary, "fetch", "--prune", "origin") + ref = f"refs/heads/{branch}" + tip = cleanup_tip(primary, ref) + if tip is not None and tip != head and not cleanup_behind(primary, tip, head): + raise CleanupRefused( + "LOCAL_TIP_MOVED", + f"{ref} is at {tip}, which is neither the merged head {head} nor behind it, " + "so it may carry commits that were never pushed", + ) + mirror = cleanup_tip(primary, f"refs/remotes/origin/{branch}") + if mirror is not None and mirror != head: + raise CleanupRefused( + "TIP_MOVED", + f"nothing was deleted: origin/{branch} is at {mirror}, and the pull request merged " + f"{head}, so something reached the branch after the merge", + ) + linked = [] + trees = cleanup_worktrees(primary) + others = [w for w in trees if w.path != primary] + for w in trees: + if not w.prunable and branch in cleanup_operation_names(w.path): + raise CleanupRefused( + "WORKTREE_KEPT", f"{w.path} has a rebase or bisect in progress on {branch!r}" + ) + holds = any(w.path == primary and w.branch == branch for w in cleanup_worktrees(primary)) + if holds and cleanup_in_progress(primary): + raise CleanupRefused( + "WORKTREE_KEPT", f"{primary} has a merge, cherry-pick, revert, or bisect in progress" + ) + if holds and cleanup_dirty(primary, False): + raise CleanupRefused( + "BASE_DIRTY", f"{primary} has {branch!r} checked out with tracked changes" + ) + for w in (w for w in others if w.branch == branch): + why = ( + "it is locked" + if w.locked + else "a rebase, bisect, merge, cherry-pick, or revert is in progress in it" + if cleanup_in_progress(w.path) + else "it holds submodules, which only git's own check may remove" + if os.path.exists(os.path.join(w.path, ".gitmodules")) + else "run from a directory outside it, such as the base clone" + if ON_WINDOWS and cleanup_cwd_inside(w.path) + else None + ) + if why is not None: + raise CleanupRefused("WORKTREE_KEPT", f"{w.path}, {why}") + if not w.prunable and cleanup_dirty(w.path, True): + raise CleanupRefused("WORKTREE_DIRTY", f"{w.path} has uncommitted changes") + linked.append(w) + return tip, linked + + +def cleanup_leave_branch(primary: str, branch: str) -> None: + """Move the primary checkout to `develop` where it holds `branch`, refusing if git will not. + + This runs before the remote delete, so a checkout that fails still deletes nothing. + """ + if not any(w.path == primary and w.branch == branch for w in cleanup_worktrees(primary)): + return + try: + cleanup_git(primary, "checkout", "develop") + except CleanupUnread as exc: + raise CleanupRefused( + "WORKTREE_KEPT", f"{primary} could not leave {branch}, so the branch was kept" + ) from exc + print(f" switched {primary} off {branch} to develop") + + +def cleanup_local(primary: str, branch: str, head: str) -> int: + """Remove the finished branch's worktrees and local branch, then return the base clone. + + The refusals are decided again before the first removal, so a refused run leaves all of it + in place. The base clone's return is reported and never fails the run. The local branch is + deleted only at `head` or an ancestor of it, after a tip re-read shows it unchanged. + """ + try: + tip, linked = cleanup_preflight(primary, branch, head) + except CleanupRefused as exc: + raise CleanupRefused(exc.status, f"nothing local was removed: {exc}") from exc + for w in linked: + moved = cleanup_remove_worktree(primary, w.path) + print(f" removed worktree {w.path}") + if moved: + cleanup_moved_note() + if tip is None: + print(f" local branch {branch} is already gone") + else: + try: + deleted = cleanup_delete_branch(primary, branch, tip) + except CleanupUnread as exc: + print(f"status=LOCAL_DELETE_NOT_CONFIRMED {exc}") + return 2 + if deleted: + print(f" deleted local branch {branch} at {tip}, confirmed by reading the ref back") + else: + print(f" local branch {branch} is already gone") + current = cleanup_base(primary) + try: + first = cleanup_git(primary, "status", "--short", "--branch").stdout.splitlines()[:1] + print(f" {first[0] if first else 'status unavailable'}") + except CleanupUnread: + print(" status unavailable") + try: + print(f" worktrees listed: {len(cleanup_worktrees(primary))}") + except CleanupUnread: + print(" worktrees listed: unavailable") + base = "current" if current else "kept" + print(f"status=CLEANED branch={branch} oid={head} locally, base={base}") + return 0 + + +class CleanupSweep: + """One pass over a clone's worktrees and local branches, removing what is provably finished. + + Nothing here is a failure unless a read did not answer or a removal could not be confirmed. + `problems` counts those, so the run continues with the other items and still exits 2. + """ + + def __init__(self, owner: str, repo: str, primary: str, apply: bool, min_age: float) -> None: + self.owner = owner + self.repo = repo + self.target = f"{owner}/{repo}" + self.primary = primary + self.apply = apply + self.min_age = min_age + self.problems = 0 + self.permanent = {"develop", "main"} + self.common = "" + self.operating: set[str] = set() + + def keep(self, reason: str, what: str) -> None: + print(f"keep {reason} {what}") + + def failed(self, what: str, exc: CleanupUnread) -> None: + self.problems += 1 + print(f"unread {what}: {exc}") + + def newest_hours(self, paths: list[str]) -> float: + """Hours since the newest mtime among `paths`, infinite where none can be read.""" + stamps = [] + for path in paths: + try: + stamps.append(os.stat(path).st_mtime) + except OSError: + continue + return float("inf") if not stamps else (time.time() - max(stamps)) / 3600 + + def worktree_hours(self, w: Worktree) -> float | None: + """The idle hours of a linked worktree, or None where its admin directory is unreadable. + + Taken before any status runs on it, and from the admin files git itself writes on use. + The directory's own mtime moves only when an entry is added or removed. + """ + admin = cleanup_admin(w.path) + if admin is None: + return None + files = [os.path.join(admin, n) for n in ("HEAD", "index", os.path.join("logs", "HEAD"))] + return self.newest_hours([w.path, *files]) + + def finished(self, branch: str, tip: str) -> tuple[str, int | None] | None: + """How `branch` at `tip` is known finished, with the develop pull request's number if any. + + A merged pull request counts only from a head in this repository whose last commit is + `tip`. A reused branch name or a later commit then never rides on an old merge. + """ + data = cleanup_read(Q_SWEEP_MERGED, o=self.owner, r=self.repo, b=branch) + found = ((data.get("repository") or {}).get("merged")) or {} + nodes = found.get("nodes") + total = found.get("totalCount") + if not isinstance(nodes, list) or not isinstance(total, int) or total > len(nodes): + raise CleanupUnread(f"the merged pull request read for {branch!r} was incomplete") + matches = [ + n + for n in nodes + if isinstance(n, dict) + and in_repository(n, self.owner, self.repo) + and ( + n.get("headRefOid") == tip + or cleanup_behind(self.primary, tip, n.get("headRefOid") or "") + ) + ] + matches.sort(key=lambda n: n.get("baseRefName") != "develop") + if matches: + num = matches[0].get("number") + return f"merged PR #{num}", num if matches[0].get("baseRefName") == "develop" else None + for upstream in ("origin/develop", "origin/main"): + if cleanup_behind(self.primary, tip, f"refs/remotes/{upstream}"): + return f"contained in {upstream}", None + return None + + def remote(self, num: int | None, branch: str) -> None: + """Report, or with `apply` run, the remote half for a merged develop pull request. + + The remote half makes its own checks, so its refusal keeps only the remote branch. A + report runs those same checks and writes nothing. + """ + if num is None: + return + if not self.apply: + try: + plan = cleanup_check(self.owner, self.repo, num) + except CleanupRefused as exc: + print(f"keep-remote via #{num}: {exc}") + except CleanupUnread as exc: + self.failed(f"remote branch of #{num}", exc) + else: + if plan.ref is None: + print(f"remote already gone {branch} via #{num}") + else: + print(f"would-remove remote branch {branch} via #{num}") + return + print(f" remote half of #{num}:") + try: + code = _cleanup(self.owner, self.repo, num) + except CleanupUnread as exc: + self.failed(f"remote branch of #{num}", exc) + return + if code == 2: + self.problems += 1 + elif code != 0: + print(f"kept-remote #{num}, the local removal stands") + + def run(self) -> int: + cleanup_git(self.primary, "fetch", "--prune", "origin") + found = cleanup_read(Q_SWEEP_DEFAULT, o=self.owner, r=self.repo) + default = ((found.get("repository") or {}).get("defaultBranchRef") or {}).get("name") + if not default: + raise CleanupUnread(f"{self.target} returned no default branch") + self.permanent.add(default) + self.common = os.path.realpath( + os.path.join( + self.primary, + cleanup_git(self.primary, "rev-parse", "--git-common-dir").stdout.strip(), + ) + ) + trees = cleanup_worktrees(self.primary) + linked = [w for w in trees if w.path != self.primary] + for w in trees: + if w.path == self.primary and w.branch: + self.permanent.add(w.branch) + for w in trees: + if not w.prunable: + self.operating |= cleanup_operation_names(w.path) + pruned = self.prune([w for w in linked if w.prunable and not w.locked]) + held = {w.branch for w in trees if w.branch and w.path not in pruned} + for w in linked: + if not w.prunable or w.locked: + self.linked(w) + listed = cleanup_git( + self.primary, "for-each-ref", "--format=%(refname)%00%(objectname)", "refs/heads/" + ).stdout.splitlines() + for line in listed: + name, _, tip = line.partition("\0") + branch = name.removeprefix("refs/heads/") + if branch not in held and branch not in self.permanent: + self.loose(branch, tip) + self.base() + return 2 if self.problems else 0 + + def prune(self, stale: list[Worktree]) -> set[str]: + """Prune the entries whose directory is gone and whose record is old enough. + + Returns the paths pruned, or under a report the paths a prune would remove, so their + branches are no longer held and are judged as loose branches in the same run. + """ + old = [] + for w in stale: + hours = self.entry_hours(w) + if hours < self.min_age: + self.keep("too-recent", f"prunable worktree entry {w.path} idle {hours:.1f}h") + else: + old.append(w) + if not old: + return set() + if not self.apply: + for w in old: + print(f"would-remove prunable worktree entry {w.path}") + return {w.path for w in old} + expire = f"{int(self.min_age * 3600)}.seconds.ago" + try: + cleanup_git(self.primary, "worktree", "prune", "--expire", expire) + left = {w.path for w in cleanup_worktrees(self.primary)} + except CleanupUnread as exc: + self.failed("prunable worktree entries", exc) + return set() + for w in old: + if w.path in left: + self.problems += 1 + print(f"unread prunable worktree entry {w.path} is still listed after the prune") + else: + print(f"removed prunable worktree entry {w.path}") + return {w.path for w in old if w.path not in left} + + def entry_hours(self, w: Worktree) -> float: + """The idle hours of a missing worktree's record, from the `index` file prune reads. + + Git prunes by the age of that file, and by nothing once it is gone. An entry this cannot + match reads as brand new, so it is kept. + """ + base = os.path.join(self.common, "worktrees") + try: + names = os.listdir(base) + except OSError: + return 0.0 + for name in names: + try: + text = Path(base, name, "gitdir").read_text(encoding="utf-8").strip() + except OSError: + continue + if os.path.realpath(os.path.dirname(os.path.join(base, name, text))) == w.path: + return self.newest_hours([os.path.join(base, name, "index")]) + return 0.0 + + def linked(self, w: Worktree) -> None: + what = f"worktree {w.path}" + (f" branch={w.branch}" if w.branch else " detached") + try: + if w.locked: + self.keep("locked", what) + return + if cleanup_in_progress(w.path): + self.keep("in-progress-operation", what) + return + if os.path.exists(os.path.join(w.path, ".gitmodules")): + self.keep("submodules", what) + return + if ON_WINDOWS and cleanup_cwd_inside(w.path): + self.keep("cwd-inside", what) + return + if w.branch in self.permanent: + self.keep("permanent-branch", what) + return + if w.branch in self.operating: + self.keep("in-progress-operation", what) + return + hours = self.worktree_hours(w) + if hours is None: + self.keep("age-unreadable", what) + return + if hours < self.min_age: + self.keep("too-recent", f"{what} idle {hours:.1f}h of {self.min_age:g}h") + return + if cleanup_dirty(w.path, True): + self.keep("dirty", what) + return + if w.branch is None: + return self.detached(w, what) + tip = cleanup_tip(self.primary, f"refs/heads/{w.branch}") + if tip is None: + self.keep("branch-unreadable", what) + return + done = self.finished(w.branch, tip) + if done is None: + self.keep("unmerged-commits", what) + return + evidence, num = done + line = f"{what} tip={tip} evidence={evidence}" + if not self.apply: + print(f"would-remove {line}") + self.remote(num, w.branch) + return + if cleanup_remove_worktree(self.primary, w.path): + cleanup_moved_note() + print(f"removed worktree {w.path}") + try: + deleted = cleanup_delete_branch(self.primary, w.branch, tip) + except CleanupRefused as exc: + print(f"kept branch {w.branch} after removing its worktree: {exc}") + return + if deleted: + print(f"removed branch {w.branch} tip={tip} evidence={evidence}") + else: + print(f"branch {w.branch} was already gone") + self.remote(num, w.branch) + except CleanupUnread as exc: + self.failed(what, exc) + + def detached(self, w: Worktree, what: str) -> None: + contained = cleanup_git( + self.primary, + "for-each-ref", + "--contains", + w.head, + "refs/remotes/origin", + "--count=1", + "--format=%(refname)", + ).stdout.strip() + if not contained: + self.keep("unpushed-commits", what) + return + if not self.apply: + print(f"would-remove {what} head={w.head} evidence=contained in {contained}") + return + if cleanup_remove_worktree(self.primary, w.path): + cleanup_moved_note() + print(f"removed worktree {w.path} head={w.head} evidence=contained in {contained}") + + def loose(self, branch: str, tip: str) -> None: + """A local branch no worktree holds, judged by the age of its reflog.""" + what = f"branch {branch}" + try: + if branch in self.operating: + self.keep("in-progress-operation", what) + return + log = os.path.join(self.common, "logs", "refs", "heads", branch) + if not os.path.exists(log): + self.keep("age-unreadable", what) + return + hours = self.newest_hours([log]) + if hours < self.min_age: + self.keep("too-recent", f"{what} idle {hours:.1f}h of {self.min_age:g}h") + return + done = self.finished(branch, tip) + if done is None: + self.keep("unmerged-commits", what) + return + evidence, num = done + if not self.apply: + print(f"would-remove {what} tip={tip} evidence={evidence}") + self.remote(num, branch) + return + if cleanup_delete_branch(self.primary, branch, tip): + print(f"removed {what} tip={tip} evidence={evidence}") + else: + print(f"{what} was already gone") + self.remote(num, branch) + except CleanupRefused as exc: + reason = "tip-moved" if exc.status == "LOCAL_TIP_MOVED" else "checked-out-elsewhere" + self.keep(reason, f"{what}: {exc}") + except CleanupUnread as exc: + self.failed(what, exc) + + def base(self) -> None: + """Return the primary checkout to current `develop`, reporting what it could not do.""" + cleanup_base(self.primary, self.apply) + + +def cleanup_sweep(owner: str, repo: str, checkout: str, apply: bool, min_age: float) -> int: + """Report, or with `apply` remove, the clone's worktrees and branches that are provably done. + + Exits 0 where the pass completed. Exits 2 where a read did not answer or a removal could + not be confirmed, the other items having been tried either way. + """ + refused = cleanup_scope(owner, repo) + if refused is not None: + return refused + try: + primary = cleanup_primary(checkout, f"{owner}/{repo}") + sweep = CleanupSweep(owner, repo, primary, apply, min_age) + code = sweep.run() + except CleanupRefused as exc: + print(f"status={exc.status} nothing was removed: {exc}") + return 1 + except CleanupUnread as exc: + print(f"status=UNREAD the sweep stopped: {exc}") + return 2 + mode = "removed" if apply else "reported only, pass --apply to remove" + print(f"status=SWEPT {mode}, problems={sweep.problems}") + return code + + +def main(argv: list[str] | None = None) -> int: + core.utf8_console() + ap = argparse.ArgumentParser(prog="pr_cleanup.py") + ap.add_argument("number", type=int, nargs="?") + ap.add_argument("--repo", required=True, metavar="OWNER/NAME") + ap.add_argument( + "--checkout", + metavar="DIR", + help="the primary clone whose worktree, local branch, and base are cleaned after the " + "remote branch, and the one `--sweep` cleans", + ) + ap.add_argument( + "--sweep", + action="store_true", + help="take no pull request, and report the finished worktrees and branches of --checkout", + ) + ap.add_argument( + "--apply", + action="store_true", + help="--sweep: remove what the report lists, including the remote head branch of a " + "merged develop pull request, through the same checks as a numbered cleanup", + ) + ap.add_argument( + "--min-age-hours", + type=float, + default=None, + help="--sweep: hours an item must sit untouched before it is eligible (default 24)", + ) + a = ap.parse_args(argv) + if a.number is None and not a.sweep: + ap.error("the following arguments are required: number") + if a.sweep and a.number is not None: + ap.error("--sweep takes no pull request number") + if a.sweep and a.checkout is None: + ap.error("--sweep requires --checkout, the primary clone it sweeps") + if not a.sweep and (a.apply or a.min_age_hours is not None): + ap.error("--apply and --min-age-hours belong to `cleanup --sweep`") + if a.min_age_hours is not None and a.min_age_hours < 0: + ap.error("--min-age-hours cannot be negative") + owner, _, repo = a.repo.partition("/") + if not owner or not repo or "/" in repo: + ap.error(f"--repo takes OWNER/NAME, not {a.repo!r}") + if a.sweep: + hours = 24.0 if a.min_age_hours is None else a.min_age_hours + return cleanup_sweep(owner, repo, a.checkout, a.apply, hours) + return cleanup(owner, repo, a.number, a.checkout) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/pr_review.py b/scripts/pr_review.py index e54c4a432..78ce5f154 100755 --- a/scripts/pr_review.py +++ b/scripts/pr_review.py @@ -31,51 +31,9 @@ reviewer or not at all, and three stale descriptions in one session generated six review findings between them. Read-only. Exit 0 = every reference resolves, 70 = one does not, 71 = there were references and none could be read, so nothing was decided. - cleanup Delete a merged pull request's head branch, the verify-then-delete `drive-pr` and - `merge-and-release` prescribe, done here so it runs under the one allow rule the - host-safety installer registers for this script rather than as a hand-typed delete. - That rule approves any arguments, so every check lives here. It takes the pull request - number, never a branch name, and reads the branch from the pull request. It refuses - unless the pull request is merged into `develop` from a head in `--repo` itself, and - the head branch is none of `develop`, `main`, or the default branch read live. The - owner is bound to `registry/repos.json`, and the repository must be registered or a - fork, by `handoff.py`'s own write-scope check. It refuses a branch any ruleset or - branch protection covers, since the write guard's per-branch check never sees a delete - made in here. It refuses a branch an open pull request in `--repo` has as its head or - base, naming each. The ref is read exactly, its tip is checked against the pull request's - `headRefOid` before the delete is sent, and the delete is confirmed by reading the ref - back. The delete itself carries no expected tip, so this is verify-then-delete rather - than a compare-and-swap. With `--checkout `, a local half follows a - remote half that exited 0, on the pull request's own branch and head commit. Every - refusal is decided before anything is deleted, the remote branch included. A re-check - after the delete can still refuse when a concurrent session changed the branch or a - worktree in between. The output then names what already happened. A locked, dirty, or - mid-operation worktree refuses. So does a branch tip that is neither the merged head nor - behind it. So does a rebase or bisect paused on the branch in any worktree, the primary - included. A worktree entry whose directory is gone is removed. The primary leaves the - merged branch before the remote delete, and a failed checkout refuses. The local half - removes the worktrees holding the branch. It deletes the local branch only at the merged - head or an ancestor of it, after a tip re-read shows it unchanged. Then it fast-forwards - the clone to current `develop`, never a reset, stash, or force. A clone left behind is - reported and does not fail the run. The clone must be a primary checkout whose origin is - `--repo`. `cleanup --sweep --checkout ` takes no pull request. It reports - what is provably finished, one `would-remove` or `keep ` line per worktree or - branch, and removes it only with `--apply`. The report fetches and prunes the - remote-tracking refs of `origin` and writes nothing else. An item must sit untouched for - `--min-age-hours` (default 24) and be clean. A branch is finished when a pull request - from `--repo` merged it at its exact tip or past it. It is also finished when - `origin/develop` or `origin/main` contains it. A detached worktree is finished when any - `origin` ref contains its commit. For a merged develop pull request the sweep also - deletes the remote head branch through the same checks as `cleanup `. The report runs - those checks and names the result. The sweep never touches the primary checkout except - to fast-forward a tracked-clean `develop` to `origin/develop`, and the report names that - step. Permanent branches, locked worktrees, and worktrees mid-operation are never - touched. Exit 0 = deleted - and confirmed gone, or already gone, or a sweep that completed. Exit 1 = refused, - a moved tip naming both commits among them. Exit 2 = a read did not answer, a - partial one included. A delete or removal that could not be confirmed also exits 2, - as does argparse's own usage error. Exit 64 = the write scope could not be - established or excludes the target, checked before the registry and before any read. + cleanup Forwarded to `pr_cleanup.py`, which holds the contract and the exit codes, so a command + line naming this script keeps working under the allow rule the host-safety installer + registers for it. status One digest line, any unresolved threads, and any suppressed findings. Read-only. Exit 0 = no Copilot review covers the head yet, or every output shape is recognized and full diff coverage is stated for this head, by the round covering it or by the @@ -416,7 +374,6 @@ from typing import NamedTuple import gh_graphql as shared -import handoff # The directory this script sits in, and the anchor every scope answer is read from. # One value serves the owner probe and the refusal naming it, so the two cannot disagree. @@ -1248,42 +1205,6 @@ def one(m: re.Match[str]) -> str: resolveReviewThread(input:{threadId:$threadId}){ thread{ id isResolved } }} """ -Q_CLEANUP_TARGET = """ -query($o:String!,$r:String!,$n:Int!){ - repository(owner:$o,name:$r){ - defaultBranchRef{ name } - pullRequest(number:$n){ - merged baseRefName headRefName headRefOid headRepository{ nameWithOwner } } }} -""" -Q_CLEANUP_REF = """ -query($o:String!,$r:String!,$q:String!){ - repository(owner:$o,name:$r){ ref(qualifiedName:$q){ id target{ oid } } }} -""" -Q_CLEANUP_HEADS = """ -query($o:String!,$r:String!,$b:String!,$after:String){ - repository(owner:$o,name:$r){ - heads: pullRequests(states:OPEN,headRefName:$b,first:100,after:$after){ - pageInfo{ hasNextPage endCursor } nodes{ number headRepository{ nameWithOwner } } } }} -""" -Q_CLEANUP_BASES = """ -query($o:String!,$r:String!,$b:String!){ - repository(owner:$o,name:$r){ - bases: pullRequests(states:OPEN,baseRefName:$b,first:20){ totalCount nodes{ number } } }} -""" -Q_SWEEP_DEFAULT = """ -query($o:String!,$r:String!){ repository(owner:$o,name:$r){ defaultBranchRef{ name } }} -""" -Q_SWEEP_MERGED = """ -query($o:String!,$r:String!,$b:String!){ - repository(owner:$o,name:$r){ - merged: pullRequests(states:MERGED,headRefName:$b,first:50){ - totalCount nodes{ number baseRefName headRefOid headRepository{ nameWithOwner } } } }} -""" -M_DELETE_REF = """ -mutation($refId:ID!){ - deleteRef(input:{refId:$refId}){ clientMutationId }} -""" - WORKFLOW_KEYS_UNAVAILABLE = "workflowKeysUnavailable" @@ -6442,1085 +6363,6 @@ def check_claims(owner: str, repo: str, num: int) -> int: return 0 -class CleanupUnread(Exception): - """A read `cleanup` needed did not produce an answer, reported at exit 2.""" - - -def cleanup_read(query: str, **variables: object) -> dict: - """One GraphQL read for `cleanup`, raising rather than ending the run at exit 1. - - `gh_graphql` exits 1 on a failed read, which is `cleanup`'s refusal code, so a read that could - not answer would be reported as a refusal the caller can act on. - """ - try: - return shared.request(query, variables).data - except shared.GraphQLError as exc: - sys.stderr.write(exc.detail) - raise CleanupUnread(str(exc)) from exc - - -def cleanup_rest(path: str, what: str) -> object: - """One REST read for `cleanup`, retried, raising with its stderr where nothing parsed.""" - proc = reread(path, ".") - data = parsed_json(proc) - if data is None: - sys.stderr.write(proc.stderr) - raise CleanupUnread(f"the {what} read failed rc={proc.returncode} or printed no JSON") - return data - - -def cleanup_ref(owner: str, repo: str, branch: str) -> dict | None: - """The branch's ref node, or None where the branch does not exist. - - The read is by exact qualified name, so a branch sharing a suffix never answers for it. The - node id it returns goes straight to the delete, so no caller ever holds one to mistype. - """ - data = cleanup_read(Q_CLEANUP_REF, o=owner, r=repo, q=f"refs/heads/{branch}") - repository = data.get("repository") - if not isinstance(repository, dict): - raise CleanupUnread(f"{owner}/{repo} returned no repository for the ref read") - ref = repository.get("ref") - if ref is None: - return None - oid = (ref.get("target") or {}).get("oid") if isinstance(ref, dict) else None - if not isinstance(ref, dict) or not ref.get("id") or not oid: - raise CleanupUnread(f"the ref read for {branch!r} returned no id and tip: {ref!r}") - return ref - - -def branch_rules(owner: str, repo: str, branch: str) -> list[str]: - """What protects the branch, rulesets and classic protection alike, empty where nothing does. - - The branch travels inside a REST path, so a name that would change the path is not read, and - an unread rule set is never reported as no rules. - """ - if UNSAFE_REF.search(branch) or DOT_SEGMENT.search(branch): - raise CleanupUnread( - f"the head branch {branch!r} holds a character that changes a REST path, so the " - "rules applying to it cannot be read" - ) - rules = cleanup_rest(f"repos/{owner}/{repo}/rules/branches/{branch}", "branch rules") - if not isinstance(rules, list) or not all(isinstance(r, dict) for r in rules): - raise CleanupUnread(f"the branch rules read returned no list of rules: {rules!r}"[:400]) - found = [f"ruleset rule {r.get('type') or 'unnamed'}" for r in rules] - detail = cleanup_rest(f"repos/{owner}/{repo}/branches/{branch}", "branch protection") - protected = detail.get("protected") if isinstance(detail, dict) else None - if not isinstance(protected, bool): - raise CleanupUnread(f"the branch read returned no protected flag: {detail!r}"[:400]) - if protected: - found.append("branch protection") - return found - - -def in_repository(node: dict, owner: str, repo: str) -> bool: - """Whether a pull request's head lives in `owner/repo`, a fork's same-named branch being none.""" - name = (node.get("headRepository") or {}).get("nameWithOwner") or "" - return name.lower() == f"{owner}/{repo}".lower() - - -def local_heads(owner: str, repo: str, branch: str) -> list[object]: - """The number of each open pull request whose head is the branch in `owner/repo`. - - The connection also holds forks' pull requests on a same-named branch. So every page is read - and filtered to this repository's own before anything is decided, and a fork's is never - counted. A page that does not answer, or one that cannot be followed to the next, raises rather - than reading as no pull request. - """ - - def fetch(cursor: str | None) -> dict: - extra = {"after": cursor} if cursor else {} - return cleanup_read(Q_CLEANUP_HEADS, o=owner, r=repo, b=branch, **extra) - - numbers: list[object] = [] - try: - for parent in shared.walk(fetch, ("repository", "heads"), strict_page=True): - nodes = parent["heads"].get("nodes") - if not isinstance(nodes, list) or not all(isinstance(n, dict) for n in nodes): - raise CleanupUnread( - f"the open pull request read returned no heads list: {nodes!r}"[:400] - ) - numbers += [n.get("number") for n in nodes if in_repository(n, owner, repo)] - except shared.GraphQLError as exc: - raise CleanupUnread(str(exc)) from exc - return numbers - - -def branch_users(owner: str, repo: str, branch: str) -> list[str]: - """The open pull requests in this repository whose head or base is the branch. - - Deleting a branch closes every open pull request headed on it. It retargets or closes the ones - based on it, so each is named where one exists. Every head is read, per `local_heads`. A base - past the twenty read is counted rather than named, every one being this repository's own. An - unanswered read is never reported as no pull request. - """ - users = [f"#{number} (head)" for number in local_heads(owner, repo, branch)] - data = cleanup_read(Q_CLEANUP_BASES, o=owner, r=repo, b=branch) - repository = data.get("repository") - if not isinstance(repository, dict): - raise CleanupUnread(f"{owner}/{repo} returned no repository for the open pull request read") - found = repository.get("bases") - nodes = found.get("nodes") if isinstance(found, dict) else None - total = found.get("totalCount") if isinstance(found, dict) else None - if not isinstance(nodes, list) or not isinstance(total, int): - raise CleanupUnread(f"the open pull request read returned no bases list: {found!r}"[:400]) - users += [f"#{n.get('number')} (base)" for n in nodes if isinstance(n, dict)] - if total > len(nodes): - users.append(f"{total - len(nodes)} more with the branch as base") - return users - - -class CleanupPlan(NamedTuple): - branch: str - head: str - ref: dict | None - - -def cleanup_check(owner: str, repo: str, num: int) -> CleanupPlan: - """Every read-only check on pull request `num` and its remote branch, with no write. - - Raises `CleanupRefused` carrying the whole refusal text, and `CleanupUnread` on any - unanswered read. A branch anything protects is refused whatever that protection would allow. - The write guard's per-branch rule check never sees a delete made from inside this script. - """ - target = f"{owner}/{repo}" - data = cleanup_read(Q_CLEANUP_TARGET, o=owner, r=repo, n=num) - repository = data.get("repository") or {} - pr = repository.get("pullRequest") - default = (repository.get("defaultBranchRef") or {}).get("name") - if not isinstance(pr, dict) or not default: - raise CleanupUnread(f"{target} #{num} returned no pull request or no default branch") - branch = pr.get("headRefName") - head = pr.get("headRefOid") - if not branch or not head: - raise CleanupUnread(f"{target} #{num} returned no head branch or head commit") - head_repo = (pr.get("headRepository") or {}).get("nameWithOwner") or "" - refusals = [] - if pr.get("merged") is not True: - refusals.append("the pull request is not merged") - if pr.get("baseRefName") != "develop": - refusals.append(f"its base is {pr.get('baseRefName')!r}, not 'develop'") - if head_repo.lower() != target.lower(): - refusals.append(f"its head lives in {head_repo or 'no repository'}, not {target}") - if branch in ("develop", "main", default): - refusals.append(f"its head branch {branch!r} is a permanent branch") - if refusals: - raise CleanupRefused( - "REFUSED", f"nothing was deleted from {target} #{num}: {', and '.join(refusals)}" - ) - - ref = cleanup_ref(owner, repo, branch) - if ref is None: - return CleanupPlan(branch, head, None) - rules = branch_rules(owner, repo, branch) - if rules: - raise CleanupRefused( - "REFUSED", - f"nothing was deleted: {branch!r} on {target} is covered by " - f"{', '.join(rules)}, so its delete is the maintainer's call", - ) - users = branch_users(owner, repo, branch) - if users: - raise CleanupRefused( - "REFUSED", - f"nothing was deleted: open pull requests use {branch!r} on {target}, " - f"{', '.join(users)}, and deleting it would close or retarget them", - ) - tip = ref["target"]["oid"] - if tip != head: - raise CleanupRefused( - "TIP_MOVED", - f"nothing was deleted: {branch!r} on {target} is at {tip}, and #{num} merged " - f"{head}, so something reached the branch after the merge or the name was reused", - ) - return CleanupPlan(branch, head, ref) - - -def cleanup_fresh(owner: str, repo: str, plan: CleanupPlan) -> CleanupPlan: - """Read the remote branch again right before its delete, so the delete uses a fresh node id. - - The checks and the local preflight take time, and another session may have pushed since. - """ - if plan.ref is None: - return plan - ref = cleanup_ref(owner, repo, plan.branch) - if ref is None: - return CleanupPlan(plan.branch, plan.head, None) - tip = ref["target"]["oid"] - if tip != plan.head: - raise CleanupRefused( - "TIP_MOVED", - f"nothing was deleted: {plan.branch!r} on {owner}/{repo} is at {tip} just before " - f"its delete, and the pull request merged {plan.head}", - ) - return CleanupPlan(plan.branch, plan.head, ref) - - -def cleanup_remote_delete(owner: str, repo: str, plan: CleanupPlan) -> int: - """Delete the remote branch `plan` verified and read it back. - - A delete that reports a failure may still have landed, so the read back decides the outcome - either way. - """ - target = f"{owner}/{repo}" - branch = plan.branch - if plan.ref is None: - print(f"status=ALREADY_GONE branch={branch} is not on {target}, so nothing was deleted") - return 0 - tip = plan.ref["target"]["oid"] - print(f"deleting: {branch} on {target} at {tip}") - try: - response = shared.request(M_DELETE_REF, {"refId": plan.ref["id"]}).data - print(f" response: {json.dumps(response)[:400]}") - except shared.GraphQLError as exc: - print(f" the delete reported a failure: {exc}") - sys.stderr.write(exc.detail) - try: - after = cleanup_ref(owner, repo, branch) - except CleanupUnread as exc: - print( - f"status=DELETE_NOT_CONFIRMED the delete of {branch!r} on {target} was sent, and " - f"reading the ref back did not answer: {exc}" - ) - return 2 - if after is not None: - print( - f"status=DELETE_NOT_CONFIRMED {branch!r} on {target} still reads at " - f"{after['target']['oid']} after the delete" - ) - return 2 - print(f"status=DELETED branch={branch} oid={tip}, confirmed by reading the ref back") - return 0 - - -def _cleanup(owner: str, repo: str, num: int) -> int: - """The checks, the delete, and the read back, raising `CleanupUnread` on any unanswered read.""" - try: - plan = cleanup_check(owner, repo, num) - except CleanupRefused as exc: - print(f"status={exc.status} {exc}") - return 1 - return cleanup_remote_delete(owner, repo, plan) - - -def cleanup_scope(owner: str, repo: str) -> int | None: - """The exit code where the write scope refuses or cannot be established, else None.""" - ok, why = in_scope(owner) - if not ok: - print(f"status=OUT_OF_SCOPE nothing was deleted: {why}") - return 64 - try: - handoff.require_write_scope(argparse.Namespace(cmd="cleanup", repo=f"{owner}/{repo}")) - except handoff.Refusal as exc: - print(f"status=REFUSED nothing was deleted, refused by handoff.py's write scope: {exc}") - return 1 - except handoff.Execution as exc: - print(f"status=UNREAD nothing was deleted: {exc}") - return 2 - return None - - -def cleanup(owner: str, repo: str, num: int, checkout: str | None = None) -> int: - """Delete the head branch of merged pull request `num` once every check passes. - - Returns 0 where the branch is deleted and confirmed gone, or is already gone, and 1 on a - refusal. Returns 2 where a read did not answer or the delete could not be confirmed. Returns - 64 where the write scope `comment` and `reply` check excludes the target. Past that check, - the owner is bound to the fleet registry. The repository must be registered or a fork, by - `handoff.py`'s own write-scope check, reused rather than copied so the two cannot drift - apart. Its refusal text is printed as `handoff.py` words it. - - With `checkout`, the local half follows a remote half that exited 0. The checkout and every - local refusal are judged before the remote delete. A local refusal then means nothing at all - was deleted, the remote branch included. A re-check after the delete can still refuse when a - concurrent session changed the branch or a worktree. The output then names what happened. - """ - refused = cleanup_scope(owner, repo) - if refused is not None: - return refused - target = f"{owner}/{repo}" - primary = None - try: - if checkout is not None: - primary = cleanup_primary(checkout, target) - plan = cleanup_check(owner, repo, num) - if primary is not None: - cleanup_preflight(primary, plan.branch, plan.head) - cleanup_leave_branch(primary, plan.branch) - plan = cleanup_fresh(owner, repo, plan) - except CleanupRefused as exc: - if exc.status in ("REFUSED", "TIP_MOVED", "BAD_CHECKOUT"): - print(f"status={exc.status} {exc}") - else: - print(f"status={exc.status} nothing was deleted, remote branch included: {exc}") - return 1 - except CleanupUnread as exc: - print(f"status=UNREAD nothing was deleted: {exc}") - return 2 - code = cleanup_remote_delete(owner, repo, plan) - if code != 0 or primary is None: - return code - try: - return cleanup_local(primary, plan.branch, plan.head) - except CleanupRefused as exc: - print(f"status={exc.status} {exc}") - return 1 - except CleanupUnread as exc: - print(f"status=UNREAD the local half stopped: {exc}") - return 2 - - -ON_WINDOWS = os.name == "nt" - - -class CleanupRefused(Exception): - """A local check refused, carrying the `status=` name to print, reported at exit 1.""" - - def __init__(self, status: str, message: str) -> None: - super().__init__(message) - self.status = status - - -class Worktree(NamedTuple): - path: str - head: str - branch: str | None - locked: bool - prunable: bool - - -GITHUB_REMOTE = re.compile( - r"^(?:https?://(?:[^@/]+@)?github\.com/|ssh://[^@/]+@github\.com/|[^@/]+@github\.com:)" - r"([^/]+)/([^/]+?)(?:\.git)?/?$", - re.IGNORECASE, -) - - -def cleanup_git( - root: str, *args: str, ok: tuple[int, ...] = (0,) -) -> subprocess.CompletedProcess[str]: - """One git call in `root` as an argv list, raising with its stderr on an unexpected code. - - A return code the caller lists in `ok` is an answer it reads. Any other code is a call that - did not do what was asked, so it is shown and ends the step rather than swallowed. - """ - try: - proc = subprocess.run( - ["git", "-C", root, *args], - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - check=False, - timeout=300, - ) - except (OSError, subprocess.SubprocessError) as exc: - raise CleanupUnread(f"`git {' '.join(args)}` did not run: {exc}") from exc - if proc.returncode not in ok: - sys.stderr.write(proc.stderr) - raise CleanupUnread(f"`git {' '.join(args)}` failed rc={proc.returncode}") - return proc - - -def cleanup_primary(checkout: str, target: str) -> str: - """The real path of the primary checkout at `checkout`, refusing anything else. - - A linked worktree is refused, since removing worktrees and moving branches belongs to the - clone that owns them. So is an origin naming another repository, since every local step - here derives from a pull request in `target`. - """ - probe = cleanup_git( - checkout, - "rev-parse", - "--absolute-git-dir", - "--git-common-dir", - "--show-toplevel", - ok=(0, 128), - ) - lines = probe.stdout.splitlines() - if probe.returncode != 0 or len(lines) != 3: - raise CleanupRefused("BAD_CHECKOUT", f"{checkout!r} is not a git checkout with a work tree") - git_dir, common, top = lines - if os.path.realpath(git_dir) != os.path.realpath(os.path.join(checkout, common)): - raise CleanupRefused( - "BAD_CHECKOUT", f"{checkout!r} is a linked worktree, not a primary one" - ) - url = cleanup_git(top, "config", "--get", "remote.origin.url", ok=(0, 1)).stdout.strip() - found = GITHUB_REMOTE.match(url) - if found is None or f"{found[1]}/{found[2]}".lower() != target.lower(): - shown = re.sub(r"//[^/@]*@", "//", url) or "unset" - raise CleanupRefused("BAD_CHECKOUT", f"origin of {top} is {shown}, not {target}") - return os.path.realpath(top) - - -def cleanup_worktrees(primary: str) -> list[Worktree]: - """Every worktree git lists for the clone, the primary first.""" - out = cleanup_git(primary, "worktree", "list", "--porcelain").stdout - trees = [] - for block in out.split("\n\n"): - fields = dict(line.partition(" ")[::2] for line in block.splitlines()) - if "worktree" not in fields: - continue - branch = fields.get("branch") - trees.append( - Worktree( - path=os.path.realpath(fields["worktree"]), - head=fields.get("HEAD", ""), - branch=branch.removeprefix("refs/heads/") if branch else None, - locked="locked" in fields, - prunable="prunable" in fields, - ) - ) - return trees - - -def cleanup_tip(primary: str, ref: str) -> str | None: - """The commit `ref` names, or None where it does not exist.""" - proc = cleanup_git(primary, "rev-parse", "--verify", "--quiet", ref, ok=(0, 1)) - return proc.stdout.strip() or None - - -def cleanup_dirty(path: str, untracked: bool) -> bool: - """Whether the work tree at `path` has changes, without refreshing its index. - - `--no-optional-locks` keeps the read from rewriting the index, which would make an untouched - tree look touched to the age rule of `--sweep`. - """ - flag = "--untracked-files=all" if untracked else "--untracked-files=no" - out = cleanup_git(path, "--no-optional-locks", "status", "--porcelain", flag).stdout - return bool(out.strip()) - - -IN_PROGRESS = ( - "rebase-merge", - "rebase-apply", - "BISECT_LOG", - "MERGE_HEAD", - "CHERRY_PICK_HEAD", - "REVERT_HEAD", -) - - -def cleanup_admin(path: str) -> str | None: - """The git directory holding the worktree at `path`'s state, or None where unreadable. - - A linked worktree names it in its `.git` file, and a primary checkout's `.git` is it. - """ - if os.path.isdir(os.path.join(path, ".git")): - return os.path.join(path, ".git") - try: - text = Path(path, ".git").read_text(encoding="utf-8").strip() - except OSError: - return None - if not text.startswith("gitdir:"): - return None - return os.path.join(path, text.removeprefix("gitdir:").strip()) - - -def cleanup_in_progress(path: str) -> bool: - """Whether a rebase, bisect, merge, cherry-pick, or revert is paused in the worktree.""" - admin = cleanup_admin(path) - return admin is not None and any(os.path.exists(os.path.join(admin, n)) for n in IN_PROGRESS) - - -def cleanup_operation_names(path: str) -> set[str]: - """The branch names a rebase or bisect paused in the worktree at `path` is working on. - - Either detaches HEAD, so the worktree no longer lists the branch it will return to. - """ - admin = cleanup_admin(path) - names: set[str] = set() - if admin is None: - return names - for name in ("rebase-merge/head-name", "rebase-apply/head-name", "BISECT_START"): - try: - text = Path(admin, name).read_text(encoding="utf-8").strip() - except OSError: - continue - names.add(text.removeprefix("refs/heads/")) - return names - - -def cleanup_cwd_inside(path: str) -> bool: - """Whether this process's working directory is the worktree at `path` or inside it.""" - try: - here = os.path.realpath(os.getcwd()) - except OSError: - return False - return here == path or here.startswith(path + os.sep) - - -def cleanup_remove_worktree(primary: str, path: str) -> bool: - """Remove the worktree at `path` without force and read the list back for it. - - Returns whether this process was standing inside it. The process moves to the primary - checkout first. Windows cannot free a directory the parent shell holds, so callers refuse - there before the first removal. - """ - inside = cleanup_cwd_inside(path) - if inside: - os.chdir(primary) - try: - cleanup_git(primary, "worktree", "remove", path) - except CleanupUnread: - if any(w.path == path for w in cleanup_worktrees(primary)): - raise - if os.path.exists(path): - raise CleanupUnread(f"git failed to remove {path}, which is unlisted but still on disk") - print(f" git reported an error, yet {path} is no longer listed, so it is already gone") - return inside - if any(w.path == path for w in cleanup_worktrees(primary)): - raise CleanupUnread(f"the worktree {path} is still listed after its removal") - return inside - - -def cleanup_moved_note() -> None: - print(" note: the shell's directory was that worktree and is gone, so change directory") - - -def cleanup_delete_branch(primary: str, branch: str, tip: str) -> bool: - """Delete the local branch while it still names `tip`, and read it back. - - Returns whether this call deleted it, False where it was already gone. The tip is read again - just before the delete. Git's own refusal then covers a branch that is checked out, being - rebased, or being bisected in any worktree. It is raised as a refusal. - """ - ref = f"refs/heads/{branch}" - now = cleanup_tip(primary, ref) - if now is None: - return False - if now != tip: - raise CleanupRefused( - "LOCAL_TIP_MOVED", f"{ref} reads {now} just before its delete, and {tip} was expected" - ) - proc = cleanup_git(primary, "branch", "-D", "--", branch, ok=(0, 1)) - if proc.returncode != 0: - if cleanup_tip(primary, ref) is None: - return False - raise CleanupRefused("WORKTREE_KEPT", f"git kept {ref}: {proc.stderr.strip()}") - if cleanup_tip(primary, ref) is not None: - raise CleanupUnread(f"{ref} still exists after its delete") - return True - - -def cleanup_base(primary: str, apply: bool = True) -> bool: - """Fast-forward the primary checkout to current `develop`, never reset, stash, or force. - - Returns whether the clone is current, printing a status line for each way it is not. A clone - on another branch, with tracked changes, or that cannot fast-forward is left alone. No - outcome here is an error, so callers report it and never fail a run on it. Without `apply` - it only reports the fast-forward it would make. - """ - try: - current = cleanup_git(primary, "symbolic-ref", "--quiet", "--short", "HEAD", ok=(0, 1)) - on = current.stdout.strip() - if on != "develop": - print(f"keep base-not-on-develop {primary} is on {on or 'a detached head'}") - return False - if cleanup_dirty(primary, False): - print(f"status=BASE_DIRTY {primary} has tracked changes, so it was left where it is") - return False - behind = cleanup_git( - primary, "merge-base", "--is-ancestor", "HEAD", "origin/develop", ok=(0, 1) - ) - if behind.returncode == 1: - print(f"status=BASE_NOT_FF develop in {primary} cannot fast-forward to origin/develop") - return False - if not apply and cleanup_tip(primary, "HEAD") != cleanup_tip( - primary, "refs/remotes/origin/develop" - ): - print(f"would-fast-forward develop in {primary}") - return True - if apply: - try: - cleanup_git(primary, "merge", "--ff-only", "origin/develop") - except CleanupUnread: - if cleanup_tip(primary, "HEAD") != cleanup_tip( - primary, "refs/remotes/origin/develop" - ): - raise - except CleanupUnread as exc: - print(f"status=BASE_UNREAD develop in {primary} could not be brought current: {exc}") - return False - print(f" develop in {primary} is at origin/develop") - return True - - -def cleanup_behind(primary: str, tip: str, head: str) -> bool: - """Whether commit `tip` is an ancestor of `head`, so it holds nothing `head` lacks. - - A `head` object this clone lacks proves nothing, and reads as not behind. - """ - proc = cleanup_git(primary, "merge-base", "--is-ancestor", tip, head, ok=(0, 1, 128)) - return proc.returncode == 0 - - -def cleanup_preflight(primary: str, branch: str, head: str) -> tuple[str | None, list[Worktree]]: - """Fetch, then decide every local refusal, returning the branch tip and the worktrees to remove. - - Nothing is removed here, so a refusal leaves all of it in place. `head` is the commit the - merged pull request carried, read live by the remote half. - """ - cleanup_git(primary, "fetch", "--prune", "origin") - ref = f"refs/heads/{branch}" - tip = cleanup_tip(primary, ref) - if tip is not None and tip != head and not cleanup_behind(primary, tip, head): - raise CleanupRefused( - "LOCAL_TIP_MOVED", - f"{ref} is at {tip}, which is neither the merged head {head} nor behind it, " - "so it may carry commits that were never pushed", - ) - mirror = cleanup_tip(primary, f"refs/remotes/origin/{branch}") - if mirror is not None and mirror != head: - raise CleanupRefused( - "TIP_MOVED", - f"nothing was deleted: origin/{branch} is at {mirror}, and the pull request merged " - f"{head}, so something reached the branch after the merge", - ) - linked = [] - trees = cleanup_worktrees(primary) - others = [w for w in trees if w.path != primary] - for w in trees: - if not w.prunable and branch in cleanup_operation_names(w.path): - raise CleanupRefused( - "WORKTREE_KEPT", f"{w.path} has a rebase or bisect in progress on {branch!r}" - ) - holds = any(w.path == primary and w.branch == branch for w in cleanup_worktrees(primary)) - if holds and cleanup_in_progress(primary): - raise CleanupRefused( - "WORKTREE_KEPT", f"{primary} has a merge, cherry-pick, revert, or bisect in progress" - ) - if holds and cleanup_dirty(primary, False): - raise CleanupRefused( - "BASE_DIRTY", f"{primary} has {branch!r} checked out with tracked changes" - ) - for w in (w for w in others if w.branch == branch): - why = ( - "it is locked" - if w.locked - else "a rebase, bisect, merge, cherry-pick, or revert is in progress in it" - if cleanup_in_progress(w.path) - else "it holds submodules, which only git's own check may remove" - if os.path.exists(os.path.join(w.path, ".gitmodules")) - else "run from a directory outside it, such as the base clone" - if ON_WINDOWS and cleanup_cwd_inside(w.path) - else None - ) - if why is not None: - raise CleanupRefused("WORKTREE_KEPT", f"{w.path}, {why}") - if not w.prunable and cleanup_dirty(w.path, True): - raise CleanupRefused("WORKTREE_DIRTY", f"{w.path} has uncommitted changes") - linked.append(w) - return tip, linked - - -def cleanup_leave_branch(primary: str, branch: str) -> None: - """Move the primary checkout to `develop` where it holds `branch`, refusing if git will not. - - This runs before the remote delete, so a checkout that fails still deletes nothing. - """ - if not any(w.path == primary and w.branch == branch for w in cleanup_worktrees(primary)): - return - try: - cleanup_git(primary, "checkout", "develop") - except CleanupUnread as exc: - raise CleanupRefused( - "WORKTREE_KEPT", f"{primary} could not leave {branch}, so the branch was kept" - ) from exc - print(f" switched {primary} off {branch} to develop") - - -def cleanup_local(primary: str, branch: str, head: str) -> int: - """Remove the finished branch's worktrees and local branch, then return the base clone. - - The refusals are decided again before the first removal, so a refused run leaves all of it - in place. The base clone's return is reported and never fails the run. The local branch is - deleted only at `head` or an ancestor of it, after a tip re-read shows it unchanged. - """ - try: - tip, linked = cleanup_preflight(primary, branch, head) - except CleanupRefused as exc: - raise CleanupRefused(exc.status, f"nothing local was removed: {exc}") from exc - for w in linked: - moved = cleanup_remove_worktree(primary, w.path) - print(f" removed worktree {w.path}") - if moved: - cleanup_moved_note() - if tip is None: - print(f" local branch {branch} is already gone") - else: - try: - deleted = cleanup_delete_branch(primary, branch, tip) - except CleanupUnread as exc: - print(f"status=LOCAL_DELETE_NOT_CONFIRMED {exc}") - return 2 - if deleted: - print(f" deleted local branch {branch} at {tip}, confirmed by reading the ref back") - else: - print(f" local branch {branch} is already gone") - current = cleanup_base(primary) - try: - first = cleanup_git(primary, "status", "--short", "--branch").stdout.splitlines()[:1] - print(f" {first[0] if first else 'status unavailable'}") - except CleanupUnread: - print(" status unavailable") - try: - print(f" worktrees listed: {len(cleanup_worktrees(primary))}") - except CleanupUnread: - print(" worktrees listed: unavailable") - base = "current" if current else "kept" - print(f"status=CLEANED branch={branch} oid={head} locally, base={base}") - return 0 - - -class CleanupSweep: - """One pass over a clone's worktrees and local branches, removing what is provably finished. - - Nothing here is a failure unless a read did not answer or a removal could not be confirmed. - `problems` counts those, so the run continues with the other items and still exits 2. - """ - - def __init__(self, owner: str, repo: str, primary: str, apply: bool, min_age: float) -> None: - self.owner = owner - self.repo = repo - self.target = f"{owner}/{repo}" - self.primary = primary - self.apply = apply - self.min_age = min_age - self.problems = 0 - self.permanent = {"develop", "main"} - self.common = "" - self.operating: set[str] = set() - - def keep(self, reason: str, what: str) -> None: - print(f"keep {reason} {what}") - - def failed(self, what: str, exc: CleanupUnread) -> None: - self.problems += 1 - print(f"unread {what}: {exc}") - - def newest_hours(self, paths: list[str]) -> float: - """Hours since the newest mtime among `paths`, infinite where none can be read.""" - stamps = [] - for path in paths: - try: - stamps.append(os.stat(path).st_mtime) - except OSError: - continue - return float("inf") if not stamps else (time.time() - max(stamps)) / 3600 - - def worktree_hours(self, w: Worktree) -> float | None: - """The idle hours of a linked worktree, or None where its admin directory is unreadable. - - Taken before any status runs on it, and from the admin files git itself writes on use. - The directory's own mtime moves only when an entry is added or removed. - """ - admin = cleanup_admin(w.path) - if admin is None: - return None - files = [os.path.join(admin, n) for n in ("HEAD", "index", os.path.join("logs", "HEAD"))] - return self.newest_hours([w.path, *files]) - - def finished(self, branch: str, tip: str) -> tuple[str, int | None] | None: - """How `branch` at `tip` is known finished, with the develop pull request's number if any. - - A merged pull request counts only from a head in this repository whose last commit is - `tip`. A reused branch name or a later commit then never rides on an old merge. - """ - data = cleanup_read(Q_SWEEP_MERGED, o=self.owner, r=self.repo, b=branch) - found = ((data.get("repository") or {}).get("merged")) or {} - nodes = found.get("nodes") - total = found.get("totalCount") - if not isinstance(nodes, list) or not isinstance(total, int) or total > len(nodes): - raise CleanupUnread(f"the merged pull request read for {branch!r} was incomplete") - matches = [ - n - for n in nodes - if isinstance(n, dict) - and in_repository(n, self.owner, self.repo) - and ( - n.get("headRefOid") == tip - or cleanup_behind(self.primary, tip, n.get("headRefOid") or "") - ) - ] - matches.sort(key=lambda n: n.get("baseRefName") != "develop") - if matches: - num = matches[0].get("number") - return f"merged PR #{num}", num if matches[0].get("baseRefName") == "develop" else None - for upstream in ("origin/develop", "origin/main"): - if cleanup_behind(self.primary, tip, f"refs/remotes/{upstream}"): - return f"contained in {upstream}", None - return None - - def remote(self, num: int | None, branch: str) -> None: - """Report, or with `apply` run, the remote half for a merged develop pull request. - - The remote half makes its own checks, so its refusal keeps only the remote branch. A - report runs those same checks and writes nothing. - """ - if num is None: - return - if not self.apply: - try: - plan = cleanup_check(self.owner, self.repo, num) - except CleanupRefused as exc: - print(f"keep-remote via #{num}: {exc}") - except CleanupUnread as exc: - self.failed(f"remote branch of #{num}", exc) - else: - if plan.ref is None: - print(f"remote already gone {branch} via #{num}") - else: - print(f"would-remove remote branch {branch} via #{num}") - return - print(f" remote half of #{num}:") - try: - code = _cleanup(self.owner, self.repo, num) - except CleanupUnread as exc: - self.failed(f"remote branch of #{num}", exc) - return - if code == 2: - self.problems += 1 - elif code != 0: - print(f"kept-remote #{num}, the local removal stands") - - def run(self) -> int: - cleanup_git(self.primary, "fetch", "--prune", "origin") - found = cleanup_read(Q_SWEEP_DEFAULT, o=self.owner, r=self.repo) - default = ((found.get("repository") or {}).get("defaultBranchRef") or {}).get("name") - if not default: - raise CleanupUnread(f"{self.target} returned no default branch") - self.permanent.add(default) - self.common = os.path.realpath( - os.path.join( - self.primary, - cleanup_git(self.primary, "rev-parse", "--git-common-dir").stdout.strip(), - ) - ) - trees = cleanup_worktrees(self.primary) - linked = [w for w in trees if w.path != self.primary] - for w in trees: - if w.path == self.primary and w.branch: - self.permanent.add(w.branch) - for w in trees: - if not w.prunable: - self.operating |= cleanup_operation_names(w.path) - pruned = self.prune([w for w in linked if w.prunable and not w.locked]) - held = {w.branch for w in trees if w.branch and w.path not in pruned} - for w in linked: - if not w.prunable or w.locked: - self.linked(w) - listed = cleanup_git( - self.primary, "for-each-ref", "--format=%(refname)%00%(objectname)", "refs/heads/" - ).stdout.splitlines() - for line in listed: - name, _, tip = line.partition("\0") - branch = name.removeprefix("refs/heads/") - if branch not in held and branch not in self.permanent: - self.loose(branch, tip) - self.base() - return 2 if self.problems else 0 - - def prune(self, stale: list[Worktree]) -> set[str]: - """Prune the entries whose directory is gone and whose record is old enough. - - Returns the paths pruned, or under a report the paths a prune would remove, so their - branches are no longer held and are judged as loose branches in the same run. - """ - old = [] - for w in stale: - hours = self.entry_hours(w) - if hours < self.min_age: - self.keep("too-recent", f"prunable worktree entry {w.path} idle {hours:.1f}h") - else: - old.append(w) - if not old: - return set() - if not self.apply: - for w in old: - print(f"would-remove prunable worktree entry {w.path}") - return {w.path for w in old} - expire = f"{int(self.min_age * 3600)}.seconds.ago" - try: - cleanup_git(self.primary, "worktree", "prune", "--expire", expire) - left = {w.path for w in cleanup_worktrees(self.primary)} - except CleanupUnread as exc: - self.failed("prunable worktree entries", exc) - return set() - for w in old: - if w.path in left: - self.problems += 1 - print(f"unread prunable worktree entry {w.path} is still listed after the prune") - else: - print(f"removed prunable worktree entry {w.path}") - return {w.path for w in old if w.path not in left} - - def entry_hours(self, w: Worktree) -> float: - """The idle hours of a missing worktree's record, from the `index` file prune reads. - - Git prunes by the age of that file, and by nothing once it is gone. An entry this cannot - match reads as brand new, so it is kept. - """ - base = os.path.join(self.common, "worktrees") - try: - names = os.listdir(base) - except OSError: - return 0.0 - for name in names: - try: - text = Path(base, name, "gitdir").read_text(encoding="utf-8").strip() - except OSError: - continue - if os.path.realpath(os.path.dirname(os.path.join(base, name, text))) == w.path: - return self.newest_hours([os.path.join(base, name, "index")]) - return 0.0 - - def linked(self, w: Worktree) -> None: - what = f"worktree {w.path}" + (f" branch={w.branch}" if w.branch else " detached") - try: - if w.locked: - self.keep("locked", what) - return - if cleanup_in_progress(w.path): - self.keep("in-progress-operation", what) - return - if os.path.exists(os.path.join(w.path, ".gitmodules")): - self.keep("submodules", what) - return - if ON_WINDOWS and cleanup_cwd_inside(w.path): - self.keep("cwd-inside", what) - return - if w.branch in self.permanent: - self.keep("permanent-branch", what) - return - if w.branch in self.operating: - self.keep("in-progress-operation", what) - return - hours = self.worktree_hours(w) - if hours is None: - self.keep("age-unreadable", what) - return - if hours < self.min_age: - self.keep("too-recent", f"{what} idle {hours:.1f}h of {self.min_age:g}h") - return - if cleanup_dirty(w.path, True): - self.keep("dirty", what) - return - if w.branch is None: - return self.detached(w, what) - tip = cleanup_tip(self.primary, f"refs/heads/{w.branch}") - if tip is None: - self.keep("branch-unreadable", what) - return - done = self.finished(w.branch, tip) - if done is None: - self.keep("unmerged-commits", what) - return - evidence, num = done - line = f"{what} tip={tip} evidence={evidence}" - if not self.apply: - print(f"would-remove {line}") - self.remote(num, w.branch) - return - if cleanup_remove_worktree(self.primary, w.path): - cleanup_moved_note() - print(f"removed worktree {w.path}") - try: - deleted = cleanup_delete_branch(self.primary, w.branch, tip) - except CleanupRefused as exc: - print(f"kept branch {w.branch} after removing its worktree: {exc}") - return - if deleted: - print(f"removed branch {w.branch} tip={tip} evidence={evidence}") - else: - print(f"branch {w.branch} was already gone") - self.remote(num, w.branch) - except CleanupUnread as exc: - self.failed(what, exc) - - def detached(self, w: Worktree, what: str) -> None: - contained = cleanup_git( - self.primary, - "for-each-ref", - "--contains", - w.head, - "refs/remotes/origin", - "--count=1", - "--format=%(refname)", - ).stdout.strip() - if not contained: - self.keep("unpushed-commits", what) - return - if not self.apply: - print(f"would-remove {what} head={w.head} evidence=contained in {contained}") - return - if cleanup_remove_worktree(self.primary, w.path): - cleanup_moved_note() - print(f"removed worktree {w.path} head={w.head} evidence=contained in {contained}") - - def loose(self, branch: str, tip: str) -> None: - """A local branch no worktree holds, judged by the age of its reflog.""" - what = f"branch {branch}" - try: - if branch in self.operating: - self.keep("in-progress-operation", what) - return - log = os.path.join(self.common, "logs", "refs", "heads", branch) - if not os.path.exists(log): - self.keep("age-unreadable", what) - return - hours = self.newest_hours([log]) - if hours < self.min_age: - self.keep("too-recent", f"{what} idle {hours:.1f}h of {self.min_age:g}h") - return - done = self.finished(branch, tip) - if done is None: - self.keep("unmerged-commits", what) - return - evidence, num = done - if not self.apply: - print(f"would-remove {what} tip={tip} evidence={evidence}") - self.remote(num, branch) - return - if cleanup_delete_branch(self.primary, branch, tip): - print(f"removed {what} tip={tip} evidence={evidence}") - else: - print(f"{what} was already gone") - self.remote(num, branch) - except CleanupRefused as exc: - reason = "tip-moved" if exc.status == "LOCAL_TIP_MOVED" else "checked-out-elsewhere" - self.keep(reason, f"{what}: {exc}") - except CleanupUnread as exc: - self.failed(what, exc) - - def base(self) -> None: - """Return the primary checkout to current `develop`, reporting what it could not do.""" - cleanup_base(self.primary, self.apply) - - -def cleanup_sweep(owner: str, repo: str, checkout: str, apply: bool, min_age: float) -> int: - """Report, or with `apply` remove, the clone's worktrees and branches that are provably done. - - Exits 0 where the pass completed. Exits 2 where a read did not answer or a removal could - not be confirmed, the other items having been tried either way. - """ - refused = cleanup_scope(owner, repo) - if refused is not None: - return refused - try: - primary = cleanup_primary(checkout, f"{owner}/{repo}") - sweep = CleanupSweep(owner, repo, primary, apply, min_age) - code = sweep.run() - except CleanupRefused as exc: - print(f"status={exc.status} nothing was removed: {exc}") - return 1 - except CleanupUnread as exc: - print(f"status=UNREAD the sweep stopped: {exc}") - return 2 - mode = "removed" if apply else "reported only, pass --apply to remove" - print(f"status=SWEPT {mode}, problems={sweep.problems}") - return code - - def utf8_console() -> None: """Write the console streams as UTF-8, whatever the host code page is. @@ -7534,13 +6376,17 @@ def utf8_console() -> None: def main(argv: list[str] | None = None) -> int: + args = sys.argv[1:] if argv is None else argv + if args[:1] == ["cleanup"]: + import pr_cleanup + + return pr_cleanup.main(args[1:]) utf8_console() ap = argparse.ArgumentParser() - sweeping = "--sweep" in (sys.argv[1:] if argv is None else argv) ap.add_argument( "cmd", choices=["attest", "claims", "cleanup", "comment", "status", "reply", "wait"] ) - ap.add_argument("number", type=int, nargs="?" if sweeping else None) + ap.add_argument("number", type=int, nargs="?") # No default, because the wrong repository is the failure this argument has actually had. # A default names one repository, and every run from elsewhere silently reads that one. # The number resolves there, the digest renders, and nothing in the output disagrees. @@ -7635,28 +6481,9 @@ def main(argv: list[str] | None = None) -> int: "--checkout", metavar="DIR", help="attest: the checkout holding the pull request's head and its recorded local pass " - "(default the current directory), cleanup: the primary clone whose worktree, local " - "branch, and base are cleaned after the remote branch, and the one `--sweep` cleans", - ) - ap.add_argument( - "--sweep", - action="store_true", - help="cleanup: take no pull request, and report the finished worktrees and branches of " - "--checkout", - ) - ap.add_argument( - "--apply", - action="store_true", - help="cleanup --sweep: remove what the report lists, including the remote head branch " - "of a merged develop pull request, through the same checks as `cleanup `", + "(default the current directory)", ) - ap.add_argument( - "--min-age-hours", - type=float, - default=None, - help="cleanup --sweep: hours an item must sit untouched before it is eligible (default 24)", - ) - a = ap.parse_args(argv) + a = ap.parse_args(args) # Named for the command they belong to, since one silently ignored reads as one that took effect. # A `status` given --body reports a clean digest and writes nothing. # Nothing in that output says the reply never happened. @@ -7672,20 +6499,12 @@ def main(argv: list[str] | None = None) -> int: ap.error(f"{flag} belongs to `reply`, not `{a.cmd}`") if a.cmd != "wait" and a.request: ap.error(f"--request belongs to `wait`, not `{a.cmd}`") - if a.cmd not in ("attest", "cleanup") and a.checkout is not None: + if a.cmd == "cleanup": + ap.error("`cleanup` takes its arguments after it, as `cleanup NUMBER --repo OWNER/NAME`") + if a.cmd != "attest" and a.checkout is not None: ap.error(f"--checkout belongs to `attest` or `cleanup`, not `{a.cmd}`") - if a.cmd != "cleanup" and a.sweep: - ap.error(f"--sweep belongs to `cleanup`, not `{a.cmd}`") - if a.number is None and not a.sweep: + if a.number is None: ap.error("the following arguments are required: number") - if a.sweep and a.number is not None: - ap.error("--sweep takes no pull request number") - if a.sweep and a.checkout is None: - ap.error("--sweep requires --checkout, the primary clone it sweeps") - if not a.sweep and (a.apply or a.min_age_hours is not None): - ap.error("--apply and --min-age-hours belong to `cleanup --sweep`") - if a.min_age_hours is not None and a.min_age_hours < 0: - ap.error("--min-age-hours cannot be negative") if a.cmd not in ("comment", "reply") and a.body is not None: ap.error(f"--body belongs to `comment` or `reply`, not `{a.cmd}`") required = ["--body"] + (["--match"] if a.cmd == "reply" else []) @@ -7722,14 +6541,6 @@ def main(argv: list[str] | None = None) -> int: if a.cmd == "claims": return check_claims(owner, repo, a.number) - if a.cmd == "cleanup" and a.sweep: - return cleanup_sweep( - owner, repo, a.checkout, a.apply, 24.0 if a.min_age_hours is None else a.min_age_hours - ) - - if a.cmd == "cleanup": - return cleanup(owner, repo, a.number, a.checkout) - if a.cmd == "attest": return attest(owner, repo, a.number, a.checkout or ".") diff --git a/scripts/pr_review_copilot.py b/scripts/pr_review_copilot.py index e3cdf79c8..8cfdcc030 100755 --- a/scripts/pr_review_copilot.py +++ b/scripts/pr_review_copilot.py @@ -14,13 +14,11 @@ The body is parsed with markdown-it-py, so a code span, a fence, or an indented block is a token of its own and never reads as markup. Only Copilot's current overview format, the one carrying the `ccr-overview-v2` marker, is read. A Copilot body in any other layout reads as a note. - -Usage: pr_review_copilot.py [--help] [REVIEWER] < BODY -Prints the reading of the body on standard input, `copilot` by default. """ from __future__ import annotations +import argparse import functools import json import re @@ -541,15 +539,13 @@ def html_lines(body: str) -> list[str]: def main(argv: list[str] | None = None) -> int: - args = sys.argv[1:] if argv is None else argv - if args and args[0] in ("-h", "--help"): - print(__doc__.strip()) - return 0 - if len(args) > 1 or (args and args[0] not in REVIEWERS): - print(f"pr_review_copilot.py: unrecognized argument: {args[-1]}", file=sys.stderr) - return 2 - reading = read(sys.stdin.read(), args[0] if args else "copilot") - print(json.dumps(reading._asdict(), indent=2)) + ap = argparse.ArgumentParser( + prog="pr_review_copilot.py", + description="Print the reading of the review body on standard input.", + ) + ap.add_argument("reviewer", nargs="?", default="copilot", choices=REVIEWERS) + a = ap.parse_args(argv) + print(json.dumps(read(sys.stdin.read(), a.reviewer)._asdict(), indent=2)) return 0 diff --git a/tests/test_cli_usage.py b/tests/test_cli_usage.py index 1f7d48d5c..a6c62c6cb 100755 --- a/tests/test_cli_usage.py +++ b/tests/test_cli_usage.py @@ -108,6 +108,7 @@ "scripts/build_dist.py", "scripts/docker_lint.py", "scripts/host_gate.py", + "scripts/pr_review_copilot.py", "scripts/prose_lint.py", "scripts/repo_gate.py", "scripts/skills_install.ps1", diff --git a/tests/test_pr_cleanup.py b/tests/test_pr_cleanup.py new file mode 100755 index 000000000..34ddf8a64 --- /dev/null +++ b/tests/test_pr_cleanup.py @@ -0,0 +1,1340 @@ +#!/usr/bin/env python3 +"""Drive pr_cleanup's verify-then-delete and its sweep against responses and checkouts it must read. + +Every GraphQL read is answered from a fake, and the local half runs against throwaway clones, so +no case reaches the network. `pr_review.py cleanup` forwards here, and the cases calling +`pr_review.main` hold that forward. +""" + +from __future__ import annotations + +import contextlib +import io +import itertools +import json +import os +import shlex +import shutil +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path +from typing import Any +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) +import pr_cleanup +import pr_review + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "spec")) + + +CLEANUP_HEAD = "a" * 40 +CLEANUP_BRANCH = "feature/example-topic" + + +def fork_head(number: int) -> dict: + """An open pull request headed on a same-named branch in a fork, not in `o/r`.""" + return {"number": number, "headRepository": {"nameWithOwner": f"fork{number}/r"}} + + +def cleanup_pr(**overrides: object) -> dict: + """A merged pull request into `develop` from a head in o/r, every field overridable.""" + pr: dict[str, object] = { + "merged": True, + "baseRefName": "develop", + "headRefName": CLEANUP_BRANCH, + "headRefOid": CLEANUP_HEAD, + "headRepository": {"nameWithOwner": "o/r"}, + } + pr.update(overrides) + return pr + + +class CleanupCase(unittest.TestCase): + """Drive `cleanup` against crafted reads, so no case reaches GitHub or deletes anything.""" + + def setUp(self) -> None: + self.out = self.enterContext(contextlib.redirect_stdout(io.StringIO())) + self.err = self.enterContext(contextlib.redirect_stderr(io.StringIO())) + self.enterContext(mock.patch.object(pr_review, "origin_owner", return_value="o")) + self.enterContext(mock.patch.object(pr_review, "READ_RETRY_DELAYS", ())) + self.enterContext( + mock.patch.object(pr_cleanup.handoff, "registry", return_value=("o", {"r"})) + ) + self.docs: list[tuple[str, dict]] = [] + self.rest: list[str] = [] + + def wire( + self, + pr: dict | None = None, + default: str = "main", + refs: list[object] | None = None, + rules: object = (), + protected: object = False, + delete_fails: bool = False, + heads: list[int] | None = None, + bases: list[int] | None = None, + head_pages: list[list[dict]] | None = None, + head_answer: object = None, + base_answer: object = None, + ) -> None: + """Answer each document in turn, `refs` holding one answer per ref read in order. + + A ref answer is a tip, None for no such branch, or an exception the read raises. + `head_pages` pages the heads connection, each page its nodes, where `heads` is one page + of this repository's own. An answer given whole replaces that read's repository, or is + raised where it is an exception. + """ + pending = list(refs if refs is not None else [CLEANUP_HEAD, None]) + local = [{"number": n, "headRepository": {"nameWithOwner": "o/r"}} for n in heads or []] + pages = head_pages if head_pages is not None else [local] + + def fake(query: str, variables: dict, **_: object) -> pr_cleanup.shared.Response: + self.docs.append((query, variables)) + if "pullRequest(number" in query: + repository = {"defaultBranchRef": {"name": default}, "pullRequest": pr} + return pr_cleanup.shared.Response({"repository": repository}, []) + if "heads: pullRequests" in query: + self.assertEqual(CLEANUP_BRANCH, variables["b"]) + if isinstance(head_answer, Exception): + raise head_answer + if head_answer is not None: + return pr_cleanup.shared.Response({"repository": head_answer}, []) + at = int(variables.get("after", "c0")[1:]) + more = at + 1 < len(pages) + page = {"hasNextPage": more, "endCursor": f"c{at + 1}" if more else None} + found = {"heads": {"pageInfo": page, "nodes": pages[at]}} + return pr_cleanup.shared.Response({"repository": found}, []) + if "bases: pullRequests" in query: + self.assertEqual(CLEANUP_BRANCH, variables["b"]) + if isinstance(base_answer, Exception): + raise base_answer + if base_answer is not None: + return pr_cleanup.shared.Response({"repository": base_answer}, []) + listed = [{"number": n} for n in bases or []] + based = {"bases": {"totalCount": len(listed), "nodes": listed}} + return pr_cleanup.shared.Response({"repository": based}, []) + if "deleteRef" in query: + if delete_fails: + raise pr_cleanup.shared.GraphQLError("gh graphql reported errors") + return pr_cleanup.shared.Response({"deleteRef": {"clientMutationId": None}}, []) + if "qualifiedName" in query: + answer = pending.pop(0) + if isinstance(answer, Exception): + raise answer + ref = None if answer is None else {"id": "REF_read", "target": {"oid": answer}} + return pr_cleanup.shared.Response({"repository": {"ref": ref}}, []) + raise AssertionError(f"unexpected document: {query[:60]}") + + def rest( + path: str, jq: str | None = None, raw: bool = False + ) -> subprocess.CompletedProcess: + self.rest.append(path) + if "/rules/branches/" in path: + body = rules + else: + body = {"name": CLEANUP_BRANCH, "protected": protected} + if isinstance(body, Exception): + return subprocess.CompletedProcess([], 1, "", "gh: Not Found (HTTP 404)") + text = json.dumps(list(body) if isinstance(body, tuple) else body) + return subprocess.CompletedProcess([], 0, text, "") + + self.enterContext(mock.patch.object(pr_cleanup.shared, "request", side_effect=fake)) + self.enterContext(mock.patch.object(pr_review, "gh_rest", side_effect=rest)) + + def run_cleanup(self, repo: str = "o/r") -> int: + return pr_review.main(["cleanup", "7", "--repo", repo]) + + def deleted(self) -> bool: + return any("deleteRef" in q for q, _ in self.docs) + + +class TestCleanupDeletesOnlyAVerifiedMergedBranch(CleanupCase): + def test_a_matching_tip_is_deleted_by_the_id_just_read_and_confirmed_gone(self) -> None: + """Two exact reads by qualified name, the tip before the delete and the read back after.""" + self.wire(cleanup_pr()) + self.assertEqual(0, self.run_cleanup()) + delete = next(v for q, v in self.docs if "deleteRef" in q) + self.assertEqual({"refId": "REF_read"}, delete) + reads = [v for q, v in self.docs if "qualifiedName" in q] + self.assertEqual([f"refs/heads/{CLEANUP_BRANCH}"] * 2, [v["q"] for v in reads]) + self.assertIn("status=DELETED", self.out.getvalue()) + + def test_a_branch_already_gone_is_done_and_deletes_nothing(self) -> None: + self.wire(cleanup_pr(), refs=[None]) + self.assertEqual(0, self.run_cleanup()) + self.assertFalse(self.deleted()) + self.assertIn("status=ALREADY_GONE", self.out.getvalue()) + + def test_a_moved_tip_refuses_and_names_both_commits(self) -> None: + moved = "b" * 40 + self.wire(cleanup_pr(), refs=[moved]) + self.assertEqual(1, self.run_cleanup()) + self.assertFalse(self.deleted()) + out = self.out.getvalue() + self.assertIn("status=TIP_MOVED", out) + self.assertIn(moved, out) + self.assertIn(CLEANUP_HEAD, out) + + def test_a_ref_still_there_after_the_delete_is_not_reported_deleted(self) -> None: + self.wire(cleanup_pr(), refs=[CLEANUP_HEAD, CLEANUP_HEAD]) + self.assertEqual(2, self.run_cleanup()) + self.assertTrue(self.deleted()) + self.assertIn("status=DELETE_NOT_CONFIRMED", self.out.getvalue()) + self.assertNotIn("status=DELETED", self.out.getvalue()) + + def test_a_read_back_that_does_not_answer_is_not_reported_deleted(self) -> None: + unread = pr_cleanup.shared.GraphQLError("gh graphql failed rc=1") + self.wire(cleanup_pr(), refs=[CLEANUP_HEAD, unread]) + self.assertEqual(2, self.run_cleanup()) + self.assertTrue(self.deleted()) + self.assertIn("status=DELETE_NOT_CONFIRMED", self.out.getvalue()) + + def test_a_delete_reporting_failure_is_decided_by_the_read_back(self) -> None: + """A failed-looking delete may have landed, so the ref read decides rather than the error.""" + self.wire(cleanup_pr(), refs=[CLEANUP_HEAD, None], delete_fails=True) + self.assertEqual(0, self.run_cleanup()) + out = self.out.getvalue() + self.assertIn("the delete reported a failure", out) + self.assertIn("status=DELETED", out) + + def test_a_delete_reporting_failure_with_the_ref_still_there_exits_2(self) -> None: + self.wire(cleanup_pr(), refs=[CLEANUP_HEAD, CLEANUP_HEAD], delete_fails=True) + self.assertEqual(2, self.run_cleanup()) + self.assertIn("status=DELETE_NOT_CONFIRMED", self.out.getvalue()) + + +class TestCleanupRefusesBeforeAnyDelete(CleanupCase): + def assert_refused(self, code: int = 1, status: str = "status=REFUSED") -> None: + self.assertEqual(code, self.run_cleanup()) + self.assertFalse(self.deleted()) + self.assertIn(status, self.out.getvalue()) + + def test_an_unmerged_pull_request_is_refused(self) -> None: + self.wire(cleanup_pr(merged=False)) + self.assert_refused() + + def test_a_base_other_than_develop_is_refused(self) -> None: + self.wire(cleanup_pr(baseRefName="main")) + self.assert_refused() + + def test_a_head_in_another_repository_is_refused(self) -> None: + self.wire(cleanup_pr(headRepository={"nameWithOwner": "o/r-fork"})) + self.assert_refused() + + def test_a_head_repository_gone_is_refused(self) -> None: + self.wire(cleanup_pr(headRepository=None)) + self.assert_refused() + + def test_a_develop_head_is_refused(self) -> None: + self.wire(cleanup_pr(headRefName="develop")) + self.assert_refused() + + def test_a_main_head_is_refused_where_main_is_not_the_default(self) -> None: + self.wire(cleanup_pr(headRefName="main"), default="trunk") + self.assert_refused() + + def test_the_default_branch_read_live_is_refused(self) -> None: + self.wire(cleanup_pr(headRefName="trunk"), default="trunk") + self.assert_refused() + + def test_a_ruleset_on_the_branch_is_refused(self) -> None: + self.wire(cleanup_pr(), rules=[{"type": "deletion"}]) + self.assert_refused() + self.assertIn("deletion", self.out.getvalue()) + + def test_classic_branch_protection_is_refused(self) -> None: + self.wire(cleanup_pr(), protected=True) + self.assert_refused() + + def test_an_unread_rule_set_stops_at_2_rather_than_reading_as_none(self) -> None: + self.wire(cleanup_pr(), rules=RuntimeError("unread")) + self.assert_refused(2, "status=UNREAD") + self.assertIn("HTTP 404", self.err.getvalue()) + self.assertIn("rc=1", self.out.getvalue()) + + def test_an_open_pull_request_headed_on_the_branch_is_refused_and_named(self) -> None: + self.wire(cleanup_pr(), heads=[41]) + self.assert_refused() + self.assertIn("#41 (head)", self.out.getvalue()) + + def test_an_open_pull_request_based_on_the_branch_is_refused_and_named(self) -> None: + self.wire(cleanup_pr(), bases=[42, 43]) + self.assert_refused() + self.assertIn("#42 (base), #43 (base)", self.out.getvalue()) + + def test_an_open_pull_request_read_that_does_not_answer_stops_at_2(self) -> None: + bad = pr_cleanup.shared.GraphQLError("gh graphql failed rc=1") + page = {"hasNextPage": False, "endCursor": None} + malformed: list[dict[str, object]] = [ + {"head_answer": bad}, + {"head_answer": {"heads": {"nodes": []}}}, + {"head_answer": {"heads": {"pageInfo": page, "nodes": None}}}, + {"head_answer": {"heads": {"pageInfo": page, "nodes": ["#9"]}}}, + {"head_answer": {"heads": {"pageInfo": {"hasNextPage": True}, "nodes": []}}}, + {"base_answer": bad}, + {"base_answer": {"bases": {"totalCount": "0", "nodes": []}}}, + ] + for answer in malformed: + with self.subTest(answer=answer): + self.docs.clear() + self.wire( + cleanup_pr(), + head_answer=answer.get("head_answer"), + base_answer=answer.get("base_answer"), + ) + self.assert_refused(2, "status=UNREAD") + + def test_an_unread_heads_page_past_the_first_stops_at_2(self) -> None: + """A page that does not answer is no pull request missing, however clean the first was.""" + self.wire(cleanup_pr(), head_pages=[[fork_head(9)], [fork_head(10)]]) + request = pr_cleanup.shared.request + assert isinstance(request, mock.Mock) + answer = request.side_effect + + def second_page_fails(query: str, variables: dict, **kw: object) -> object: + if "heads: pullRequests" in query and variables.get("after"): + raise pr_cleanup.shared.GraphQLError("gh graphql failed rc=1") + return answer(query, variables, **kw) + + request.side_effect = second_page_fails + self.assert_refused(2, "status=UNREAD") + + def test_more_open_base_pull_requests_than_the_page_holds_are_refused(self) -> None: + full = {"bases": {"totalCount": 25, "nodes": []}} + self.wire(cleanup_pr(), base_answer=full) + self.assert_refused() + self.assertIn("25 more with the branch as base", self.out.getvalue()) + + def test_a_forks_pull_request_on_a_same_named_branch_is_not_a_user(self) -> None: + self.wire(cleanup_pr(), head_pages=[[fork_head(9)]]) + self.assertEqual(0, self.run_cleanup()) + self.assertTrue(self.deleted()) + + def test_fork_pull_requests_filling_every_page_are_not_users(self) -> None: + """Past the first page, forks alone sharing the branch name leave nothing to refuse.""" + pages = [[fork_head(n) for n in range(k, k + 100)] for k in (100, 200, 300)] + self.wire(cleanup_pr(), head_pages=pages) + self.assertEqual(0, self.run_cleanup()) + self.assertTrue(self.deleted()) + reads = [v.get("after") for q, v in self.docs if "heads: pullRequests" in q] + self.assertEqual([None, "c1", "c2"], reads) + self.assertNotIn("more with the branch", self.out.getvalue()) + + def test_a_local_pull_request_past_the_first_page_is_refused_and_named(self) -> None: + local = {"number": 512, "headRepository": {"nameWithOwner": "O/R"}} + pages = [[fork_head(n) for n in range(100, 200)], [fork_head(200), local]] + self.wire(cleanup_pr(), head_pages=pages) + self.assert_refused() + self.assertIn("#512 (head)", self.out.getvalue()) + self.assertNotIn("#200", self.out.getvalue()) + + def test_a_rule_read_that_is_not_a_list_stops_at_2(self) -> None: + self.wire(cleanup_pr(), rules={"message": "Upgrade to GitHub Pro"}) + self.assert_refused(2, "status=UNREAD") + + def test_an_unread_protection_flag_stops_at_2(self) -> None: + self.wire(cleanup_pr(), protected=None) + self.assert_refused(2, "status=UNREAD") + + def test_a_branch_name_that_changes_the_rest_path_stops_at_2(self) -> None: + self.wire(cleanup_pr(headRefName="feature/a?b"), refs=[CLEANUP_HEAD]) + self.assert_refused(2, "status=UNREAD") + self.assertEqual([], self.rest) + + def test_an_unread_pull_request_stops_at_2(self) -> None: + self.wire(None) + self.assert_refused(2, "status=UNREAD") + + def test_an_unread_tip_stops_at_2(self) -> None: + self.wire(cleanup_pr(), refs=[pr_cleanup.shared.GraphQLError("gh graphql failed rc=1")]) + self.assert_refused(2, "status=UNREAD") + + def test_an_owner_other_than_the_checkout_is_out_of_scope_before_any_read(self) -> None: + self.wire(cleanup_pr()) + self.assertEqual(64, self.run_cleanup(repo="x/r")) + self.assertEqual([], self.docs) + self.assertIn("status=OUT_OF_SCOPE", self.out.getvalue()) + + def test_an_owner_other_than_the_registry_is_refused_before_any_read(self) -> None: + self.wire(cleanup_pr()) + with mock.patch.object(pr_cleanup.handoff, "registry", return_value=("p", {"r"})): + self.assertEqual(1, self.run_cleanup()) + self.assertEqual([], self.docs) + self.assertIn("status=REFUSED", self.out.getvalue()) + + def test_an_unregistered_repository_that_is_not_a_fork_is_refused(self) -> None: + self.wire(cleanup_pr()) + flags = {"hasIssuesEnabled": True, "isFork": False} + with mock.patch.object(pr_cleanup.handoff, "gh_json", return_value=flags): + self.assertEqual(1, self.run_cleanup(repo="o/unlisted")) + self.assertEqual([], self.docs) + + def test_an_unregistered_fork_under_the_owner_is_admitted(self) -> None: + self.wire(cleanup_pr(headRepository={"nameWithOwner": "o/forked"})) + flags = {"hasIssuesEnabled": True, "isFork": True} + with mock.patch.object(pr_cleanup.handoff, "gh_json", return_value=flags): + self.assertEqual(0, self.run_cleanup(repo="o/forked")) + self.assertTrue(self.deleted()) + + def test_an_unreadable_registry_stops_at_2(self) -> None: + self.wire(cleanup_pr()) + failure = pr_cleanup.handoff.Execution("could not read the fleet registry") + with mock.patch.object(pr_cleanup.handoff, "registry", side_effect=failure): + self.assertEqual(2, self.run_cleanup()) + self.assertEqual([], self.docs) + + +EDIT_PICKS = ( + r"import sys,re,pathlib; p=pathlib.Path(sys.argv[1]); " + r"p.write_text(re.sub(r\"^pick\", \"edit\", p.read_text(), flags=re.M))" +) +SEQUENCE_EDITOR = shlex.quote(sys.executable) + ' -c "' + EDIT_PICKS + '"' + + +def run_git(cwd: str, *args: str) -> str: + """One git call in a throwaway repository, failing the test on a nonzero exit.""" + done = subprocess.run( + ["git", "-C", cwd, *args], capture_output=True, text=True, encoding="utf-8", check=True + ) + return done.stdout.strip() + + +class LocalCleanupCase(CleanupCase): + """A bare origin, a primary clone naming o/r, and linked worktrees, all real git in a temp dir. + + Only the GitHub reads and writes are mocked, so every local removal below is git's own. + """ + + def setUp(self) -> None: + super().setUp() + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = os.path.realpath(tmp.name) + self.enterContext( + mock.patch.dict( + os.environ, {"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_SYSTEM": os.devnull} + ) + ) + self.bare = os.path.join(self.root, "origin.git") + self.primary = os.path.join(self.root, "primary") + self.seed = os.path.join(self.root, "seed") + subprocess.run( + ["git", "init", "--bare", "-b", "develop", self.bare], check=True, capture_output=True + ) + subprocess.run(["git", "init", "-b", "develop", self.seed], check=True, capture_output=True) + self.configure(self.seed) + self.commit(self.seed, "seed") + run_git(self.seed, "push", self.bare, "develop:develop", "develop:main") + subprocess.run(["git", "clone", self.bare, self.primary], check=True, capture_output=True) + self.configure(self.primary) + run_git(self.primary, "branch", "main", "origin/main") + run_git(self.primary, "config", f"url.{self.bare}.insteadOf", "https://github.com/o/r.git") + run_git(self.primary, "remote", "set-url", "origin", "https://github.com/o/r.git") + self.count = 0 + + def configure(self, repo: str) -> None: + run_git(repo, "config", "user.name", "Test User") + run_git(repo, "config", "user.email", "test@example.com") + run_git(repo, "config", "commit.gpgsign", "false") + + def commit(self, repo: str, message: str) -> str: + run_git(repo, "commit", "--allow-empty", "-m", message) + return run_git(repo, "rev-parse", "HEAD") + + def worktree(self, branch: str, commits: int = 1) -> tuple[str, str]: + """A linked worktree on a new local branch with `commits` unpushed commits.""" + path = os.path.join(self.root, "wt", branch.replace("/", "_")) + run_git(self.primary, "worktree", "add", "-b", branch, path, "origin/develop") + for _ in range(commits): + self.count += 1 + self.commit(path, f"work {self.count}") + return path, run_git(path, "rev-parse", "HEAD") + + def advance_origin(self) -> str: + """A new commit on origin's develop, as a merge into it would leave.""" + run_git(self.seed, "pull", "--ff-only", self.bare, "develop") + self.count += 1 + tip = self.commit(self.seed, f"merge {self.count}") + run_git(self.seed, "push", self.bare, "develop:develop") + return tip + + def branches(self) -> list[str]: + out = run_git(self.primary, "for-each-ref", "--format=%(refname:short)", "refs/heads") + return out.splitlines() + + def listed(self) -> list[str]: + out = run_git(self.primary, "worktree", "list", "--porcelain") + return [ + os.path.realpath(ln.split(" ", 1)[1]) + for ln in out.splitlines() + if ln.startswith("worktree ") + ] + + def run_local(self, checkout: str | None = None) -> int: + argv = ["cleanup", "7", "--repo", "o/r", "--checkout", checkout or self.primary] + return pr_review.main(argv) + + def pause_rebase(self, repo: str) -> None: + env = {**os.environ, "GIT_SEQUENCE_EDITOR": SEQUENCE_EDITOR} + argv = ["git", "-C", repo, "rebase", "-i", "HEAD~2"] + subprocess.run(argv, env=env, capture_output=True, check=True) + + def wire_merged(self, tip: str) -> None: + self.wire(cleanup_pr(headRefOid=tip), refs=[tip, tip, None]) + + +class TestCleanupLocalHalf(LocalCleanupCase): + def test_the_worktree_and_branch_go_and_the_base_clone_catches_up(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + merged = self.advance_origin() + self.wire_merged(tip) + self.assertEqual(0, self.run_local()) + self.assertFalse(os.path.exists(path)) + self.assertNotIn(CLEANUP_BRANCH, self.branches()) + self.assertEqual([self.primary], self.listed()) + self.assertEqual(merged, run_git(self.primary, "rev-parse", "HEAD")) + out = self.out.getvalue() + self.assertIn("status=DELETED", out) + self.assertIn("status=CLEANED", out) + self.assertIn("## develop...origin/develop", out) + + def test_without_a_checkout_nothing_local_is_touched(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + self.wire(cleanup_pr(headRefOid=tip), refs=[tip, None]) + self.assertEqual(0, pr_review.main(["cleanup", "7", "--repo", "o/r"])) + self.assertTrue(os.path.isdir(path)) + self.assertIn(CLEANUP_BRANCH, self.branches()) + self.assertNotIn("status=CLEANED", self.out.getvalue()) + + def test_a_branch_already_gone_locally_still_returns_the_base_clone(self) -> None: + merged = self.advance_origin() + self.wire(cleanup_pr(headRefOid=merged), refs=[merged, merged, None]) + self.assertEqual(0, self.run_local()) + self.assertIn("is already gone", self.out.getvalue()) + self.assertEqual(merged, run_git(self.primary, "rev-parse", "HEAD")) + + def test_a_moved_local_tip_refuses_and_removes_nothing(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + self.count += 1 + later = self.commit(path, f"unpushed {self.count}") + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + out = self.out.getvalue() + self.assertIn("status=LOCAL_TIP_MOVED", out) + self.assertIn(tip, out) + self.assertIn(later, out) + self.assertFalse(self.deleted()) + self.assertIn("remote branch included", self.out.getvalue()) + self.assertTrue(os.path.isdir(path)) + self.assertEqual(later, run_git(self.primary, "rev-parse", CLEANUP_BRANCH)) + + def test_a_dirty_worktree_refuses_and_removes_nothing(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + Path(path, "scratch.txt").write_text("x", encoding="utf-8") + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + self.assertIn("status=WORKTREE_DIRTY", self.out.getvalue()) + self.assertFalse(self.deleted()) + self.assertIn("remote branch included", self.out.getvalue()) + self.assertTrue(os.path.isdir(path)) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_a_locked_worktree_refuses_and_removes_nothing(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + run_git(self.primary, "worktree", "lock", path) + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) + self.assertFalse(self.deleted()) + self.assertIn("remote branch included", self.out.getvalue()) + self.assertTrue(os.path.isdir(path)) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_a_checkout_whose_origin_is_another_repository_is_refused_before_the_remote_delete( + self, + ) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + run_git(self.primary, "remote", "set-url", "origin", "git@github.com:other/repo.git") + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + self.assertIn("status=BAD_CHECKOUT", self.out.getvalue()) + self.assertFalse(self.deleted()) + self.assertTrue(os.path.isdir(path)) + + def test_a_linked_worktree_is_not_a_primary_checkout(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + self.wire_merged(tip) + self.assertEqual(1, self.run_local(path)) + self.assertIn("status=BAD_CHECKOUT", self.out.getvalue()) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_a_remote_refusal_skips_the_local_half(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + self.wire(cleanup_pr(headRefOid=tip, merged=False)) + self.assertEqual(1, self.run_local()) + self.assertNotIn("status=CLEANED", self.out.getvalue()) + self.assertTrue(os.path.isdir(path)) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_a_primary_holding_the_branch_moves_to_develop_before_the_delete(self) -> None: + run_git(self.primary, "checkout", "-b", CLEANUP_BRANCH) + tip = self.commit(self.primary, "primary work") + self.advance_origin() + self.wire_merged(tip) + self.assertEqual(0, self.run_local()) + self.assertNotIn(CLEANUP_BRANCH, self.branches()) + self.assertEqual("develop", run_git(self.primary, "symbolic-ref", "--short", "HEAD")) + out = self.out.getvalue() + self.assertLess(out.index("switched"), out.index("deleting:")) + + def test_a_rebase_paused_in_the_primary_on_the_branch_refuses(self) -> None: + run_git(self.primary, "checkout", "-b", CLEANUP_BRANCH) + for n in range(3): + self.commit(self.primary, f"primary work {n}") + tip = run_git(self.primary, "rev-parse", "HEAD") + self.pause_rebase(self.primary) + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) + self.assertFalse(self.deleted()) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_the_closing_informational_reads_never_fail_a_landed_cleanup(self) -> None: + _, tip = self.worktree(CLEANUP_BRANCH) + self.wire_merged(tip) + real = pr_cleanup.cleanup_git + + def flaky(root: str, *args: str, **kw: Any) -> subprocess.CompletedProcess[str]: + if args[:1] == ("status",) and "--branch" in args: + raise pr_cleanup.CleanupUnread("status read failed") + return real(root, *args, **kw) + + listing = pr_cleanup.cleanup_worktrees + + def failing_list(primary: str) -> list[pr_cleanup.Worktree]: + if "status unavailable" in self.out.getvalue(): + raise pr_cleanup.CleanupUnread("list read failed") + return listing(primary) + + with ( + mock.patch.object(pr_cleanup, "cleanup_git", side_effect=flaky), + mock.patch.object(pr_cleanup, "cleanup_worktrees", side_effect=failing_list), + ): + self.assertEqual(0, self.run_local()) + out = self.out.getvalue() + self.assertIn("status unavailable", out) + self.assertIn("worktrees listed: unavailable", out) + self.assertIn("status=CLEANED", out) + + def test_a_primary_stopped_mid_cherry_pick_on_the_branch_refuses(self) -> None: + run_git(self.primary, "checkout", "-b", CLEANUP_BRANCH) + tip = self.commit(self.primary, "primary work") + admin = Path(run_git(self.primary, "rev-parse", "--absolute-git-dir")) + (admin / "CHERRY_PICK_HEAD").write_text(tip + "\n", encoding="utf-8") + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) + self.assertFalse(self.deleted()) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_a_remote_branch_that_moved_before_the_delete_is_not_deleted(self) -> None: + _, tip = self.worktree(CLEANUP_BRANCH) + self.wire(cleanup_pr(headRefOid=tip), refs=[tip, "c" * 40]) + self.assertEqual(1, self.run_local()) + self.assertIn("status=TIP_MOVED", self.out.getvalue()) + self.assertFalse(self.deleted()) + + def test_an_origin_branch_that_differs_from_the_merged_head_refuses(self) -> None: + path, _ = self.worktree(CLEANUP_BRANCH) + run_git(path, "push", "origin", CLEANUP_BRANCH) + self.count += 1 + tip = self.commit(path, f"after the push {self.count}") + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + self.assertIn("status=TIP_MOVED", self.out.getvalue()) + self.assertFalse(self.deleted()) + + def test_a_primary_holding_the_branch_with_tracked_changes_refuses(self) -> None: + run_git(self.primary, "checkout", "-b", CLEANUP_BRANCH) + Path(self.primary, "tracked.txt").write_text("a", encoding="utf-8") + run_git(self.primary, "add", "tracked.txt") + tip = run_git(self.primary, "rev-parse", "HEAD") + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + self.assertIn("status=BASE_DIRTY", self.out.getvalue()) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_a_diverged_develop_is_reported_without_failing_the_removals(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + self.advance_origin() + run_git(self.primary, "fetch", "origin") + self.count += 1 + self.commit(self.primary, f"local only {self.count}") + self.wire_merged(tip) + self.assertEqual(0, self.run_local()) + out = self.out.getvalue() + self.assertLess(out.index("removed worktree"), out.index("status=BASE_NOT_FF")) + self.assertIn("base=kept", out) + self.assertFalse(os.path.exists(path)) + self.assertNotIn(CLEANUP_BRANCH, self.branches()) + + def test_the_shell_directory_inside_a_removed_worktree_is_handled_per_platform(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + self.wire_merged(tip) + before = os.getcwd() + self.addCleanup(os.chdir, before) + os.chdir(path) + if pr_cleanup.ON_WINDOWS: + self.assertEqual(1, self.run_local()) + self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) + self.assertTrue(os.path.isdir(path)) + else: + self.assertEqual(0, self.run_local()) + self.assertIn("note: the shell's directory", self.out.getvalue()) + self.assertFalse(os.path.exists(path)) + + def test_a_shell_inside_the_worktree_refuses_on_windows(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + self.wire_merged(tip) + before = os.getcwd() + self.addCleanup(os.chdir, before) + os.chdir(path) + with mock.patch.object(pr_cleanup, "ON_WINDOWS", True): + self.assertEqual(1, self.run_local()) + self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) + self.assertTrue(os.path.isdir(path)) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_a_worktree_with_submodules_refuses_and_removes_nothing(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + Path(path, ".gitmodules").write_text("", encoding="utf-8") + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) + self.assertTrue(os.path.isdir(path)) + + def test_a_rerun_with_the_primary_elsewhere_is_done_with_the_base_kept(self) -> None: + run_git(self.primary, "checkout", "-b", "elsewhere") + self.wire(cleanup_pr(headRefOid=CLEANUP_HEAD), refs=[CLEANUP_HEAD, CLEANUP_HEAD, None]) + self.assertEqual(0, self.run_local()) + out = self.out.getvalue() + self.assertIn("is already gone", out) + self.assertIn("base=kept", out) + + def test_a_tip_that_moves_before_the_delete_is_a_refusal_after_the_removals(self) -> None: + _, tip = self.worktree(CLEANUP_BRANCH) + self.wire_merged(tip) + real = pr_cleanup.cleanup_tip + heads = [] + + def moving(primary: str, ref: str) -> str | None: + if not ref.startswith("refs/heads/"): + return real(primary, ref) + heads.append(ref) + return "b" * 40 if len(heads) == 3 else real(primary, ref) + + with mock.patch.object(pr_cleanup, "cleanup_tip", side_effect=moving): + self.assertEqual(1, self.run_local()) + out = self.out.getvalue() + self.assertLess(out.index("removed worktree"), out.index("status=LOCAL_TIP_MOVED")) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_an_unconfirmed_branch_delete_is_exit_2(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + self.wire_merged(tip) + with mock.patch.object(pr_cleanup, "cleanup_tip", side_effect=itertools.repeat(tip)): + self.assertEqual(2, self.run_local()) + self.assertIn("status=LOCAL_DELETE_NOT_CONFIRMED", self.out.getvalue()) + self.assertFalse(os.path.exists(path)) + + def test_a_primary_on_another_branch_is_left_there(self) -> None: + _, tip = self.worktree(CLEANUP_BRANCH) + run_git(self.primary, "checkout", "-b", "elsewhere") + self.wire_merged(tip) + self.assertEqual(0, self.run_local()) + self.assertEqual("elsewhere", run_git(self.primary, "symbolic-ref", "--short", "HEAD")) + out = self.out.getvalue() + self.assertIn("keep base-not-on-develop", out) + self.assertIn("base=kept", out) + + def test_a_branch_being_bisected_in_another_worktree_is_kept(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH, commits=3) + run_git(path, "bisect", "start") + run_git(path, "bisect", "bad", "HEAD") + run_git(path, "bisect", "good", "HEAD~2") + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) + self.assertFalse(self.deleted()) + self.assertIn(CLEANUP_BRANCH, self.branches()) + self.assertTrue(os.path.isdir(path)) + + def test_a_branch_being_rebased_in_another_worktree_is_kept(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH, commits=3) + self.pause_rebase(path) + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) + self.assertFalse(self.deleted()) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_a_prunable_entry_holding_the_branch_is_removed_without_force(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + shutil.rmtree(path) + self.wire_merged(tip) + self.assertEqual(0, self.run_local()) + self.assertEqual([self.primary], self.listed()) + self.assertNotIn(CLEANUP_BRANCH, self.branches()) + + def test_a_local_tip_behind_the_merged_head_is_removed(self) -> None: + path, _ = self.worktree(CLEANUP_BRANCH) + self.count += 1 + ahead = self.commit(path, f"merged tip {self.count}") + run_git(self.primary, "branch", "ahead", ahead) + run_git(path, "reset", "--hard", "HEAD~1") + self.wire_merged(ahead) + self.assertEqual(0, self.run_local()) + self.assertNotIn(CLEANUP_BRANCH, self.branches()) + + def test_a_partly_removed_worktree_is_an_unconfirmed_removal(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + self.wire_merged(tip) + real = pr_cleanup.cleanup_git + + def partial(root: str, *args: str, **kw: Any) -> subprocess.CompletedProcess[str]: + if args[:2] == ("worktree", "remove"): + real(root, *args) + os.makedirs(path) + raise pr_cleanup.CleanupUnread("could not delete every file") + return real(root, *args, **kw) + + with mock.patch.object(pr_cleanup, "cleanup_git", side_effect=partial): + self.assertEqual(2, self.run_local()) + self.assertIn(path, self.out.getvalue()) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_a_branch_delete_git_refuses_is_a_kept_branch(self) -> None: + _, tip = self.worktree(CLEANUP_BRANCH) + self.wire_merged(tip) + real = pr_cleanup.cleanup_git + + def refusing(root: str, *args: str, **kw: Any) -> subprocess.CompletedProcess[str]: + if args[:2] == ("branch", "-D"): + return subprocess.CompletedProcess([], 1, "", "error: used by worktree") + return real(root, *args, **kw) + + with mock.patch.object(pr_cleanup, "cleanup_git", side_effect=refusing): + self.assertEqual(1, self.run_local()) + self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_a_worktree_mid_operation_refuses_and_removes_nothing(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + admin = Path(run_git(path, "rev-parse", "--absolute-git-dir")) + (admin / "MERGE_HEAD").write_text(tip + "\n", encoding="utf-8") + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) + self.assertTrue(os.path.isdir(path)) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_a_worktree_removed_by_someone_else_mid_run_is_done(self) -> None: + path, tip = self.worktree(CLEANUP_BRANCH) + self.wire_merged(tip) + real = pr_cleanup.cleanup_git + + def racing(root: str, *args: str, **kw: Any) -> subprocess.CompletedProcess[str]: + if args[:2] == ("worktree", "remove"): + real(root, *args) + raise pr_cleanup.CleanupUnread("another process got there first") + return real(root, *args, **kw) + + with mock.patch.object(pr_cleanup, "cleanup_git", side_effect=racing): + self.assertEqual(0, self.run_local()) + self.assertIn("already gone", self.out.getvalue()) + self.assertFalse(os.path.exists(path)) + self.assertNotIn(CLEANUP_BRANCH, self.branches()) + + def test_a_branch_deleted_by_someone_else_before_the_delete_is_already_gone(self) -> None: + _, tip = self.worktree(CLEANUP_BRANCH) + self.wire_merged(tip) + real = pr_cleanup.cleanup_tip + calls = [] + + def vanishing(primary: str, ref: str) -> str | None: + if ref.startswith("refs/heads/"): + calls.append(ref) + if len(calls) == 3 and ref.startswith("refs/heads/"): + run_git(primary, "branch", "-D", "--", CLEANUP_BRANCH) + return None + return real(primary, ref) + + with mock.patch.object(pr_cleanup, "cleanup_tip", side_effect=vanishing): + self.assertEqual(0, self.run_local()) + self.assertIn("status=CLEANED", self.out.getvalue()) + + def test_a_primary_that_cannot_leave_the_branch_keeps_it_and_exits_1(self) -> None: + Path(self.seed, "clash.txt").write_text("x", encoding="utf-8") + run_git(self.seed, "add", "clash.txt") + self.commit(self.seed, "add clash") + run_git(self.seed, "push", self.bare, "develop:develop") + run_git(self.primary, "pull", "--ff-only", "origin", "develop") + run_git(self.primary, "checkout", "-b", CLEANUP_BRANCH, "develop~1") + Path(self.primary, "clash.txt").write_text("y", encoding="utf-8") + tip = run_git(self.primary, "rev-parse", "HEAD") + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + self.assertIn("could not leave", self.out.getvalue()) + self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) + self.assertIn("nothing was deleted, remote branch included", self.out.getvalue()) + self.assertFalse(self.deleted()) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + def test_a_develop_held_by_another_worktree_stops_the_primary_leaving(self) -> None: + run_git(self.primary, "checkout", "-b", CLEANUP_BRANCH) + tip = self.commit(self.primary, "primary work") + other = os.path.join(self.root, "wt", "develop-holder") + run_git(self.primary, "worktree", "add", other, "develop") + self.wire_merged(tip) + self.assertEqual(1, self.run_local()) + self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) + self.assertFalse(self.deleted()) + self.assertIn(CLEANUP_BRANCH, self.branches()) + + +class TestCleanupOriginParsing(unittest.TestCase): + def test_https_and_ssh_forms_name_the_repository_case_insensitively(self) -> None: + for url in ( + "https://github.com/O/R.git", + "https://github.com/o/r", + "https://user@github.com/o/r.git/", + "git@github.com:o/R.git", + "ssh://git@github.com/O/r", + ): + found = pr_cleanup.GITHUB_REMOTE.match(url) + self.assertIsNotNone(found, url) + assert found is not None + self.assertEqual("o/r", f"{found[1]}/{found[2]}".lower()) + + def test_other_hosts_and_shapes_do_not_match(self) -> None: + for url in ("https://example.com/o/r.git", "/srv/o/r.git", "https://github.com/o", ""): + self.assertIsNone(pr_cleanup.GITHUB_REMOTE.match(url), url) + + +class TestCleanupSweepArguments(CleanupCase): + def usage(self, *argv: str) -> None: + with self.assertRaises(SystemExit) as caught: + pr_review.main(list(argv)) + self.assertEqual(2, caught.exception.code) + + def test_a_missing_number_is_a_usage_error_outside_the_sweep(self) -> None: + self.usage("status", "--repo", "o/r") + self.usage("cleanup", "--repo", "o/r") + + def test_a_required_number_still_parses_ahead_of_the_options(self) -> None: + class Reached(Exception): + pass + + with ( + mock.patch.object(pr_review, "full_read", side_effect=Reached), + self.assertRaises(Reached), + ): + pr_review.main(["status", "--repo", "o/r", "7"]) + with mock.patch.object(pr_cleanup, "cleanup", return_value=0) as cleaned: + self.assertEqual( + 0, pr_review.main(["cleanup", "--repo", "o/r", "7", "--checkout", "x"]) + ) + cleaned.assert_called_once_with("o", "r", 7, "x") + + def test_the_sweep_flags_are_checked_against_each_other(self) -> None: + self.usage("cleanup", "7", "--sweep", "--repo", "o/r", "--checkout", "/x") + self.usage("cleanup", "--sweep", "--repo", "o/r") + self.usage("cleanup", "7", "--repo", "o/r", "--apply") + self.usage("cleanup", "7", "--repo", "o/r", "--min-age-hours", "1") + self.usage("status", "7", "--repo", "o/r", "--sweep") + + +class TestCleanupSweep(LocalCleanupCase): + def setUp(self) -> None: + super().setUp() + self.merged_prs: dict[str, list[dict]] = {} + self.failing: set[str] = set() + + def age(self, path: str, hours: float) -> None: + """Set every file the sweep reads the age from to `hours` ago.""" + admin = Path(path, ".git").read_text(encoding="utf-8").split(":", 1)[1].strip() + stamp = time.time() - hours * 3600 + for p in (path, *(os.path.join(admin, n) for n in ("HEAD", "index", "logs/HEAD"))): + if os.path.exists(p): + os.utime(p, (stamp, stamp)) + + def age_branch(self, branch: str, hours: float) -> None: + log = os.path.join(self.primary, ".git", "logs", "refs", "heads", branch) + stamp = time.time() - hours * 3600 + os.utime(log, (stamp, stamp)) + + def merged_pr(self, branch: str, tip: str, base: str = "develop") -> None: + node = { + "number": 7, + "baseRefName": base, + "headRefOid": tip, + "headRepository": {"nameWithOwner": "o/r"}, + } + self.merged_prs[branch] = [node] + + def wire_sweep( + self, remote_tip: str | None = None, remote_gone: bool = False, **pr: object + ) -> None: + refs: list[object] = [remote_tip, None] if remote_tip else [] + if remote_gone: + refs = [None] + self.wire(cleanup_pr(headRefOid=remote_tip or CLEANUP_HEAD, **pr), refs=refs) + inner = pr_cleanup.shared.request + + def fake(query: str, variables: dict, **kw: Any) -> pr_cleanup.shared.Response: + if query == pr_cleanup.Q_SWEEP_DEFAULT: + head = {"defaultBranchRef": {"name": "main"}} + return pr_cleanup.shared.Response({"repository": head}, []) + if query == pr_cleanup.Q_SWEEP_MERGED: + if variables["b"] in self.failing: + raise pr_cleanup.shared.GraphQLError("gh graphql reported errors") + nodes = self.merged_prs.get(variables["b"], []) + page = {"merged": {"totalCount": len(nodes), "nodes": nodes}} + return pr_cleanup.shared.Response({"repository": page}, []) + return inner(query, variables, **kw) + + self.enterContext(mock.patch.object(pr_cleanup.shared, "request", side_effect=fake)) + + def sweep(self, *extra: str) -> int: + argv = ["cleanup", "--sweep", "--repo", "o/r", "--checkout", self.primary, *extra] + return pr_review.main(argv) + + def scenario(self) -> dict[str, str]: + """Old and finished items beside every kind of item that must stay.""" + made: dict[str, str] = {} + path, tip = self.worktree(CLEANUP_BRANCH) + self.merged_pr(CLEANUP_BRANCH, tip) + self.age(path, 48) + made["merged"] = path + detached = os.path.join(self.root, "wt", "detached") + run_git(self.primary, "worktree", "add", "--detach", detached, "origin/develop") + self.age(detached, 48) + made["detached"] = detached + gone = os.path.join(self.root, "wt", "gone") + run_git(self.primary, "worktree", "add", "--detach", gone, "origin/develop") + admin = Path(gone, ".git").read_text(encoding="utf-8").split(":", 1)[1].strip() + shutil.rmtree(gone) + old = time.time() - 48 * 3600 + os.utime(os.path.join(admin, "index"), (old, old)) + made["gone"] = gone + fresh = os.path.join(self.root, "wt", "fresh-gone") + run_git(self.primary, "worktree", "add", "--detach", fresh, "origin/develop") + shutil.rmtree(fresh) + made["fresh-gone"] = fresh + recent, recent_tip = self.worktree("recent-work") + self.merged_pr("recent-work", recent_tip) + made["recent"] = recent + unmerged, _ = self.worktree("unmerged-work") + self.age(unmerged, 48) + made["unmerged"] = unmerged + dirty, dirty_tip = self.worktree("dirty-work") + self.merged_pr("dirty-work", dirty_tip) + Path(dirty, "scratch.txt").write_text("x", encoding="utf-8") + self.age(dirty, 48) + made["dirty"] = dirty + locked, locked_tip = self.worktree("locked-work") + self.merged_pr("locked-work", locked_tip) + run_git(self.primary, "worktree", "lock", locked) + self.age(locked, 48) + made["locked"] = locked + run_git(self.primary, "branch", "loose-done", "origin/develop") + self.age_branch("loose-done", 48) + run_git(self.primary, "branch", "loose-recent", "origin/develop") + self.advance_origin() + return made + + def test_a_dry_run_reports_every_item_and_removes_nothing(self) -> None: + made = self.scenario() + before = (sorted(self.branches()), sorted(self.listed())) + self.wire_sweep(remote_tip=run_git(self.primary, "rev-parse", CLEANUP_BRANCH)) + self.assertEqual(0, self.sweep()) + self.assertEqual(before, (sorted(self.branches()), sorted(self.listed()))) + self.assertFalse(self.deleted()) + out = self.out.getvalue() + self.assertIn(f"would-remove worktree {made['merged']}", out) + self.assertIn(f"would-remove worktree {made['detached']} detached", out) + self.assertIn(f"would-remove prunable worktree entry {made['gone']}", out) + self.assertIn("would-remove branch loose-done", out) + self.assertIn(f"would-remove remote branch {CLEANUP_BRANCH} via #7", out) + self.assertIn(f"would-fast-forward develop in {self.primary}", out) + self.assertNotIn("removed ", out.replace("would-remove", "")) + + def test_apply_removes_what_is_finished_and_keeps_the_rest(self) -> None: + made = self.scenario() + tip = run_git(self.primary, "rev-parse", CLEANUP_BRANCH) + self.wire_sweep(remote_tip=tip) + self.assertEqual(0, self.sweep("--apply")) + self.assertIn(made["fresh-gone"], self.listed()) + for gone in ("merged", "detached", "gone"): + self.assertNotIn(made[gone], self.listed(), gone) + self.assertFalse(os.path.exists(made["merged"])) + for kept in ("recent", "unmerged", "dirty", "locked"): + self.assertTrue(os.path.isdir(made[kept]), kept) + self.assertIn(made[kept], self.listed(), kept) + branches = self.branches() + self.assertNotIn(CLEANUP_BRANCH, branches) + self.assertNotIn("loose-done", branches) + for kept in ("develop", "main", "loose-recent", "recent-work", "unmerged-work"): + self.assertIn(kept, branches) + self.assertTrue(self.deleted()) + out = self.out.getvalue() + self.assertIn("keep too-recent", out) + self.assertIn("keep unmerged-commits", out) + self.assertIn("keep dirty", out) + self.assertIn("keep locked", out) + self.assertEqual( + run_git(self.primary, "rev-parse", "origin/develop"), + run_git(self.primary, "rev-parse", "develop"), + ) + + def test_a_read_failure_continues_and_exits_2(self) -> None: + made = self.scenario() + early, _ = self.worktree("aa-failing") + self.age(early, 48) + self.failing.add("aa-failing") + tip = run_git(self.primary, "rev-parse", CLEANUP_BRANCH) + self.wire_sweep(remote_tip=tip) + self.assertEqual(2, self.sweep("--apply")) + out = self.out.getvalue() + self.assertLess(out.index("unread worktree"), out.index("removed worktree")) + self.assertNotIn(made["merged"], self.listed()) + self.assertIn(early, self.listed()) + + def test_the_remote_check_in_a_report_names_a_refusal(self) -> None: + self.scenario() + self.wire_sweep(remote_tip=run_git(self.primary, "rev-parse", CLEANUP_BRANCH), merged=False) + self.assertEqual(0, self.sweep()) + out = self.out.getvalue() + self.assertIn("keep-remote via #7", out) + self.assertNotIn("would-remove remote", out) + self.assertFalse(self.deleted()) + + def test_the_remote_check_in_a_report_names_a_branch_already_gone(self) -> None: + self.scenario() + self.wire_sweep(remote_gone=True) + self.assertEqual(0, self.sweep()) + self.assertIn(f"remote already gone {CLEANUP_BRANCH} via #7", self.out.getvalue()) + + def test_a_loose_branch_whose_tip_moved_is_kept_as_tip_moved(self) -> None: + run_git(self.primary, "branch", "loose-done", "origin/develop") + self.age_branch("loose-done", 48) + self.wire_sweep() + moved = pr_cleanup.CleanupRefused("LOCAL_TIP_MOVED", "moved") + with mock.patch.object(pr_cleanup, "cleanup_delete_branch", side_effect=moved): + self.assertEqual(0, self.sweep("--apply")) + self.assertIn("keep tip-moved branch loose-done", self.out.getvalue()) + + def test_main_and_develop_survive_a_sweep_with_no_age_floor(self) -> None: + run_git(self.primary, "checkout", "-b", "primary-work") + self.wire_sweep() + self.assertEqual(0, self.sweep("--apply", "--min-age-hours", "0")) + for kept in ("main", "develop", "primary-work"): + self.assertIn(kept, self.branches()) + + def test_the_primary_checkout_branch_is_never_touched(self) -> None: + run_git(self.primary, "checkout", "-b", "primary-work") + self.age_branch("primary-work", 48) + self.wire_sweep() + self.assertEqual(0, self.sweep("--apply")) + self.assertIn("primary-work", self.branches()) + for line in self.out.getvalue().splitlines(): + if "primary-work" in line: + self.assertTrue(line.startswith("keep base-not-on-develop"), line) + + def test_a_branch_without_a_reflog_is_kept_as_age_unreadable(self) -> None: + run_git(self.primary, "branch", "loose-done", "origin/develop") + os.remove(os.path.join(self.primary, ".git", "logs", "refs", "heads", "loose-done")) + self.wire_sweep() + self.assertEqual(0, self.sweep("--apply")) + self.assertIn("keep age-unreadable branch loose-done", self.out.getvalue()) + self.assertIn("loose-done", self.branches()) + + def gone_on_branch(self, branch: str, entry_hours: float = 48) -> str: + """A finished, idle branch whose worktree directory is gone, its record `entry_hours` old.""" + gone = os.path.join(self.root, "wt", branch) + run_git(self.primary, "worktree", "add", "-b", branch, gone, "origin/develop") + admin = Path(gone, ".git").read_text(encoding="utf-8").split(":", 1)[1].strip() + shutil.rmtree(gone) + old = time.time() - entry_hours * 3600 + os.utime(os.path.join(admin, "index"), (old, old)) + self.age_branch(branch, 48) + return gone + + def test_a_pruned_entry_s_branch_is_swept_in_the_same_run(self) -> None: + gone = self.gone_on_branch("gone-done") + self.advance_origin() + self.wire_sweep(remote_tip=None) + self.assertEqual(0, self.sweep("--apply")) + self.assertNotIn(gone, self.listed()) + self.assertNotIn("gone-done", self.branches()) + + def test_a_dry_run_reports_a_prunable_entry_s_branch(self) -> None: + self.gone_on_branch("gone-done") + self.advance_origin() + self.wire_sweep(remote_tip=None) + self.assertEqual(0, self.sweep()) + self.assertIn("gone-done", self.branches()) + self.assertIn("would-remove branch gone-done", self.out.getvalue()) + + def test_a_too_recent_prunable_entry_still_holds_its_branch(self) -> None: + gone = self.gone_on_branch("gone-recent", entry_hours=0) + self.advance_origin() + self.wire_sweep(remote_tip=None) + self.assertEqual(0, self.sweep()) + self.assertNotIn("would-remove branch gone-recent", self.out.getvalue()) + self.assertEqual(0, self.sweep("--apply")) + self.assertIn(gone, self.listed()) + self.assertIn("gone-recent", self.branches()) + + def test_a_failed_prune_is_counted_and_the_other_items_still_run(self) -> None: + made = self.scenario() + self.gone_on_branch("gone-failed") + tip = run_git(self.primary, "rev-parse", CLEANUP_BRANCH) + self.wire_sweep(remote_tip=tip) + real = pr_cleanup.cleanup_git + + def failing(root: str, *args: str, **kw: Any) -> subprocess.CompletedProcess[str]: + if args[:2] == ("worktree", "prune"): + raise pr_cleanup.CleanupUnread("prune failed") + return real(root, *args, **kw) + + with mock.patch.object(pr_cleanup, "cleanup_git", side_effect=failing): + self.assertEqual(2, self.sweep("--apply")) + self.assertIn("unread prunable worktree entries", self.out.getvalue()) + self.assertNotIn("branch gone-failed", self.out.getvalue()) + self.assertIn("gone-failed", self.branches()) + self.assertNotIn(made["merged"], self.listed()) + + def test_a_stale_remote_ref_for_a_deleted_branch_is_not_containment(self) -> None: + stale = os.path.join(self.root, "wt", "stale-detached") + run_git(self.primary, "worktree", "add", "--detach", stale, "origin/develop") + self.count += 1 + self.commit(stale, f"only on a deleted branch {self.count}") + run_git(stale, "push", "origin", "HEAD:refs/heads/gone-branch") + run_git(self.primary, "fetch", "origin") + run_git(self.bare, "branch", "-D", "gone-branch") + self.age(stale, 48) + sha = run_git(stale, "rev-parse", "HEAD") + self.wire_sweep() + for extra in ((), ("--apply",)): + run_git(self.primary, "update-ref", "refs/remotes/origin/gone-branch", sha) + self.assertEqual(0, self.sweep(*extra)) + out = self.out.getvalue() + self.assertIn(f"keep unpushed-commits worktree {stale} detached", out) + self.assertNotIn(f"would-remove worktree {stale}", out) + self.assertIn(stale, self.listed()) + + def test_a_primary_paused_mid_rebase_keeps_the_branch_in_both_modes(self) -> None: + run_git(self.primary, "checkout", "-b", "rebasing-work") + for n in range(3): + self.commit(self.primary, f"primary work {n}") + tip = run_git(self.primary, "rev-parse", "HEAD") + self.pause_rebase(self.primary) + self.merged_pr("rebasing-work", tip) + self.age_branch("rebasing-work", 48) + self.wire_sweep() + for extra in ((), ("--apply",)): + self.assertEqual(0, self.sweep(*extra)) + self.assertIn("keep in-progress-operation branch rebasing-work", self.out.getvalue()) + self.assertIn("rebasing-work", self.branches()) + + def test_a_worktree_with_submodules_is_kept(self) -> None: + path, tip = self.worktree("modular-work") + self.merged_pr("modular-work", tip) + Path(path, ".gitmodules").write_text("", encoding="utf-8") + self.age(path, 48) + self.wire_sweep() + self.assertEqual(0, self.sweep("--apply")) + self.assertIn("keep submodules", self.out.getvalue()) + self.assertIn(path, self.listed()) + + def test_a_shell_inside_a_worktree_keeps_it_on_windows(self) -> None: + path, tip = self.worktree("held-work") + self.merged_pr("held-work", tip) + self.age(path, 48) + self.wire_sweep() + before = os.getcwd() + self.addCleanup(os.chdir, before) + os.chdir(path) + with mock.patch.object(pr_cleanup, "ON_WINDOWS", True): + self.assertEqual(0, self.sweep("--apply")) + self.assertIn("keep cwd-inside", self.out.getvalue()) + self.assertIn(path, self.listed()) + + def test_a_worktree_mid_operation_is_kept(self) -> None: + path, tip = self.worktree("paused-work") + self.merged_pr("paused-work", tip) + admin = Path(run_git(path, "rev-parse", "--absolute-git-dir")) + (admin / "BISECT_LOG").write_text("\n", encoding="utf-8") + self.age(path, 48) + self.wire_sweep() + self.assertEqual(0, self.sweep("--apply")) + self.assertIn("keep in-progress-operation", self.out.getvalue()) + self.assertIn(path, self.listed()) + self.assertIn("paused-work", self.branches()) + + def test_a_branch_being_bisected_elsewhere_is_kept_as_in_progress(self) -> None: + path, tip = self.worktree("bisected-work", commits=3) + self.merged_pr("bisected-work", tip) + run_git(path, "bisect", "start") + run_git(path, "bisect", "bad", "HEAD") + run_git(path, "bisect", "good", "HEAD~2") + self.age(path, 48) + self.age_branch("bisected-work", 48) + self.wire_sweep() + self.assertEqual(0, self.sweep("--apply")) + self.assertIn("keep in-progress-operation branch bisected-work", self.out.getvalue()) + self.assertIn("bisected-work", self.branches()) + self.assertIn(path, self.listed()) + + def test_a_branch_delete_git_refuses_is_kept_as_checked_out_elsewhere(self) -> None: + run_git(self.primary, "branch", "loose-done", "origin/develop") + self.age_branch("loose-done", 48) + self.wire_sweep() + real = pr_cleanup.cleanup_git + + def refusing(root: str, *args: str, **kw: Any) -> subprocess.CompletedProcess[str]: + if args[:2] == ("branch", "-D"): + return subprocess.CompletedProcess([], 1, "", "error: used by worktree") + return real(root, *args, **kw) + + with mock.patch.object(pr_cleanup, "cleanup_git", side_effect=refusing): + self.assertEqual(0, self.sweep("--apply")) + self.assertIn("keep checked-out-elsewhere branch loose-done", self.out.getvalue()) + + def test_a_branch_behind_a_merged_head_counts_as_finished(self) -> None: + path, _ = self.worktree("behind-work") + self.count += 1 + ahead = self.commit(path, f"merged tip {self.count}") + run_git(self.primary, "branch", "ahead", ahead) + run_git(path, "reset", "--hard", "HEAD~1") + run_git(self.primary, "worktree", "remove", path) + self.merged_pr("behind-work", ahead) + self.age_branch("behind-work", 48) + self.wire_sweep(remote_tip=ahead) + self.assertEqual(0, self.sweep()) + self.assertIn("would-remove branch behind-work", self.out.getvalue()) + + def test_a_checkout_naming_another_repository_is_refused(self) -> None: + run_git(self.primary, "remote", "set-url", "origin", "https://github.com/other/repo.git") + self.wire_sweep() + self.assertEqual(1, self.sweep("--apply")) + self.assertIn("status=BAD_CHECKOUT", self.out.getvalue()) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/test_pr_review.py b/tests/test_pr_review.py index f4a95e85e..7bc636825 100755 --- a/tests/test_pr_review.py +++ b/tests/test_pr_review.py @@ -19,8 +19,6 @@ import json import os import re -import shlex -import shutil import subprocess import sys import tempfile @@ -28,7 +26,7 @@ import unittest from datetime import UTC, datetime, timedelta from pathlib import Path -from typing import Any, ClassVar +from typing import ClassVar from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) @@ -11284,20 +11282,23 @@ def test_the_runbook_names_partial_coverage_as_a_state_that_blocks_a_merge(self) self.assertIn("a coverage statement that does not reach this head", text) def test_the_only_writes_are_the_five_named_here(self) -> None: - """Every write this script makes is one of five, and each arrived as a reviewed change. + """Every write these scripts make is one of five, and each arrived as a reviewed change. The read subcommands are the bulk of it and a mutation reaching them is a digest that writes, so the whole-source guard stays and is narrowed to the documents the script actually needs rather than dropped when the first of them arrived. `requestReviews` closes the gap where `wait` only polled and never asked. `addComment` owns body-only finding responses. The reply and resolve pair owns inline threads. `deleteRef` is - `cleanup`'s, by an id read in the same run, so no REST verb enters for it. `union:true` only + `pr_cleanup.py`'s, by an id read in the same run, so no REST verb enters for it. `union:true` only adds to the request set, so it cannot drop a requested human reviewer. `docs/pr-reviewer-reference.md` keeps the `union:false` clear-and-recover form as a manual operation, the runbook carrying no mutation of its own. A sixth document arriving is a write nobody reviewed as one rather than a style drift. """ - source = (REPO / "scripts" / "pr_review.py").read_text(encoding="utf-8") + source = "".join( + (REPO / "scripts" / name).read_text(encoding="utf-8") + for name in ("pr_review.py", "pr_cleanup.py") + ) for verb in ( "-X POST", "-X PATCH", @@ -12424,1310 +12425,5 @@ def test_the_dedupe_falls_back_to_the_app_slug_for_a_null_workflow_run(self) -> self.assertEqual([("lint", "FAILURE"), ("lint", "SUCCESS")], kept) -CLEANUP_HEAD = "a" * 40 -CLEANUP_BRANCH = "feature/example-topic" - - -def fork_head(number: int) -> dict: - """An open pull request headed on a same-named branch in a fork, not in `o/r`.""" - return {"number": number, "headRepository": {"nameWithOwner": f"fork{number}/r"}} - - -def cleanup_pr(**overrides: object) -> dict: - """A merged pull request into `develop` from a head in o/r, every field overridable.""" - pr: dict[str, object] = { - "merged": True, - "baseRefName": "develop", - "headRefName": CLEANUP_BRANCH, - "headRefOid": CLEANUP_HEAD, - "headRepository": {"nameWithOwner": "o/r"}, - } - pr.update(overrides) - return pr - - -class CleanupCase(unittest.TestCase): - """Drive `cleanup` against crafted reads, so no case reaches GitHub or deletes anything.""" - - def setUp(self) -> None: - self.out = self.enterContext(contextlib.redirect_stdout(io.StringIO())) - self.err = self.enterContext(contextlib.redirect_stderr(io.StringIO())) - self.enterContext(mock.patch.object(pr_review, "origin_owner", return_value="o")) - self.enterContext(mock.patch.object(pr_review, "READ_RETRY_DELAYS", ())) - self.enterContext( - mock.patch.object(pr_review.handoff, "registry", return_value=("o", {"r"})) - ) - self.docs: list[tuple[str, dict]] = [] - self.rest: list[str] = [] - - def wire( - self, - pr: dict | None = None, - default: str = "main", - refs: list[object] | None = None, - rules: object = (), - protected: object = False, - delete_fails: bool = False, - heads: list[int] | None = None, - bases: list[int] | None = None, - head_pages: list[list[dict]] | None = None, - head_answer: object = None, - base_answer: object = None, - ) -> None: - """Answer each document in turn, `refs` holding one answer per ref read in order. - - A ref answer is a tip, None for no such branch, or an exception the read raises. - `head_pages` pages the heads connection, each page its nodes, where `heads` is one page - of this repository's own. An answer given whole replaces that read's repository, or is - raised where it is an exception. - """ - pending = list(refs if refs is not None else [CLEANUP_HEAD, None]) - local = [{"number": n, "headRepository": {"nameWithOwner": "o/r"}} for n in heads or []] - pages = head_pages if head_pages is not None else [local] - - def fake(query: str, variables: dict, **_: object) -> pr_review.shared.Response: - self.docs.append((query, variables)) - if "pullRequest(number" in query: - repository = {"defaultBranchRef": {"name": default}, "pullRequest": pr} - return pr_review.shared.Response({"repository": repository}, []) - if "heads: pullRequests" in query: - self.assertEqual(CLEANUP_BRANCH, variables["b"]) - if isinstance(head_answer, Exception): - raise head_answer - if head_answer is not None: - return pr_review.shared.Response({"repository": head_answer}, []) - at = int(variables.get("after", "c0")[1:]) - more = at + 1 < len(pages) - page = {"hasNextPage": more, "endCursor": f"c{at + 1}" if more else None} - found = {"heads": {"pageInfo": page, "nodes": pages[at]}} - return pr_review.shared.Response({"repository": found}, []) - if "bases: pullRequests" in query: - self.assertEqual(CLEANUP_BRANCH, variables["b"]) - if isinstance(base_answer, Exception): - raise base_answer - if base_answer is not None: - return pr_review.shared.Response({"repository": base_answer}, []) - listed = [{"number": n} for n in bases or []] - based = {"bases": {"totalCount": len(listed), "nodes": listed}} - return pr_review.shared.Response({"repository": based}, []) - if "deleteRef" in query: - if delete_fails: - raise pr_review.shared.GraphQLError("gh graphql reported errors") - return pr_review.shared.Response({"deleteRef": {"clientMutationId": None}}, []) - if "qualifiedName" in query: - answer = pending.pop(0) - if isinstance(answer, Exception): - raise answer - ref = None if answer is None else {"id": "REF_read", "target": {"oid": answer}} - return pr_review.shared.Response({"repository": {"ref": ref}}, []) - raise AssertionError(f"unexpected document: {query[:60]}") - - def rest( - path: str, jq: str | None = None, raw: bool = False - ) -> subprocess.CompletedProcess: - self.rest.append(path) - if "/rules/branches/" in path: - body = rules - else: - body = {"name": CLEANUP_BRANCH, "protected": protected} - if isinstance(body, Exception): - return subprocess.CompletedProcess([], 1, "", "gh: Not Found (HTTP 404)") - text = json.dumps(list(body) if isinstance(body, tuple) else body) - return subprocess.CompletedProcess([], 0, text, "") - - self.enterContext(mock.patch.object(pr_review.shared, "request", side_effect=fake)) - self.enterContext(mock.patch.object(pr_review, "gh_rest", side_effect=rest)) - - def run_cleanup(self, repo: str = "o/r") -> int: - return pr_review.main(["cleanup", "7", "--repo", repo]) - - def deleted(self) -> bool: - return any("deleteRef" in q for q, _ in self.docs) - - -class TestCleanupDeletesOnlyAVerifiedMergedBranch(CleanupCase): - def test_a_matching_tip_is_deleted_by_the_id_just_read_and_confirmed_gone(self) -> None: - """Two exact reads by qualified name, the tip before the delete and the read back after.""" - self.wire(cleanup_pr()) - self.assertEqual(0, self.run_cleanup()) - delete = next(v for q, v in self.docs if "deleteRef" in q) - self.assertEqual({"refId": "REF_read"}, delete) - reads = [v for q, v in self.docs if "qualifiedName" in q] - self.assertEqual([f"refs/heads/{CLEANUP_BRANCH}"] * 2, [v["q"] for v in reads]) - self.assertIn("status=DELETED", self.out.getvalue()) - - def test_a_branch_already_gone_is_done_and_deletes_nothing(self) -> None: - self.wire(cleanup_pr(), refs=[None]) - self.assertEqual(0, self.run_cleanup()) - self.assertFalse(self.deleted()) - self.assertIn("status=ALREADY_GONE", self.out.getvalue()) - - def test_a_moved_tip_refuses_and_names_both_commits(self) -> None: - moved = "b" * 40 - self.wire(cleanup_pr(), refs=[moved]) - self.assertEqual(1, self.run_cleanup()) - self.assertFalse(self.deleted()) - out = self.out.getvalue() - self.assertIn("status=TIP_MOVED", out) - self.assertIn(moved, out) - self.assertIn(CLEANUP_HEAD, out) - - def test_a_ref_still_there_after_the_delete_is_not_reported_deleted(self) -> None: - self.wire(cleanup_pr(), refs=[CLEANUP_HEAD, CLEANUP_HEAD]) - self.assertEqual(2, self.run_cleanup()) - self.assertTrue(self.deleted()) - self.assertIn("status=DELETE_NOT_CONFIRMED", self.out.getvalue()) - self.assertNotIn("status=DELETED", self.out.getvalue()) - - def test_a_read_back_that_does_not_answer_is_not_reported_deleted(self) -> None: - unread = pr_review.shared.GraphQLError("gh graphql failed rc=1") - self.wire(cleanup_pr(), refs=[CLEANUP_HEAD, unread]) - self.assertEqual(2, self.run_cleanup()) - self.assertTrue(self.deleted()) - self.assertIn("status=DELETE_NOT_CONFIRMED", self.out.getvalue()) - - def test_a_delete_reporting_failure_is_decided_by_the_read_back(self) -> None: - """A failed-looking delete may have landed, so the ref read decides rather than the error.""" - self.wire(cleanup_pr(), refs=[CLEANUP_HEAD, None], delete_fails=True) - self.assertEqual(0, self.run_cleanup()) - out = self.out.getvalue() - self.assertIn("the delete reported a failure", out) - self.assertIn("status=DELETED", out) - - def test_a_delete_reporting_failure_with_the_ref_still_there_exits_2(self) -> None: - self.wire(cleanup_pr(), refs=[CLEANUP_HEAD, CLEANUP_HEAD], delete_fails=True) - self.assertEqual(2, self.run_cleanup()) - self.assertIn("status=DELETE_NOT_CONFIRMED", self.out.getvalue()) - - -class TestCleanupRefusesBeforeAnyDelete(CleanupCase): - def assert_refused(self, code: int = 1, status: str = "status=REFUSED") -> None: - self.assertEqual(code, self.run_cleanup()) - self.assertFalse(self.deleted()) - self.assertIn(status, self.out.getvalue()) - - def test_an_unmerged_pull_request_is_refused(self) -> None: - self.wire(cleanup_pr(merged=False)) - self.assert_refused() - - def test_a_base_other_than_develop_is_refused(self) -> None: - self.wire(cleanup_pr(baseRefName="main")) - self.assert_refused() - - def test_a_head_in_another_repository_is_refused(self) -> None: - self.wire(cleanup_pr(headRepository={"nameWithOwner": "o/r-fork"})) - self.assert_refused() - - def test_a_head_repository_gone_is_refused(self) -> None: - self.wire(cleanup_pr(headRepository=None)) - self.assert_refused() - - def test_a_develop_head_is_refused(self) -> None: - self.wire(cleanup_pr(headRefName="develop")) - self.assert_refused() - - def test_a_main_head_is_refused_where_main_is_not_the_default(self) -> None: - self.wire(cleanup_pr(headRefName="main"), default="trunk") - self.assert_refused() - - def test_the_default_branch_read_live_is_refused(self) -> None: - self.wire(cleanup_pr(headRefName="trunk"), default="trunk") - self.assert_refused() - - def test_a_ruleset_on_the_branch_is_refused(self) -> None: - self.wire(cleanup_pr(), rules=[{"type": "deletion"}]) - self.assert_refused() - self.assertIn("deletion", self.out.getvalue()) - - def test_classic_branch_protection_is_refused(self) -> None: - self.wire(cleanup_pr(), protected=True) - self.assert_refused() - - def test_an_unread_rule_set_stops_at_2_rather_than_reading_as_none(self) -> None: - self.wire(cleanup_pr(), rules=RuntimeError("unread")) - self.assert_refused(2, "status=UNREAD") - self.assertIn("HTTP 404", self.err.getvalue()) - self.assertIn("rc=1", self.out.getvalue()) - - def test_an_open_pull_request_headed_on_the_branch_is_refused_and_named(self) -> None: - self.wire(cleanup_pr(), heads=[41]) - self.assert_refused() - self.assertIn("#41 (head)", self.out.getvalue()) - - def test_an_open_pull_request_based_on_the_branch_is_refused_and_named(self) -> None: - self.wire(cleanup_pr(), bases=[42, 43]) - self.assert_refused() - self.assertIn("#42 (base), #43 (base)", self.out.getvalue()) - - def test_an_open_pull_request_read_that_does_not_answer_stops_at_2(self) -> None: - bad = pr_review.shared.GraphQLError("gh graphql failed rc=1") - page = {"hasNextPage": False, "endCursor": None} - malformed: list[dict[str, object]] = [ - {"head_answer": bad}, - {"head_answer": {"heads": {"nodes": []}}}, - {"head_answer": {"heads": {"pageInfo": page, "nodes": None}}}, - {"head_answer": {"heads": {"pageInfo": page, "nodes": ["#9"]}}}, - {"head_answer": {"heads": {"pageInfo": {"hasNextPage": True}, "nodes": []}}}, - {"base_answer": bad}, - {"base_answer": {"bases": {"totalCount": "0", "nodes": []}}}, - ] - for answer in malformed: - with self.subTest(answer=answer): - self.docs.clear() - self.wire( - cleanup_pr(), - head_answer=answer.get("head_answer"), - base_answer=answer.get("base_answer"), - ) - self.assert_refused(2, "status=UNREAD") - - def test_an_unread_heads_page_past_the_first_stops_at_2(self) -> None: - """A page that does not answer is no pull request missing, however clean the first was.""" - self.wire(cleanup_pr(), head_pages=[[fork_head(9)], [fork_head(10)]]) - request = pr_review.shared.request - assert isinstance(request, mock.Mock) - answer = request.side_effect - - def second_page_fails(query: str, variables: dict, **kw: object) -> object: - if "heads: pullRequests" in query and variables.get("after"): - raise pr_review.shared.GraphQLError("gh graphql failed rc=1") - return answer(query, variables, **kw) - - request.side_effect = second_page_fails - self.assert_refused(2, "status=UNREAD") - - def test_more_open_base_pull_requests_than_the_page_holds_are_refused(self) -> None: - full = {"bases": {"totalCount": 25, "nodes": []}} - self.wire(cleanup_pr(), base_answer=full) - self.assert_refused() - self.assertIn("25 more with the branch as base", self.out.getvalue()) - - def test_a_forks_pull_request_on_a_same_named_branch_is_not_a_user(self) -> None: - self.wire(cleanup_pr(), head_pages=[[fork_head(9)]]) - self.assertEqual(0, self.run_cleanup()) - self.assertTrue(self.deleted()) - - def test_fork_pull_requests_filling_every_page_are_not_users(self) -> None: - """Past the first page, forks alone sharing the branch name leave nothing to refuse.""" - pages = [[fork_head(n) for n in range(k, k + 100)] for k in (100, 200, 300)] - self.wire(cleanup_pr(), head_pages=pages) - self.assertEqual(0, self.run_cleanup()) - self.assertTrue(self.deleted()) - reads = [v.get("after") for q, v in self.docs if "heads: pullRequests" in q] - self.assertEqual([None, "c1", "c2"], reads) - self.assertNotIn("more with the branch", self.out.getvalue()) - - def test_a_local_pull_request_past_the_first_page_is_refused_and_named(self) -> None: - local = {"number": 512, "headRepository": {"nameWithOwner": "O/R"}} - pages = [[fork_head(n) for n in range(100, 200)], [fork_head(200), local]] - self.wire(cleanup_pr(), head_pages=pages) - self.assert_refused() - self.assertIn("#512 (head)", self.out.getvalue()) - self.assertNotIn("#200", self.out.getvalue()) - - def test_a_rule_read_that_is_not_a_list_stops_at_2(self) -> None: - self.wire(cleanup_pr(), rules={"message": "Upgrade to GitHub Pro"}) - self.assert_refused(2, "status=UNREAD") - - def test_an_unread_protection_flag_stops_at_2(self) -> None: - self.wire(cleanup_pr(), protected=None) - self.assert_refused(2, "status=UNREAD") - - def test_a_branch_name_that_changes_the_rest_path_stops_at_2(self) -> None: - self.wire(cleanup_pr(headRefName="feature/a?b"), refs=[CLEANUP_HEAD]) - self.assert_refused(2, "status=UNREAD") - self.assertEqual([], self.rest) - - def test_an_unread_pull_request_stops_at_2(self) -> None: - self.wire(None) - self.assert_refused(2, "status=UNREAD") - - def test_an_unread_tip_stops_at_2(self) -> None: - self.wire(cleanup_pr(), refs=[pr_review.shared.GraphQLError("gh graphql failed rc=1")]) - self.assert_refused(2, "status=UNREAD") - - def test_an_owner_other_than_the_checkout_is_out_of_scope_before_any_read(self) -> None: - self.wire(cleanup_pr()) - self.assertEqual(64, self.run_cleanup(repo="x/r")) - self.assertEqual([], self.docs) - self.assertIn("status=OUT_OF_SCOPE", self.out.getvalue()) - - def test_an_owner_other_than_the_registry_is_refused_before_any_read(self) -> None: - self.wire(cleanup_pr()) - with mock.patch.object(pr_review.handoff, "registry", return_value=("p", {"r"})): - self.assertEqual(1, self.run_cleanup()) - self.assertEqual([], self.docs) - self.assertIn("status=REFUSED", self.out.getvalue()) - - def test_an_unregistered_repository_that_is_not_a_fork_is_refused(self) -> None: - self.wire(cleanup_pr()) - flags = {"hasIssuesEnabled": True, "isFork": False} - with mock.patch.object(pr_review.handoff, "gh_json", return_value=flags): - self.assertEqual(1, self.run_cleanup(repo="o/unlisted")) - self.assertEqual([], self.docs) - - def test_an_unregistered_fork_under_the_owner_is_admitted(self) -> None: - self.wire(cleanup_pr(headRepository={"nameWithOwner": "o/forked"})) - flags = {"hasIssuesEnabled": True, "isFork": True} - with mock.patch.object(pr_review.handoff, "gh_json", return_value=flags): - self.assertEqual(0, self.run_cleanup(repo="o/forked")) - self.assertTrue(self.deleted()) - - def test_an_unreadable_registry_stops_at_2(self) -> None: - self.wire(cleanup_pr()) - failure = pr_review.handoff.Execution("could not read the fleet registry") - with mock.patch.object(pr_review.handoff, "registry", side_effect=failure): - self.assertEqual(2, self.run_cleanup()) - self.assertEqual([], self.docs) - - -EDIT_PICKS = ( - r"import sys,re,pathlib; p=pathlib.Path(sys.argv[1]); " - r"p.write_text(re.sub(r\"^pick\", \"edit\", p.read_text(), flags=re.M))" -) -SEQUENCE_EDITOR = shlex.quote(sys.executable) + ' -c "' + EDIT_PICKS + '"' - - -def run_git(cwd: str, *args: str) -> str: - """One git call in a throwaway repository, failing the test on a nonzero exit.""" - done = subprocess.run( - ["git", "-C", cwd, *args], capture_output=True, text=True, encoding="utf-8", check=True - ) - return done.stdout.strip() - - -class LocalCleanupCase(CleanupCase): - """A bare origin, a primary clone naming o/r, and linked worktrees, all real git in a temp dir. - - Only the GitHub reads and writes are mocked, so every local removal below is git's own. - """ - - def setUp(self) -> None: - super().setUp() - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = os.path.realpath(tmp.name) - self.enterContext( - mock.patch.dict( - os.environ, {"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_SYSTEM": os.devnull} - ) - ) - self.bare = os.path.join(self.root, "origin.git") - self.primary = os.path.join(self.root, "primary") - self.seed = os.path.join(self.root, "seed") - subprocess.run( - ["git", "init", "--bare", "-b", "develop", self.bare], check=True, capture_output=True - ) - subprocess.run(["git", "init", "-b", "develop", self.seed], check=True, capture_output=True) - self.configure(self.seed) - self.commit(self.seed, "seed") - run_git(self.seed, "push", self.bare, "develop:develop", "develop:main") - subprocess.run(["git", "clone", self.bare, self.primary], check=True, capture_output=True) - self.configure(self.primary) - run_git(self.primary, "branch", "main", "origin/main") - run_git(self.primary, "config", f"url.{self.bare}.insteadOf", "https://github.com/o/r.git") - run_git(self.primary, "remote", "set-url", "origin", "https://github.com/o/r.git") - self.count = 0 - - def configure(self, repo: str) -> None: - run_git(repo, "config", "user.name", "Test User") - run_git(repo, "config", "user.email", "test@example.com") - run_git(repo, "config", "commit.gpgsign", "false") - - def commit(self, repo: str, message: str) -> str: - run_git(repo, "commit", "--allow-empty", "-m", message) - return run_git(repo, "rev-parse", "HEAD") - - def worktree(self, branch: str, commits: int = 1) -> tuple[str, str]: - """A linked worktree on a new local branch with `commits` unpushed commits.""" - path = os.path.join(self.root, "wt", branch.replace("/", "_")) - run_git(self.primary, "worktree", "add", "-b", branch, path, "origin/develop") - for _ in range(commits): - self.count += 1 - self.commit(path, f"work {self.count}") - return path, run_git(path, "rev-parse", "HEAD") - - def advance_origin(self) -> str: - """A new commit on origin's develop, as a merge into it would leave.""" - run_git(self.seed, "pull", "--ff-only", self.bare, "develop") - self.count += 1 - tip = self.commit(self.seed, f"merge {self.count}") - run_git(self.seed, "push", self.bare, "develop:develop") - return tip - - def branches(self) -> list[str]: - out = run_git(self.primary, "for-each-ref", "--format=%(refname:short)", "refs/heads") - return out.splitlines() - - def listed(self) -> list[str]: - out = run_git(self.primary, "worktree", "list", "--porcelain") - return [ - os.path.realpath(ln.split(" ", 1)[1]) - for ln in out.splitlines() - if ln.startswith("worktree ") - ] - - def run_local(self, checkout: str | None = None) -> int: - argv = ["cleanup", "7", "--repo", "o/r", "--checkout", checkout or self.primary] - return pr_review.main(argv) - - def pause_rebase(self, repo: str) -> None: - env = {**os.environ, "GIT_SEQUENCE_EDITOR": SEQUENCE_EDITOR} - argv = ["git", "-C", repo, "rebase", "-i", "HEAD~2"] - subprocess.run(argv, env=env, capture_output=True, check=True) - - def wire_merged(self, tip: str) -> None: - self.wire(cleanup_pr(headRefOid=tip), refs=[tip, tip, None]) - - -class TestCleanupLocalHalf(LocalCleanupCase): - def test_the_worktree_and_branch_go_and_the_base_clone_catches_up(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - merged = self.advance_origin() - self.wire_merged(tip) - self.assertEqual(0, self.run_local()) - self.assertFalse(os.path.exists(path)) - self.assertNotIn(CLEANUP_BRANCH, self.branches()) - self.assertEqual([self.primary], self.listed()) - self.assertEqual(merged, run_git(self.primary, "rev-parse", "HEAD")) - out = self.out.getvalue() - self.assertIn("status=DELETED", out) - self.assertIn("status=CLEANED", out) - self.assertIn("## develop...origin/develop", out) - - def test_without_a_checkout_nothing_local_is_touched(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - self.wire(cleanup_pr(headRefOid=tip), refs=[tip, None]) - self.assertEqual(0, pr_review.main(["cleanup", "7", "--repo", "o/r"])) - self.assertTrue(os.path.isdir(path)) - self.assertIn(CLEANUP_BRANCH, self.branches()) - self.assertNotIn("status=CLEANED", self.out.getvalue()) - - def test_a_branch_already_gone_locally_still_returns_the_base_clone(self) -> None: - merged = self.advance_origin() - self.wire(cleanup_pr(headRefOid=merged), refs=[merged, merged, None]) - self.assertEqual(0, self.run_local()) - self.assertIn("is already gone", self.out.getvalue()) - self.assertEqual(merged, run_git(self.primary, "rev-parse", "HEAD")) - - def test_a_moved_local_tip_refuses_and_removes_nothing(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - self.count += 1 - later = self.commit(path, f"unpushed {self.count}") - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - out = self.out.getvalue() - self.assertIn("status=LOCAL_TIP_MOVED", out) - self.assertIn(tip, out) - self.assertIn(later, out) - self.assertFalse(self.deleted()) - self.assertIn("remote branch included", self.out.getvalue()) - self.assertTrue(os.path.isdir(path)) - self.assertEqual(later, run_git(self.primary, "rev-parse", CLEANUP_BRANCH)) - - def test_a_dirty_worktree_refuses_and_removes_nothing(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - Path(path, "scratch.txt").write_text("x", encoding="utf-8") - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - self.assertIn("status=WORKTREE_DIRTY", self.out.getvalue()) - self.assertFalse(self.deleted()) - self.assertIn("remote branch included", self.out.getvalue()) - self.assertTrue(os.path.isdir(path)) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_a_locked_worktree_refuses_and_removes_nothing(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - run_git(self.primary, "worktree", "lock", path) - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) - self.assertFalse(self.deleted()) - self.assertIn("remote branch included", self.out.getvalue()) - self.assertTrue(os.path.isdir(path)) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_a_checkout_whose_origin_is_another_repository_is_refused_before_the_remote_delete( - self, - ) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - run_git(self.primary, "remote", "set-url", "origin", "git@github.com:other/repo.git") - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - self.assertIn("status=BAD_CHECKOUT", self.out.getvalue()) - self.assertFalse(self.deleted()) - self.assertTrue(os.path.isdir(path)) - - def test_a_linked_worktree_is_not_a_primary_checkout(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - self.wire_merged(tip) - self.assertEqual(1, self.run_local(path)) - self.assertIn("status=BAD_CHECKOUT", self.out.getvalue()) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_a_remote_refusal_skips_the_local_half(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - self.wire(cleanup_pr(headRefOid=tip, merged=False)) - self.assertEqual(1, self.run_local()) - self.assertNotIn("status=CLEANED", self.out.getvalue()) - self.assertTrue(os.path.isdir(path)) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_a_primary_holding_the_branch_moves_to_develop_before_the_delete(self) -> None: - run_git(self.primary, "checkout", "-b", CLEANUP_BRANCH) - tip = self.commit(self.primary, "primary work") - self.advance_origin() - self.wire_merged(tip) - self.assertEqual(0, self.run_local()) - self.assertNotIn(CLEANUP_BRANCH, self.branches()) - self.assertEqual("develop", run_git(self.primary, "symbolic-ref", "--short", "HEAD")) - out = self.out.getvalue() - self.assertLess(out.index("switched"), out.index("deleting:")) - - def test_a_rebase_paused_in_the_primary_on_the_branch_refuses(self) -> None: - run_git(self.primary, "checkout", "-b", CLEANUP_BRANCH) - for n in range(3): - self.commit(self.primary, f"primary work {n}") - tip = run_git(self.primary, "rev-parse", "HEAD") - self.pause_rebase(self.primary) - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) - self.assertFalse(self.deleted()) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_the_closing_informational_reads_never_fail_a_landed_cleanup(self) -> None: - _, tip = self.worktree(CLEANUP_BRANCH) - self.wire_merged(tip) - real = pr_review.cleanup_git - - def flaky(root: str, *args: str, **kw: Any) -> subprocess.CompletedProcess[str]: - if args[:1] == ("status",) and "--branch" in args: - raise pr_review.CleanupUnread("status read failed") - return real(root, *args, **kw) - - listing = pr_review.cleanup_worktrees - - def failing_list(primary: str) -> list[pr_review.Worktree]: - if "status unavailable" in self.out.getvalue(): - raise pr_review.CleanupUnread("list read failed") - return listing(primary) - - with ( - mock.patch.object(pr_review, "cleanup_git", side_effect=flaky), - mock.patch.object(pr_review, "cleanup_worktrees", side_effect=failing_list), - ): - self.assertEqual(0, self.run_local()) - out = self.out.getvalue() - self.assertIn("status unavailable", out) - self.assertIn("worktrees listed: unavailable", out) - self.assertIn("status=CLEANED", out) - - def test_a_primary_stopped_mid_cherry_pick_on_the_branch_refuses(self) -> None: - run_git(self.primary, "checkout", "-b", CLEANUP_BRANCH) - tip = self.commit(self.primary, "primary work") - admin = Path(run_git(self.primary, "rev-parse", "--absolute-git-dir")) - (admin / "CHERRY_PICK_HEAD").write_text(tip + "\n", encoding="utf-8") - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) - self.assertFalse(self.deleted()) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_a_remote_branch_that_moved_before_the_delete_is_not_deleted(self) -> None: - _, tip = self.worktree(CLEANUP_BRANCH) - self.wire(cleanup_pr(headRefOid=tip), refs=[tip, "c" * 40]) - self.assertEqual(1, self.run_local()) - self.assertIn("status=TIP_MOVED", self.out.getvalue()) - self.assertFalse(self.deleted()) - - def test_an_origin_branch_that_differs_from_the_merged_head_refuses(self) -> None: - path, _ = self.worktree(CLEANUP_BRANCH) - run_git(path, "push", "origin", CLEANUP_BRANCH) - self.count += 1 - tip = self.commit(path, f"after the push {self.count}") - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - self.assertIn("status=TIP_MOVED", self.out.getvalue()) - self.assertFalse(self.deleted()) - - def test_a_primary_holding_the_branch_with_tracked_changes_refuses(self) -> None: - run_git(self.primary, "checkout", "-b", CLEANUP_BRANCH) - Path(self.primary, "tracked.txt").write_text("a", encoding="utf-8") - run_git(self.primary, "add", "tracked.txt") - tip = run_git(self.primary, "rev-parse", "HEAD") - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - self.assertIn("status=BASE_DIRTY", self.out.getvalue()) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_a_diverged_develop_is_reported_without_failing_the_removals(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - self.advance_origin() - run_git(self.primary, "fetch", "origin") - self.count += 1 - self.commit(self.primary, f"local only {self.count}") - self.wire_merged(tip) - self.assertEqual(0, self.run_local()) - out = self.out.getvalue() - self.assertLess(out.index("removed worktree"), out.index("status=BASE_NOT_FF")) - self.assertIn("base=kept", out) - self.assertFalse(os.path.exists(path)) - self.assertNotIn(CLEANUP_BRANCH, self.branches()) - - def test_the_shell_directory_inside_a_removed_worktree_is_handled_per_platform(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - self.wire_merged(tip) - before = os.getcwd() - self.addCleanup(os.chdir, before) - os.chdir(path) - if pr_review.ON_WINDOWS: - self.assertEqual(1, self.run_local()) - self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) - self.assertTrue(os.path.isdir(path)) - else: - self.assertEqual(0, self.run_local()) - self.assertIn("note: the shell's directory", self.out.getvalue()) - self.assertFalse(os.path.exists(path)) - - def test_a_shell_inside_the_worktree_refuses_on_windows(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - self.wire_merged(tip) - before = os.getcwd() - self.addCleanup(os.chdir, before) - os.chdir(path) - with mock.patch.object(pr_review, "ON_WINDOWS", True): - self.assertEqual(1, self.run_local()) - self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) - self.assertTrue(os.path.isdir(path)) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_a_worktree_with_submodules_refuses_and_removes_nothing(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - Path(path, ".gitmodules").write_text("", encoding="utf-8") - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) - self.assertTrue(os.path.isdir(path)) - - def test_a_rerun_with_the_primary_elsewhere_is_done_with_the_base_kept(self) -> None: - run_git(self.primary, "checkout", "-b", "elsewhere") - self.wire(cleanup_pr(headRefOid=CLEANUP_HEAD), refs=[CLEANUP_HEAD, CLEANUP_HEAD, None]) - self.assertEqual(0, self.run_local()) - out = self.out.getvalue() - self.assertIn("is already gone", out) - self.assertIn("base=kept", out) - - def test_a_tip_that_moves_before_the_delete_is_a_refusal_after_the_removals(self) -> None: - _, tip = self.worktree(CLEANUP_BRANCH) - self.wire_merged(tip) - real = pr_review.cleanup_tip - heads = [] - - def moving(primary: str, ref: str) -> str | None: - if not ref.startswith("refs/heads/"): - return real(primary, ref) - heads.append(ref) - return "b" * 40 if len(heads) == 3 else real(primary, ref) - - with mock.patch.object(pr_review, "cleanup_tip", side_effect=moving): - self.assertEqual(1, self.run_local()) - out = self.out.getvalue() - self.assertLess(out.index("removed worktree"), out.index("status=LOCAL_TIP_MOVED")) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_an_unconfirmed_branch_delete_is_exit_2(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - self.wire_merged(tip) - with mock.patch.object(pr_review, "cleanup_tip", side_effect=itertools.repeat(tip)): - self.assertEqual(2, self.run_local()) - self.assertIn("status=LOCAL_DELETE_NOT_CONFIRMED", self.out.getvalue()) - self.assertFalse(os.path.exists(path)) - - def test_a_primary_on_another_branch_is_left_there(self) -> None: - _, tip = self.worktree(CLEANUP_BRANCH) - run_git(self.primary, "checkout", "-b", "elsewhere") - self.wire_merged(tip) - self.assertEqual(0, self.run_local()) - self.assertEqual("elsewhere", run_git(self.primary, "symbolic-ref", "--short", "HEAD")) - out = self.out.getvalue() - self.assertIn("keep base-not-on-develop", out) - self.assertIn("base=kept", out) - - def test_a_branch_being_bisected_in_another_worktree_is_kept(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH, commits=3) - run_git(path, "bisect", "start") - run_git(path, "bisect", "bad", "HEAD") - run_git(path, "bisect", "good", "HEAD~2") - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) - self.assertFalse(self.deleted()) - self.assertIn(CLEANUP_BRANCH, self.branches()) - self.assertTrue(os.path.isdir(path)) - - def test_a_branch_being_rebased_in_another_worktree_is_kept(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH, commits=3) - self.pause_rebase(path) - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) - self.assertFalse(self.deleted()) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_a_prunable_entry_holding_the_branch_is_removed_without_force(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - shutil.rmtree(path) - self.wire_merged(tip) - self.assertEqual(0, self.run_local()) - self.assertEqual([self.primary], self.listed()) - self.assertNotIn(CLEANUP_BRANCH, self.branches()) - - def test_a_local_tip_behind_the_merged_head_is_removed(self) -> None: - path, _ = self.worktree(CLEANUP_BRANCH) - self.count += 1 - ahead = self.commit(path, f"merged tip {self.count}") - run_git(self.primary, "branch", "ahead", ahead) - run_git(path, "reset", "--hard", "HEAD~1") - self.wire_merged(ahead) - self.assertEqual(0, self.run_local()) - self.assertNotIn(CLEANUP_BRANCH, self.branches()) - - def test_a_partly_removed_worktree_is_an_unconfirmed_removal(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - self.wire_merged(tip) - real = pr_review.cleanup_git - - def partial(root: str, *args: str, **kw: Any) -> subprocess.CompletedProcess[str]: - if args[:2] == ("worktree", "remove"): - real(root, *args) - os.makedirs(path) - raise pr_review.CleanupUnread("could not delete every file") - return real(root, *args, **kw) - - with mock.patch.object(pr_review, "cleanup_git", side_effect=partial): - self.assertEqual(2, self.run_local()) - self.assertIn(path, self.out.getvalue()) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_a_branch_delete_git_refuses_is_a_kept_branch(self) -> None: - _, tip = self.worktree(CLEANUP_BRANCH) - self.wire_merged(tip) - real = pr_review.cleanup_git - - def refusing(root: str, *args: str, **kw: Any) -> subprocess.CompletedProcess[str]: - if args[:2] == ("branch", "-D"): - return subprocess.CompletedProcess([], 1, "", "error: used by worktree") - return real(root, *args, **kw) - - with mock.patch.object(pr_review, "cleanup_git", side_effect=refusing): - self.assertEqual(1, self.run_local()) - self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_a_worktree_mid_operation_refuses_and_removes_nothing(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - admin = Path(run_git(path, "rev-parse", "--absolute-git-dir")) - (admin / "MERGE_HEAD").write_text(tip + "\n", encoding="utf-8") - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) - self.assertTrue(os.path.isdir(path)) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_a_worktree_removed_by_someone_else_mid_run_is_done(self) -> None: - path, tip = self.worktree(CLEANUP_BRANCH) - self.wire_merged(tip) - real = pr_review.cleanup_git - - def racing(root: str, *args: str, **kw: Any) -> subprocess.CompletedProcess[str]: - if args[:2] == ("worktree", "remove"): - real(root, *args) - raise pr_review.CleanupUnread("another process got there first") - return real(root, *args, **kw) - - with mock.patch.object(pr_review, "cleanup_git", side_effect=racing): - self.assertEqual(0, self.run_local()) - self.assertIn("already gone", self.out.getvalue()) - self.assertFalse(os.path.exists(path)) - self.assertNotIn(CLEANUP_BRANCH, self.branches()) - - def test_a_branch_deleted_by_someone_else_before_the_delete_is_already_gone(self) -> None: - _, tip = self.worktree(CLEANUP_BRANCH) - self.wire_merged(tip) - real = pr_review.cleanup_tip - calls = [] - - def vanishing(primary: str, ref: str) -> str | None: - if ref.startswith("refs/heads/"): - calls.append(ref) - if len(calls) == 3 and ref.startswith("refs/heads/"): - run_git(primary, "branch", "-D", "--", CLEANUP_BRANCH) - return None - return real(primary, ref) - - with mock.patch.object(pr_review, "cleanup_tip", side_effect=vanishing): - self.assertEqual(0, self.run_local()) - self.assertIn("status=CLEANED", self.out.getvalue()) - - def test_a_primary_that_cannot_leave_the_branch_keeps_it_and_exits_1(self) -> None: - Path(self.seed, "clash.txt").write_text("x", encoding="utf-8") - run_git(self.seed, "add", "clash.txt") - self.commit(self.seed, "add clash") - run_git(self.seed, "push", self.bare, "develop:develop") - run_git(self.primary, "pull", "--ff-only", "origin", "develop") - run_git(self.primary, "checkout", "-b", CLEANUP_BRANCH, "develop~1") - Path(self.primary, "clash.txt").write_text("y", encoding="utf-8") - tip = run_git(self.primary, "rev-parse", "HEAD") - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - self.assertIn("could not leave", self.out.getvalue()) - self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) - self.assertIn("nothing was deleted, remote branch included", self.out.getvalue()) - self.assertFalse(self.deleted()) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - def test_a_develop_held_by_another_worktree_stops_the_primary_leaving(self) -> None: - run_git(self.primary, "checkout", "-b", CLEANUP_BRANCH) - tip = self.commit(self.primary, "primary work") - other = os.path.join(self.root, "wt", "develop-holder") - run_git(self.primary, "worktree", "add", other, "develop") - self.wire_merged(tip) - self.assertEqual(1, self.run_local()) - self.assertIn("status=WORKTREE_KEPT", self.out.getvalue()) - self.assertFalse(self.deleted()) - self.assertIn(CLEANUP_BRANCH, self.branches()) - - -class TestCleanupOriginParsing(unittest.TestCase): - def test_https_and_ssh_forms_name_the_repository_case_insensitively(self) -> None: - for url in ( - "https://github.com/O/R.git", - "https://github.com/o/r", - "https://user@github.com/o/r.git/", - "git@github.com:o/R.git", - "ssh://git@github.com/O/r", - ): - found = pr_review.GITHUB_REMOTE.match(url) - self.assertIsNotNone(found, url) - assert found is not None - self.assertEqual("o/r", f"{found[1]}/{found[2]}".lower()) - - def test_other_hosts_and_shapes_do_not_match(self) -> None: - for url in ("https://example.com/o/r.git", "/srv/o/r.git", "https://github.com/o", ""): - self.assertIsNone(pr_review.GITHUB_REMOTE.match(url), url) - - -class TestCleanupSweepArguments(CleanupCase): - def usage(self, *argv: str) -> None: - with self.assertRaises(SystemExit) as caught: - pr_review.main(list(argv)) - self.assertEqual(2, caught.exception.code) - - def test_a_missing_number_is_a_usage_error_outside_the_sweep(self) -> None: - self.usage("status", "--repo", "o/r") - self.usage("cleanup", "--repo", "o/r") - - def test_a_required_number_still_parses_ahead_of_the_options(self) -> None: - class Reached(Exception): - pass - - with ( - mock.patch.object(pr_review, "full_read", side_effect=Reached), - self.assertRaises(Reached), - ): - pr_review.main(["status", "--repo", "o/r", "7"]) - with mock.patch.object(pr_review, "cleanup", return_value=0) as cleaned: - self.assertEqual( - 0, pr_review.main(["cleanup", "--repo", "o/r", "7", "--checkout", "x"]) - ) - cleaned.assert_called_once_with("o", "r", 7, "x") - - def test_the_sweep_flags_are_checked_against_each_other(self) -> None: - self.usage("cleanup", "7", "--sweep", "--repo", "o/r", "--checkout", "/x") - self.usage("cleanup", "--sweep", "--repo", "o/r") - self.usage("cleanup", "7", "--repo", "o/r", "--apply") - self.usage("cleanup", "7", "--repo", "o/r", "--min-age-hours", "1") - self.usage("status", "7", "--repo", "o/r", "--sweep") - - -class TestCleanupSweep(LocalCleanupCase): - def setUp(self) -> None: - super().setUp() - self.merged_prs: dict[str, list[dict]] = {} - self.failing: set[str] = set() - - def age(self, path: str, hours: float) -> None: - """Set every file the sweep reads the age from to `hours` ago.""" - admin = Path(path, ".git").read_text(encoding="utf-8").split(":", 1)[1].strip() - stamp = time.time() - hours * 3600 - for p in (path, *(os.path.join(admin, n) for n in ("HEAD", "index", "logs/HEAD"))): - if os.path.exists(p): - os.utime(p, (stamp, stamp)) - - def age_branch(self, branch: str, hours: float) -> None: - log = os.path.join(self.primary, ".git", "logs", "refs", "heads", branch) - stamp = time.time() - hours * 3600 - os.utime(log, (stamp, stamp)) - - def merged_pr(self, branch: str, tip: str, base: str = "develop") -> None: - node = { - "number": 7, - "baseRefName": base, - "headRefOid": tip, - "headRepository": {"nameWithOwner": "o/r"}, - } - self.merged_prs[branch] = [node] - - def wire_sweep( - self, remote_tip: str | None = None, remote_gone: bool = False, **pr: object - ) -> None: - refs: list[object] = [remote_tip, None] if remote_tip else [] - if remote_gone: - refs = [None] - self.wire(cleanup_pr(headRefOid=remote_tip or CLEANUP_HEAD, **pr), refs=refs) - inner = pr_review.shared.request - - def fake(query: str, variables: dict, **kw: Any) -> pr_review.shared.Response: - if query == pr_review.Q_SWEEP_DEFAULT: - head = {"defaultBranchRef": {"name": "main"}} - return pr_review.shared.Response({"repository": head}, []) - if query == pr_review.Q_SWEEP_MERGED: - if variables["b"] in self.failing: - raise pr_review.shared.GraphQLError("gh graphql reported errors") - nodes = self.merged_prs.get(variables["b"], []) - page = {"merged": {"totalCount": len(nodes), "nodes": nodes}} - return pr_review.shared.Response({"repository": page}, []) - return inner(query, variables, **kw) - - self.enterContext(mock.patch.object(pr_review.shared, "request", side_effect=fake)) - - def sweep(self, *extra: str) -> int: - argv = ["cleanup", "--sweep", "--repo", "o/r", "--checkout", self.primary, *extra] - return pr_review.main(argv) - - def scenario(self) -> dict[str, str]: - """Old and finished items beside every kind of item that must stay.""" - made: dict[str, str] = {} - path, tip = self.worktree(CLEANUP_BRANCH) - self.merged_pr(CLEANUP_BRANCH, tip) - self.age(path, 48) - made["merged"] = path - detached = os.path.join(self.root, "wt", "detached") - run_git(self.primary, "worktree", "add", "--detach", detached, "origin/develop") - self.age(detached, 48) - made["detached"] = detached - gone = os.path.join(self.root, "wt", "gone") - run_git(self.primary, "worktree", "add", "--detach", gone, "origin/develop") - admin = Path(gone, ".git").read_text(encoding="utf-8").split(":", 1)[1].strip() - shutil.rmtree(gone) - old = time.time() - 48 * 3600 - os.utime(os.path.join(admin, "index"), (old, old)) - made["gone"] = gone - fresh = os.path.join(self.root, "wt", "fresh-gone") - run_git(self.primary, "worktree", "add", "--detach", fresh, "origin/develop") - shutil.rmtree(fresh) - made["fresh-gone"] = fresh - recent, recent_tip = self.worktree("recent-work") - self.merged_pr("recent-work", recent_tip) - made["recent"] = recent - unmerged, _ = self.worktree("unmerged-work") - self.age(unmerged, 48) - made["unmerged"] = unmerged - dirty, dirty_tip = self.worktree("dirty-work") - self.merged_pr("dirty-work", dirty_tip) - Path(dirty, "scratch.txt").write_text("x", encoding="utf-8") - self.age(dirty, 48) - made["dirty"] = dirty - locked, locked_tip = self.worktree("locked-work") - self.merged_pr("locked-work", locked_tip) - run_git(self.primary, "worktree", "lock", locked) - self.age(locked, 48) - made["locked"] = locked - run_git(self.primary, "branch", "loose-done", "origin/develop") - self.age_branch("loose-done", 48) - run_git(self.primary, "branch", "loose-recent", "origin/develop") - self.advance_origin() - return made - - def test_a_dry_run_reports_every_item_and_removes_nothing(self) -> None: - made = self.scenario() - before = (sorted(self.branches()), sorted(self.listed())) - self.wire_sweep(remote_tip=run_git(self.primary, "rev-parse", CLEANUP_BRANCH)) - self.assertEqual(0, self.sweep()) - self.assertEqual(before, (sorted(self.branches()), sorted(self.listed()))) - self.assertFalse(self.deleted()) - out = self.out.getvalue() - self.assertIn(f"would-remove worktree {made['merged']}", out) - self.assertIn(f"would-remove worktree {made['detached']} detached", out) - self.assertIn(f"would-remove prunable worktree entry {made['gone']}", out) - self.assertIn("would-remove branch loose-done", out) - self.assertIn(f"would-remove remote branch {CLEANUP_BRANCH} via #7", out) - self.assertIn(f"would-fast-forward develop in {self.primary}", out) - self.assertNotIn("removed ", out.replace("would-remove", "")) - - def test_apply_removes_what_is_finished_and_keeps_the_rest(self) -> None: - made = self.scenario() - tip = run_git(self.primary, "rev-parse", CLEANUP_BRANCH) - self.wire_sweep(remote_tip=tip) - self.assertEqual(0, self.sweep("--apply")) - self.assertIn(made["fresh-gone"], self.listed()) - for gone in ("merged", "detached", "gone"): - self.assertNotIn(made[gone], self.listed(), gone) - self.assertFalse(os.path.exists(made["merged"])) - for kept in ("recent", "unmerged", "dirty", "locked"): - self.assertTrue(os.path.isdir(made[kept]), kept) - self.assertIn(made[kept], self.listed(), kept) - branches = self.branches() - self.assertNotIn(CLEANUP_BRANCH, branches) - self.assertNotIn("loose-done", branches) - for kept in ("develop", "main", "loose-recent", "recent-work", "unmerged-work"): - self.assertIn(kept, branches) - self.assertTrue(self.deleted()) - out = self.out.getvalue() - self.assertIn("keep too-recent", out) - self.assertIn("keep unmerged-commits", out) - self.assertIn("keep dirty", out) - self.assertIn("keep locked", out) - self.assertEqual( - run_git(self.primary, "rev-parse", "origin/develop"), - run_git(self.primary, "rev-parse", "develop"), - ) - - def test_a_read_failure_continues_and_exits_2(self) -> None: - made = self.scenario() - early, _ = self.worktree("aa-failing") - self.age(early, 48) - self.failing.add("aa-failing") - tip = run_git(self.primary, "rev-parse", CLEANUP_BRANCH) - self.wire_sweep(remote_tip=tip) - self.assertEqual(2, self.sweep("--apply")) - out = self.out.getvalue() - self.assertLess(out.index("unread worktree"), out.index("removed worktree")) - self.assertNotIn(made["merged"], self.listed()) - self.assertIn(early, self.listed()) - - def test_the_remote_check_in_a_report_names_a_refusal(self) -> None: - self.scenario() - self.wire_sweep(remote_tip=run_git(self.primary, "rev-parse", CLEANUP_BRANCH), merged=False) - self.assertEqual(0, self.sweep()) - out = self.out.getvalue() - self.assertIn("keep-remote via #7", out) - self.assertNotIn("would-remove remote", out) - self.assertFalse(self.deleted()) - - def test_the_remote_check_in_a_report_names_a_branch_already_gone(self) -> None: - self.scenario() - self.wire_sweep(remote_gone=True) - self.assertEqual(0, self.sweep()) - self.assertIn(f"remote already gone {CLEANUP_BRANCH} via #7", self.out.getvalue()) - - def test_a_loose_branch_whose_tip_moved_is_kept_as_tip_moved(self) -> None: - run_git(self.primary, "branch", "loose-done", "origin/develop") - self.age_branch("loose-done", 48) - self.wire_sweep() - moved = pr_review.CleanupRefused("LOCAL_TIP_MOVED", "moved") - with mock.patch.object(pr_review, "cleanup_delete_branch", side_effect=moved): - self.assertEqual(0, self.sweep("--apply")) - self.assertIn("keep tip-moved branch loose-done", self.out.getvalue()) - - def test_main_and_develop_survive_a_sweep_with_no_age_floor(self) -> None: - run_git(self.primary, "checkout", "-b", "primary-work") - self.wire_sweep() - self.assertEqual(0, self.sweep("--apply", "--min-age-hours", "0")) - for kept in ("main", "develop", "primary-work"): - self.assertIn(kept, self.branches()) - - def test_the_primary_checkout_branch_is_never_touched(self) -> None: - run_git(self.primary, "checkout", "-b", "primary-work") - self.age_branch("primary-work", 48) - self.wire_sweep() - self.assertEqual(0, self.sweep("--apply")) - self.assertIn("primary-work", self.branches()) - for line in self.out.getvalue().splitlines(): - if "primary-work" in line: - self.assertTrue(line.startswith("keep base-not-on-develop"), line) - - def test_a_branch_without_a_reflog_is_kept_as_age_unreadable(self) -> None: - run_git(self.primary, "branch", "loose-done", "origin/develop") - os.remove(os.path.join(self.primary, ".git", "logs", "refs", "heads", "loose-done")) - self.wire_sweep() - self.assertEqual(0, self.sweep("--apply")) - self.assertIn("keep age-unreadable branch loose-done", self.out.getvalue()) - self.assertIn("loose-done", self.branches()) - - def gone_on_branch(self, branch: str, entry_hours: float = 48) -> str: - """A finished, idle branch whose worktree directory is gone, its record `entry_hours` old.""" - gone = os.path.join(self.root, "wt", branch) - run_git(self.primary, "worktree", "add", "-b", branch, gone, "origin/develop") - admin = Path(gone, ".git").read_text(encoding="utf-8").split(":", 1)[1].strip() - shutil.rmtree(gone) - old = time.time() - entry_hours * 3600 - os.utime(os.path.join(admin, "index"), (old, old)) - self.age_branch(branch, 48) - return gone - - def test_a_pruned_entry_s_branch_is_swept_in_the_same_run(self) -> None: - gone = self.gone_on_branch("gone-done") - self.advance_origin() - self.wire_sweep(remote_tip=None) - self.assertEqual(0, self.sweep("--apply")) - self.assertNotIn(gone, self.listed()) - self.assertNotIn("gone-done", self.branches()) - - def test_a_dry_run_reports_a_prunable_entry_s_branch(self) -> None: - self.gone_on_branch("gone-done") - self.advance_origin() - self.wire_sweep(remote_tip=None) - self.assertEqual(0, self.sweep()) - self.assertIn("gone-done", self.branches()) - self.assertIn("would-remove branch gone-done", self.out.getvalue()) - - def test_a_too_recent_prunable_entry_still_holds_its_branch(self) -> None: - gone = self.gone_on_branch("gone-recent", entry_hours=0) - self.advance_origin() - self.wire_sweep(remote_tip=None) - self.assertEqual(0, self.sweep()) - self.assertNotIn("would-remove branch gone-recent", self.out.getvalue()) - self.assertEqual(0, self.sweep("--apply")) - self.assertIn(gone, self.listed()) - self.assertIn("gone-recent", self.branches()) - - def test_a_failed_prune_is_counted_and_the_other_items_still_run(self) -> None: - made = self.scenario() - self.gone_on_branch("gone-failed") - tip = run_git(self.primary, "rev-parse", CLEANUP_BRANCH) - self.wire_sweep(remote_tip=tip) - real = pr_review.cleanup_git - - def failing(root: str, *args: str, **kw: Any) -> subprocess.CompletedProcess[str]: - if args[:2] == ("worktree", "prune"): - raise pr_review.CleanupUnread("prune failed") - return real(root, *args, **kw) - - with mock.patch.object(pr_review, "cleanup_git", side_effect=failing): - self.assertEqual(2, self.sweep("--apply")) - self.assertIn("unread prunable worktree entries", self.out.getvalue()) - self.assertNotIn("branch gone-failed", self.out.getvalue()) - self.assertIn("gone-failed", self.branches()) - self.assertNotIn(made["merged"], self.listed()) - - def test_a_stale_remote_ref_for_a_deleted_branch_is_not_containment(self) -> None: - stale = os.path.join(self.root, "wt", "stale-detached") - run_git(self.primary, "worktree", "add", "--detach", stale, "origin/develop") - self.count += 1 - self.commit(stale, f"only on a deleted branch {self.count}") - run_git(stale, "push", "origin", "HEAD:refs/heads/gone-branch") - run_git(self.primary, "fetch", "origin") - run_git(self.bare, "branch", "-D", "gone-branch") - self.age(stale, 48) - sha = run_git(stale, "rev-parse", "HEAD") - self.wire_sweep() - for extra in ((), ("--apply",)): - run_git(self.primary, "update-ref", "refs/remotes/origin/gone-branch", sha) - self.assertEqual(0, self.sweep(*extra)) - out = self.out.getvalue() - self.assertIn(f"keep unpushed-commits worktree {stale} detached", out) - self.assertNotIn(f"would-remove worktree {stale}", out) - self.assertIn(stale, self.listed()) - - def test_a_primary_paused_mid_rebase_keeps_the_branch_in_both_modes(self) -> None: - run_git(self.primary, "checkout", "-b", "rebasing-work") - for n in range(3): - self.commit(self.primary, f"primary work {n}") - tip = run_git(self.primary, "rev-parse", "HEAD") - self.pause_rebase(self.primary) - self.merged_pr("rebasing-work", tip) - self.age_branch("rebasing-work", 48) - self.wire_sweep() - for extra in ((), ("--apply",)): - self.assertEqual(0, self.sweep(*extra)) - self.assertIn("keep in-progress-operation branch rebasing-work", self.out.getvalue()) - self.assertIn("rebasing-work", self.branches()) - - def test_a_worktree_with_submodules_is_kept(self) -> None: - path, tip = self.worktree("modular-work") - self.merged_pr("modular-work", tip) - Path(path, ".gitmodules").write_text("", encoding="utf-8") - self.age(path, 48) - self.wire_sweep() - self.assertEqual(0, self.sweep("--apply")) - self.assertIn("keep submodules", self.out.getvalue()) - self.assertIn(path, self.listed()) - - def test_a_shell_inside_a_worktree_keeps_it_on_windows(self) -> None: - path, tip = self.worktree("held-work") - self.merged_pr("held-work", tip) - self.age(path, 48) - self.wire_sweep() - before = os.getcwd() - self.addCleanup(os.chdir, before) - os.chdir(path) - with mock.patch.object(pr_review, "ON_WINDOWS", True): - self.assertEqual(0, self.sweep("--apply")) - self.assertIn("keep cwd-inside", self.out.getvalue()) - self.assertIn(path, self.listed()) - - def test_a_worktree_mid_operation_is_kept(self) -> None: - path, tip = self.worktree("paused-work") - self.merged_pr("paused-work", tip) - admin = Path(run_git(path, "rev-parse", "--absolute-git-dir")) - (admin / "BISECT_LOG").write_text("\n", encoding="utf-8") - self.age(path, 48) - self.wire_sweep() - self.assertEqual(0, self.sweep("--apply")) - self.assertIn("keep in-progress-operation", self.out.getvalue()) - self.assertIn(path, self.listed()) - self.assertIn("paused-work", self.branches()) - - def test_a_branch_being_bisected_elsewhere_is_kept_as_in_progress(self) -> None: - path, tip = self.worktree("bisected-work", commits=3) - self.merged_pr("bisected-work", tip) - run_git(path, "bisect", "start") - run_git(path, "bisect", "bad", "HEAD") - run_git(path, "bisect", "good", "HEAD~2") - self.age(path, 48) - self.age_branch("bisected-work", 48) - self.wire_sweep() - self.assertEqual(0, self.sweep("--apply")) - self.assertIn("keep in-progress-operation branch bisected-work", self.out.getvalue()) - self.assertIn("bisected-work", self.branches()) - self.assertIn(path, self.listed()) - - def test_a_branch_delete_git_refuses_is_kept_as_checked_out_elsewhere(self) -> None: - run_git(self.primary, "branch", "loose-done", "origin/develop") - self.age_branch("loose-done", 48) - self.wire_sweep() - real = pr_review.cleanup_git - - def refusing(root: str, *args: str, **kw: Any) -> subprocess.CompletedProcess[str]: - if args[:2] == ("branch", "-D"): - return subprocess.CompletedProcess([], 1, "", "error: used by worktree") - return real(root, *args, **kw) - - with mock.patch.object(pr_review, "cleanup_git", side_effect=refusing): - self.assertEqual(0, self.sweep("--apply")) - self.assertIn("keep checked-out-elsewhere branch loose-done", self.out.getvalue()) - - def test_a_branch_behind_a_merged_head_counts_as_finished(self) -> None: - path, _ = self.worktree("behind-work") - self.count += 1 - ahead = self.commit(path, f"merged tip {self.count}") - run_git(self.primary, "branch", "ahead", ahead) - run_git(path, "reset", "--hard", "HEAD~1") - run_git(self.primary, "worktree", "remove", path) - self.merged_pr("behind-work", ahead) - self.age_branch("behind-work", 48) - self.wire_sweep(remote_tip=ahead) - self.assertEqual(0, self.sweep()) - self.assertIn("would-remove branch behind-work", self.out.getvalue()) - - def test_a_checkout_naming_another_repository_is_refused(self) -> None: - run_git(self.primary, "remote", "set-url", "origin", "https://github.com/other/repo.git") - self.wire_sweep() - self.assertEqual(1, self.sweep("--apply")) - self.assertIn("status=BAD_CHECKOUT", self.out.getvalue()) - - if __name__ == "__main__": unittest.main(verbosity=2) From 5ac2228265a828260d0de1408faaed7ddd4aa427 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Fri, 23 Oct 2026 11:40:12 -0700 Subject: [PATCH 03/22] Read Reviewer Bodies through the Adapter and markdown-it-py Route every body reading in pr_review.py through pr_review_copilot.py and delete the hand-written Markdown reader: CodeSpans, the fence and tag helpers, and the details and summary opener readers. The digest's three collect-split-count copies become one function, and the readers for Copilot's first body format, the statement carry, and the prose, narrative, and headline finding pairings are retired. Coverage from a file table and from a recorded partial stays. Comments and docstrings in pr_review.py and pr_cleanup.py are condensed under their ceilings. Co-Authored-By: Claude Opus 5.5 --- scripts/pr_cleanup.py | 173 +- scripts/pr_review.py | 5231 ++++------------------------- scripts/pr_review_copilot.py | 41 +- scripts/reviewers/coderabbit.json | 1 + scripts/reviewers/copilot.json | 1 + scripts/reviewers/qodo.json | 1 + 6 files changed, 688 insertions(+), 4760 deletions(-) diff --git a/scripts/pr_cleanup.py b/scripts/pr_cleanup.py index d0eae7fdf..4507d5f3a 100755 --- a/scripts/pr_cleanup.py +++ b/scripts/pr_cleanup.py @@ -10,43 +10,27 @@ `pr_review.py cleanup` forwards here, so a command line naming either script runs the same code. -Delete a merged pull request's head branch, the verify-then-delete `drive-pr` and -`merge-and-release` prescribe, done here so it runs under the one allow rule the host-safety -installer registers for this script rather than as a hand-typed delete. That rule approves any -arguments, so every check lives here. It takes the pull request number, never a branch name, and -reads the branch from the pull request. It refuses unless the pull request is merged into `develop` -from a head in `--repo` itself, and the head branch is none of `develop`, `main`, or the default -branch read live. The owner is bound to `registry/repos.json`, and the repository must be -registered or a fork, by `handoff.py`'s own write-scope check. It refuses a branch any ruleset or -branch protection covers, since the write guard's per-branch check never sees a delete made in -here. It refuses a branch an open pull request in `--repo` has as its head or base, naming each. -The ref is read exactly, its tip is checked against the pull request's `headRefOid` before the -delete is sent, and the delete is confirmed by reading the ref back. The delete itself carries no -expected tip, so this is verify-then-delete rather than a compare-and-swap. With `--checkout -`, a local half follows a remote half that exited 0, on the pull request's own -branch and head commit. Every refusal is decided before anything is deleted, the remote branch -included. A re-check after the delete can still refuse when a concurrent session changed the branch -or a worktree in between. The output then names what already happened. A locked, dirty, or -mid-operation worktree refuses. So does a branch tip that is neither the merged head nor behind it. -So does a rebase or bisect paused on the branch in any worktree, the primary included. A worktree -entry whose directory is gone is removed. The primary leaves the merged branch before the remote -delete, and a failed checkout refuses. The local half removes the worktrees holding the branch. It -deletes the local branch only at the merged head or an ancestor of it, after a tip re-read shows it -unchanged. Then it fast-forwards the clone to current `develop`, never a reset, stash, or force. A -clone left behind is reported and does not fail the run. The clone must be a primary checkout whose -origin is `--repo`. +The verify-then-delete `drive-pr` and `merge-and-release` prescribe, run under the one allow rule +the host-safety installer registers for this script, so every check lives here. It takes the pull +request number, never a branch name. It refuses unless the pull request is merged into `develop` +from a head in `--repo` itself, the head is not `develop`, `main`, or the default branch, the +owner and repository pass `handoff.py`'s write-scope check, no ruleset or protection covers the +branch, and no open pull request has it as head or base. The tip is checked against the pull +request's `headRefOid` before the delete and the delete is confirmed by reading the ref back. + +With `--checkout `, a local half follows a remote half that exited 0. Every refusal +is decided before anything is deleted. A locked, dirty, or mid-operation worktree refuses, as does +a branch tip neither at the merged head nor behind it. The local half removes the worktrees +holding the branch, deletes the local branch, and fast-forwards the clone to `develop`, never a +reset, stash, or force. A clone left behind is reported and does not fail the run. `cleanup --sweep --checkout ` takes no pull request. It reports what is provably finished, one `would-remove` or `keep ` line per worktree or branch, and removes it only -with `--apply`. The report fetches and prunes the remote-tracking refs of `origin` and writes -nothing else. An item must sit untouched for `--min-age-hours` (default 24) and be clean. A branch -is finished when a pull request from `--repo` merged it at its exact tip or past it. It is also -finished when `origin/develop` or `origin/main` contains it. A detached worktree is finished when -any `origin` ref contains its commit. For a merged develop pull request the sweep also deletes the -remote head branch through the same checks as `cleanup `. The report runs those checks and names -the result. The sweep never touches the primary checkout except to fast-forward a tracked-clean -`develop` to `origin/develop`, and the report names that step. Permanent branches, locked -worktrees, and worktrees mid-operation are never touched. +with `--apply`. An item must sit untouched for `--min-age-hours` (default 24) and be clean. A +branch is finished when a pull request from `--repo` merged it at its exact tip or past it, or +`origin/develop` or `origin/main` contains it. For a merged develop pull request the sweep also +deletes the remote head branch through the same checks as `cleanup `. Permanent branches, +locked worktrees, and worktrees mid-operation are never touched. Exit 0 = deleted and confirmed gone, or already gone, or a sweep that completed. Exit 1 = refused, a moved tip naming both commits among them. Exit 2 = a read did not answer, a partial one included. @@ -113,11 +97,7 @@ class CleanupUnread(Exception): def cleanup_read(query: str, **variables: object) -> dict: - """One GraphQL read for `cleanup`, raising rather than ending the run at exit 1. - - `gh_graphql` exits 1 on a failed read, which is `cleanup`'s refusal code, so a read that could - not answer would be reported as a refusal the caller can act on. - """ + """One GraphQL read for `cleanup`, raising rather than ending the run at exit 1.""" try: return shared.request(query, variables).data except shared.GraphQLError as exc: @@ -136,11 +116,7 @@ def cleanup_rest(path: str, what: str) -> object: def cleanup_ref(owner: str, repo: str, branch: str) -> dict | None: - """The branch's ref node, or None where the branch does not exist. - - The read is by exact qualified name, so a branch sharing a suffix never answers for it. The - node id it returns goes straight to the delete, so no caller ever holds one to mistype. - """ + """The branch's ref node, or None where the branch does not exist.""" data = cleanup_read(Q_CLEANUP_REF, o=owner, r=repo, q=f"refs/heads/{branch}") repository = data.get("repository") if not isinstance(repository, dict): @@ -155,11 +131,7 @@ def cleanup_ref(owner: str, repo: str, branch: str) -> dict | None: def branch_rules(owner: str, repo: str, branch: str) -> list[str]: - """What protects the branch, rulesets and classic protection alike, empty where nothing does. - - The branch travels inside a REST path, so a name that would change the path is not read, and - an unread rule set is never reported as no rules. - """ + """What protects the branch, rulesets and classic protection alike, empty where nothing does.""" if core.UNSAFE_REF.search(branch) or core.DOT_SEGMENT.search(branch): raise CleanupUnread( f"the head branch {branch!r} holds a character that changes a REST path, so the " @@ -185,13 +157,7 @@ def in_repository(node: dict, owner: str, repo: str) -> bool: def local_heads(owner: str, repo: str, branch: str) -> list[object]: - """The number of each open pull request whose head is the branch in `owner/repo`. - - The connection also holds forks' pull requests on a same-named branch. So every page is read - and filtered to this repository's own before anything is decided, and a fork's is never - counted. A page that does not answer, or one that cannot be followed to the next, raises rather - than reading as no pull request. - """ + """The number of each open pull request whose head is the branch in `owner/repo`.""" def fetch(cursor: str | None) -> dict: extra = {"after": cursor} if cursor else {} @@ -212,13 +178,7 @@ def fetch(cursor: str | None) -> dict: def branch_users(owner: str, repo: str, branch: str) -> list[str]: - """The open pull requests in this repository whose head or base is the branch. - - Deleting a branch closes every open pull request headed on it. It retargets or closes the ones - based on it, so each is named where one exists. Every head is read, per `local_heads`. A base - past the twenty read is counted rather than named, every one being this repository's own. An - unanswered read is never reported as no pull request. - """ + """The open pull requests in this repository whose head or base is the branch.""" users = [f"#{number} (head)" for number in local_heads(owner, repo, branch)] data = cleanup_read(Q_CLEANUP_BASES, o=owner, r=repo, b=branch) repository = data.get("repository") @@ -302,10 +262,7 @@ def cleanup_check(owner: str, repo: str, num: int) -> CleanupPlan: def cleanup_fresh(owner: str, repo: str, plan: CleanupPlan) -> CleanupPlan: - """Read the remote branch again right before its delete, so the delete uses a fresh node id. - - The checks and the local preflight take time, and another session may have pushed since. - """ + """Read the remote branch again right before its delete, so the delete uses a fresh node id.""" if plan.ref is None: return plan ref = cleanup_ref(owner, repo, plan.branch) @@ -322,11 +279,7 @@ def cleanup_fresh(owner: str, repo: str, plan: CleanupPlan) -> CleanupPlan: def cleanup_remote_delete(owner: str, repo: str, plan: CleanupPlan) -> int: - """Delete the remote branch `plan` verified and read it back. - - A delete that reports a failure may still have landed, so the read back decides the outcome - either way. - """ + """Delete the remote branch `plan` verified and read it back.""" target = f"{owner}/{repo}" branch = plan.branch if plan.ref is None: @@ -464,11 +417,7 @@ class Worktree(NamedTuple): def cleanup_git( root: str, *args: str, ok: tuple[int, ...] = (0,) ) -> subprocess.CompletedProcess[str]: - """One git call in `root` as an argv list, raising with its stderr on an unexpected code. - - A return code the caller lists in `ok` is an answer it reads. Any other code is a call that - did not do what was asked, so it is shown and ends the step rather than swallowed. - """ + """One git call in `root` as an argv list, raising with its stderr on an unexpected code.""" try: proc = subprocess.run( ["git", "-C", root, *args], @@ -488,12 +437,7 @@ def cleanup_git( def cleanup_primary(checkout: str, target: str) -> str: - """The real path of the primary checkout at `checkout`, refusing anything else. - - A linked worktree is refused, since removing worktrees and moving branches belongs to the - clone that owns them. So is an origin naming another repository, since every local step - here derives from a pull request in `target`. - """ + """The real path of the primary checkout at `checkout`, refusing anything else.""" probe = cleanup_git( checkout, "rev-parse", @@ -546,11 +490,7 @@ def cleanup_tip(primary: str, ref: str) -> str | None: def cleanup_dirty(path: str, untracked: bool) -> bool: - """Whether the work tree at `path` has changes, without refreshing its index. - - `--no-optional-locks` keeps the read from rewriting the index, which would make an untouched - tree look touched to the age rule of `--sweep`. - """ + """Whether the work tree at `path` has changes, without refreshing its index.""" flag = "--untracked-files=all" if untracked else "--untracked-files=no" out = cleanup_git(path, "--no-optional-locks", "status", "--porcelain", flag).stdout return bool(out.strip()) @@ -567,10 +507,7 @@ def cleanup_dirty(path: str, untracked: bool) -> bool: def cleanup_admin(path: str) -> str | None: - """The git directory holding the worktree at `path`'s state, or None where unreadable. - - A linked worktree names it in its `.git` file, and a primary checkout's `.git` is it. - """ + """The git directory holding the worktree at `path`'s state, or None where unreadable.""" if os.path.isdir(os.path.join(path, ".git")): return os.path.join(path, ".git") try: @@ -589,10 +526,7 @@ def cleanup_in_progress(path: str) -> bool: def cleanup_operation_names(path: str) -> set[str]: - """The branch names a rebase or bisect paused in the worktree at `path` is working on. - - Either detaches HEAD, so the worktree no longer lists the branch it will return to. - """ + """The branch names a rebase or bisect paused in the worktree at `path` is working on.""" admin = cleanup_admin(path) names: set[str] = set() if admin is None: @@ -712,20 +646,13 @@ def cleanup_base(primary: str, apply: bool = True) -> bool: def cleanup_behind(primary: str, tip: str, head: str) -> bool: - """Whether commit `tip` is an ancestor of `head`, so it holds nothing `head` lacks. - - A `head` object this clone lacks proves nothing, and reads as not behind. - """ + """Whether commit `tip` is an ancestor of `head`, so it holds nothing `head` lacks.""" proc = cleanup_git(primary, "merge-base", "--is-ancestor", tip, head, ok=(0, 1, 128)) return proc.returncode == 0 def cleanup_preflight(primary: str, branch: str, head: str) -> tuple[str | None, list[Worktree]]: - """Fetch, then decide every local refusal, returning the branch tip and the worktrees to remove. - - Nothing is removed here, so a refusal leaves all of it in place. `head` is the commit the - merged pull request carried, read live by the remote half. - """ + """Fetch, then decide every local refusal, returning the branch tip and the worktrees to remove.""" cleanup_git(primary, "fetch", "--prune", "origin") ref = f"refs/heads/{branch}" tip = cleanup_tip(primary, ref) @@ -780,10 +707,7 @@ def cleanup_preflight(primary: str, branch: str, head: str) -> tuple[str | None, def cleanup_leave_branch(primary: str, branch: str) -> None: - """Move the primary checkout to `develop` where it holds `branch`, refusing if git will not. - - This runs before the remote delete, so a checkout that fails still deletes nothing. - """ + """Move the primary checkout to `develop` where it holds `branch`, refusing if git will not.""" if not any(w.path == primary and w.branch == branch for w in cleanup_worktrees(primary)): return try: @@ -796,12 +720,7 @@ def cleanup_leave_branch(primary: str, branch: str) -> None: def cleanup_local(primary: str, branch: str, head: str) -> int: - """Remove the finished branch's worktrees and local branch, then return the base clone. - - The refusals are decided again before the first removal, so a refused run leaves all of it - in place. The base clone's return is reported and never fails the run. The local branch is - deleted only at `head` or an ancestor of it, after a tip re-read shows it unchanged. - """ + """Remove the finished branch's worktrees and local branch, then return the base clone.""" try: tip, linked = cleanup_preflight(primary, branch, head) except CleanupRefused as exc: @@ -875,11 +794,7 @@ def newest_hours(self, paths: list[str]) -> float: return float("inf") if not stamps else (time.time() - max(stamps)) / 3600 def worktree_hours(self, w: Worktree) -> float | None: - """The idle hours of a linked worktree, or None where its admin directory is unreadable. - - Taken before any status runs on it, and from the admin files git itself writes on use. - The directory's own mtime moves only when an entry is added or removed. - """ + """The idle hours of a linked worktree, or None where its admin directory is unreadable.""" admin = cleanup_admin(w.path) if admin is None: return None @@ -918,11 +833,7 @@ def finished(self, branch: str, tip: str) -> tuple[str, int | None] | None: return None def remote(self, num: int | None, branch: str) -> None: - """Report, or with `apply` run, the remote half for a merged develop pull request. - - The remote half makes its own checks, so its refusal keeps only the remote branch. A - report runs those same checks and writes nothing. - """ + """Report, or with `apply` run, the remote half for a merged develop pull request.""" if num is None: return if not self.apply: @@ -987,11 +898,7 @@ def run(self) -> int: return 2 if self.problems else 0 def prune(self, stale: list[Worktree]) -> set[str]: - """Prune the entries whose directory is gone and whose record is old enough. - - Returns the paths pruned, or under a report the paths a prune would remove, so their - branches are no longer held and are judged as loose branches in the same run. - """ + """Prune the entries whose directory is gone and whose record is old enough.""" old = [] for w in stale: hours = self.entry_hours(w) @@ -1021,11 +928,7 @@ def prune(self, stale: list[Worktree]) -> set[str]: return {w.path for w in old if w.path not in left} def entry_hours(self, w: Worktree) -> float: - """The idle hours of a missing worktree's record, from the `index` file prune reads. - - Git prunes by the age of that file, and by nothing once it is gone. An entry this cannot - match reads as brand new, so it is kept. - """ + """The idle hours of a missing worktree's record, from the `index` file prune reads.""" base = os.path.join(self.common, "worktrees") try: names = os.listdir(base) diff --git a/scripts/pr_review.py b/scripts/pr_review.py index 78ce5f154..06368dc27 100755 --- a/scripts/pr_review.py +++ b/scripts/pr_review.py @@ -1,4 +1,8 @@ #!/usr/bin/env python3 +# /// script +# requires-python = ">=3.13" +# dependencies = ["markdown-it-py>=4"] +# /// """Consolidated Copilot-review status for a PR - one command, one compact digest. Why this exists: 4,513 of the measured `gh` invocations were one call per agent turn, and @@ -7,237 +11,79 @@ invocation whose output is a few hundred bytes. See GOVERNANCE.md "Context and Delegation Discipline" for the rule this implements. +This file is the gate: the plumbing, the checks, the verdict, the wait loop, and the writes. +What a reviewer's body says is read by `pr_review_copilot.py`, whose vocabulary lives in +`reviewers/.json`, so a change in the reviewer's wording is a data edit there and never +an edit here. A shape the adapter cannot place prints as a note under `shapes=NOTED` and decides +no exit code. + Subcommands attest Publish that a recorded local pass covers the pull request's head, as a comment carrying `` that `status` and - `wait` read, an attestation counting only against the base it names. The comment outlives - the receipt, which removing the worktree deletes. A promotion reads the comment only in - its Merge Gate's per-file fallback, per pr-review-conduct. `attest` reads the receipt - `local_review.py` keeps in the checkout's git directory, which nothing on GitHub can, and - refuses unless the checkout (--checkout, default the current directory) is at the pull - request's head with no change beyond it, its merge base with the base branch is the pull - request's own, and `local_review.py status` reports a covering pass against the base, - read once for the coverage and the findings count alike. Exit 0 = posted, 64 = the write - scope could not be established or excludes the target, 65 = the pull request could not be - read, 66 = the response did not confirm the comment, 67 = the checkout is not the head, - holds changes, or measures another merge base, or that merge base could not be read, 68 = - no current local pass covers the content. + `wait` read, an attestation counting only against the base it names. It reads the + receipt `local_review.py` keeps in the checkout's git directory and refuses unless the + checkout (--checkout, default the current directory) is at the pull request's head with + no change beyond it, its merge base with the base branch is the pull request's own, and + `local_review.py status` reports a covering pass against the base. Exit 0 = posted, + 64 = the write scope could not be established or excludes the target, 65 = the pull + request could not be read, 66 = the response did not confirm the comment, 67 = the + checkout is not the head, holds changes, or measures another merge base, or that merge + base could not be read, 68 = no current local pass covers the content. comment Post one PR-conversation answer, including a suppressed-finding disposition. The PR node id is read in the same run, and the returned comment URL and body confirm the write. Exit 0 = done, 64 = write scope could not be established or excludes the target, 65 = the PR could not be read, 66 = the response did not confirm the comment. claims Check the description against the branch it describes. A body claiming a commit or quoting a `uses:` ref the head tree no longer carries is a silent failure caught by a - reviewer or not at all, and three stale descriptions in one session generated six - review findings between them. Read-only. Exit 0 = every reference resolves, 70 = one - does not, 71 = there were references and none could be read, so nothing was decided. + reviewer or not at all. Read-only. Exit 0 = every reference resolves, 70 = one does + not, 71 = there were references and none could be read, so nothing was decided. cleanup Forwarded to `pr_cleanup.py`, which holds the contract and the exit codes, so a command line naming this script keeps working under the allow rule the host-safety installer registers for it. - status One digest line, any unresolved threads, and any suppressed findings. Read-only. - Exit 0 = no Copilot review covers the head yet, or every output shape is recognized - and full diff coverage is stated for this head, by the round covering it or by the - carry below, or where nothing states or carries any, a round covering the head names - exactly the changed files in its own file table, `coverage=table` in the digest, or - where no round covering the head carries a table, the newest round that does names - them under the same change-set bound, `coverage=carried:table`, or an attested local - pass covers the head as described below, `coverage=local`. - `review_on_head` and `rounds=` - in the digest name Copilot's own coverage specifically, the reviewer this script - requests and waits for, never "no review of any kind covers this head": a - tracked other reviewer, named under `other_reviewed` below, can carry the exact head - commit while Copilot's own `review_on_head` still reads `NO`, and an empty body from - that other reviewer on that head is its own ordinary "reviewed, nothing to flag" - shape, the same reading an empty-bodied Copilot round already gets, not a gap. - `review_on_head=local` reads a head no Copilot round covers on a pull request into a - branch other than the default, with `coverage=local` beside it. That reading needs an - attestation vouching for the head, and no round on record stating or appearing to state - partial coverage. + status One digest line, any unresolved threads, and any finding no thread carries. Read-only. + Exit 0 = no Copilot review covers the head yet, or the review covering it states no + partial coverage and its verdict counts what it flags. 42 = the round covering the + head states it read fewer files than the pull request changed, or states nothing while + an earlier round on record states partial coverage. 50 = that round opens on a verdict + other than the clean one while it counts no finding, opens no thread, collapses no + suppressed or previously-missed finding, and no thread is open, so what it flags is + named in its headline alone, printed under `VERDICT WITH NO COUNTED FINDING`. The code + repeats on that head after the headline is answered, since nothing here reads an + answer. A clean verdict on the same terms prints its headline under `CLEAN VERDICT + HEADLINE`, which changes no exit code. + `coverage=` names how the head's diff is shown read: `full` or `PARTIAL` as the round + states it, `UNKNOWN` for a statement this cannot believe, `table` where a round + covering the head names exactly the changed files in its own file table, + `carried:table` where the newest round carrying a table does, `local` where an attested + local pass covers a head on a pull request into a branch other than the default, and + `none` otherwise. A table stands in only where no round on record states partial + coverage and the whole review history is in view. `none` decides no exit code and + prints a note, since Merge Gate item 2 in pr-review-conduct reads this field. A promotion re-reviews content its feature pull requests already carried, so the hosted - review runs once per change, at the promotion. On a pull request into any other branch, - the attested local pass alone covers every head. Under the same conditions the - attestation also covers a head whose Copilot round states no coverage, has none carried - to it, and carries no file table, which reads `review_on_head=yes coverage=local`. - Use `wait` when review presence is the condition, since `status` reports an absent - review without treating it as a failure. - 42 = a round read fewer files than the pull request changed, so part of the diff - has no review at all. That round is the one covering the head, or the one carried - to it under 45 below, an unread part staying unread across a push that leaves the - change set alone. Measured over four pull requests and seven rounds here, a - re-request never cleared one and no round ever recovered, so this is a state to - hand to the maintainer rather than one to retry into. - 43 = the reviewer sent a shape this script has no reader for, so no field here can - be believed. The remedy is an issue on the repository hosting this script, and the - review loop does not close until the reader is fixed. Merging regardless is the - maintainer's decision rather than the agent's. - 45 = no statement of changed-file coverage describes this head, and no file table or - attested local pass stands in for one. A round that - states none carries the newest round that states some forward, bounded on the change - set, so this covers three states: nothing ever stated coverage, the round that did - describes a different set of changed files, or that comparison could not be read. - Past those, a round covering the head whose own table names exactly the changed - files stands in, or where none carries a table, the newest round that does, its table - naming exactly the changed files, under the same change-set bound. Either table - stands in only where no Copilot round on the pull request, on any commit, states or - appears to state partial coverage, quoted or not, and the whole review - history is in view, since over the rounds measured the table names the whole changed - set on partial rounds too. The digest names why no table stood in. - Copilot's Balanced review effort, the default since 2026-09-28, writes the table and - almost never a statement, which is the case the table reading exists for. - Where the head branch lacks the current review instructions, which a round at Lite - effort needs to state coverage, bring them onto it, push, and run `wait`, which requests a round on the new head, and where the - comparison could not be read, run `status` again. Past those, a develop -> main - promotion can still satisfy coverage, in the one case pr-review-conduct's Merge Gate - item 2 states. Otherwise hand the state to the maintainer rather than retrying into - it, since a round - re-requested on the same head states coverage or carries a table only by chance. - 50 = the round covering the head opens on a verdict other than the clean one, while it - states no open finding, opened no thread, collapsed no suppressed or previously-missed - finding, and no reviewer's thread is open, so what it flags is named in its headline - alone, printed under `VERDICT WITH NO COUNTED FINDING`. Ranked under 42, 43, and 45, - and over `wait`'s 44. - The headline is owed the triage a suppressed finding gets, and the code repeats on that - head after it is answered, since nothing here reads an answer. - A clean verdict on the same terms prints its headline under `CLEAN VERDICT HEADLINE`. - That line is advisory and changes no exit code, since it may name an answered nit. - A refusal naming the account quota still reads as absent here, exit 0, since a refusal - covers no head either. Its printed digest line carries `refusal=QUOTA` regardless, and - `refusal=ERROR` for an error refusal whose run log names no rate limit or could not be - read. Either field reads the pull request's newest Copilot review where it is a quota or - error refusal, on an earlier head or over a head a genuine round covered before it, and a - file-count refusal is spent by coverage of the same head. `wait` is where that state gets - its own exit codes, 46 and 47 below, because only `wait` is the command a caller might - otherwise poll out a timeout on. - `unresolved` counts every open thread whoever opened it, since an open thread blocks - a ruleset-gated merge whatever its author, and a filter on known reviewer logins - once read `unresolved=0` over a qodo thread posted under a login it did not know. - The known logins, Copilot, CodeRabbit (`coderabbitai`), and qodo - (`qodo-free-for-open-source-projects`), only attribute a thread in the breakdown - beside the count, where any other author reads as `other`. - Both `threads=` and `unresolved=` are read from a single 100-thread page with no - further pagination, so a pull request carrying more than that undercounts silently - past that point: both fields print a trailing `+` and a `THREADS TRUNCATED` block - follows, naming the gap rather than leaving either count to be trusted as whole. - Reading past the cut needs `reply`'s own paginated walk instead. `suppressed=` - and `cr_outside_diff=` carry the identical marker over the separate 100-review page - they are both read from, a `REVIEWS TRUNCATED` block following, since an unanswered - finding on a round old enough to fall out of that window is exactly as invisible. - Coverage, refusal, and `wait`/request support stay Copilot-only, each being its own - format and its own future task per bot. Where either has posted anything at all on - the current head, `other_reviewed` names it, identity and commit only, no verdict - read from what it said. `other_rate_limited` names one whose newest comment or review - carries its own rate-limit marker instead. That marker is a structural - `` convention rather than free-text prose (observed on - CodeRabbit). Reading it needs no per-bot wording model the way Copilot's quota refusal - needed `QUOTA` built for its own text. CodeRabbit's reply to an explicit review command - lands in the same field, read by a pattern of its own for CodeRabbit's fixed wording. - That reply is an `auto-generated reply` marker over an `Action not completed` block - saying `Review rate limited.`, and its service is named from the login. - Two of their own finding shapes are read, though, each its own blind spot a thread - poll alone cannot see. `cr_outside_diff=N (on_head=X earlier=Y)` counts - CodeRabbit's own "outside diff range" findings, collapsed into the review body rather - than raised as an inline review comment because the finding sits on a line outside - the pull request's changed hunks. Printed once CodeRabbit has raised one, on any - round, or once the reviews window is truncated, since an older round could then - still carry one unseen (`cr_outside_diff=0+`). Stays silent otherwise, whether that - silence means no finding was raised or CodeRabbit was never trialed at all. - `qodo_open=N` counts Qodo's own - numbered findings that carry neither its `Resolved` nor `Dismissed` self-tracked - badge: Qodo's formal review carries an empty body on every round observed, so its - findings are read from its "Code Review by Qodo" PR-level comment instead, not - head-scoped since a comment carries no commit. Printed as `0` once Qodo has posted - that comment at all, since a `0` is itself a reading, `unknown` where its findings - comment specifically could be sitting behind the 100-comment window even while a - paired `PR Summary by Qodo` stays visible, so its silence cannot be told from it - never having commented, and absent only where it genuinely never has. Qodo's own - badge is a fast pre-triage signal, not a substitute for reading the finding: - spot-verify against `gh pr diff` rather than trusting it outright. - `overview=T/M` reads the second Copilot review-body format's own finding total, `T`, - beside the number of review threads that round actually opened, `M`. `T` reads `?` - where no total is found in the overview preamble or in a count-first open-findings - section, which covers a round stating none, a round stating one only after its first - collapsed section anywhere else, and a round stating one as a bullet, that last - blocking at exit 43 as an unvetted metadata label. None of them says - the round withheld nothing, and a `?` is a reason to read the body. Present - only where the round covering the head is written in that format, which reached this - repository after every round the vetted marker lists below were measured over. - `M` is read from the API rather than from the review's prose. That format enumerates - the findings it opened threads for, and the anchor each entry links is the database id - of that thread's own comment, so the threads are the same set already structured. - Reading the enumeration instead took six attempts and four of them cancelled a - shortfall by counting something that was not an entry, telling those apart needing a - Markdown parser rather than a line scan. - A total larger than the thread count is findings the round raised that polling threads - cannot see, and a `FINDINGS WITH NO THREAD` block follows naming the shortfall, except - where a count-first open section supplied the total, as stated below, or where open - entries standing for an earlier round's threads account for it, as stated below. Two - things overstate that shortfall rather than hiding it, so it is confirmed against the - body rather than acted on from the number. One is a thread past the hundred - `reviewThreads` reads, which would have counted in `M`, and `threads=` carries the - trailing `+` saying the page was cut. The other is a finding an earlier round raised - that the total still counts and no open entry links, its thread being none this round - opened. An open entry whose title links an earlier round's thread, and which links - none this round opened, is counted beside `M` before the two are compared, since the - total counts what is still open rather than what this round raised. So `T` above `M` - can print no block, and where a block prints it names how many it counted that way. - A withheld finding is owed the triage a suppressed one is. No exit code rides on it, - the same as `suppressed=` and `cr_outside_diff=`, since what an unread finding says is - the reader's to judge. - Where the preamble states no total, the count opening the open-findings section is - `T`, since that format's later revision writes the bare zero line only for a zero. - Each entry an open section lists links its thread, and an entry whose title links no - thread on the pull request is counted in that same block whatever the totals say. So - is each entry an `Open (N)` section counts beyond its linked entries, the bullets at its - margin carrying a link this script reads, outside any block collapsed within it. - Where the open-findings section supplied `T`, the block is measured against the - entries it lists with a link rather than against `M`, so an entry linking an earlier - round's thread is no finding without one, while a finding that section's count names - and no entry links is still counted. Entries are counted rather than links, so a - back-reference beside an entry's own link covers no other entry. - The block also counts each finding a file table row names with a vote count, `(N - votes)`, that pairs with no thread of that round on the row's file. Each thread pairs - with one finding at most, so two findings on a file one thread is on leave one. - It counts a headline spelling out more findings than the round and the reviewer's - earlier threads account for, those threads resolved or not, since a headline counts - across rounds and counts a settled finding as readily as an owed one. - A round can also list its findings in prose under a `Review findings:` label, each - entry naming the files it concerns in code spans, a trailing part of a path or a - directory holding it included. An entry that pairs with no thread of that round, one - thread per entry, is a finding with no thread. Where those entries outnumber the - shortfall above, the block counts them instead. A thread an open entry links counts as - that round's in both pairings, since the entry names a finding the round still holds. - An `Open findings remain:` list is read the same way, except that an entry pairs only - with a thread whose open entry is badged at the severity tier the entry's own bold - word states. An entry naming no file pairs on that tier alone, and an entry or thread - whose tier is not read pairs with nothing. An entry stating `votes each` counts as two. - Ten bodies in that format have been read here, so what follows describes those rather - than the format in general. None carried a `Suppressed comments` heading, which is - why this field rather than `suppressed=` is what finds a withheld finding in one. - None stated its file coverage the first format's way, in either the bulleted spelling - or the bare one, so the `fleet-review` marker the fleet's own carried `fleet-code-review` - instructions ask for is the only coverage statement this format has been seen to make. - Five of the ten carry it, on heads carrying those same instructions, so its absence is - intermittent rather than structural. Both absences measured on one drive were - re-reviews of a delta of one line and of four files, which is why a round stating none - carries an earlier round's statement forward rather than blocking. A re-request is not - the remedy the block named either: four were measured and one produced the marker, so - it clears by chance rather than by asking. - A later body in that format that - does collapse a suppressed section is read by `suppressed=`, that heading being vetted - and read wherever it sits. Whether the shortfall counts those findings a second time - turns on whether the stated total includes them, which no body read here says, so treat - `suppressed=2` beside a shortfall of 2 as either two findings or four until the body - settles it. A body stating coverage as a bare `**Files reviewed:**` line would still go - unread, the reader requiring a bullet where this format states its metadata without - one, which is why `effort=` had to drop that requirement. Ten rounds have stated it - that way none of the time, so this is a gap rather than the reason a round reads as - unstated, and `Files reviewed` sitting in the vetted labels does nothing about it - since the line never reaches that comparison. - Nothing reports either contradiction, the vetted lists reporting an unvetted marker - rather than a marker turning up somewhere new. - Two quotation shapes carry a column-0 `
` past both masks, a multi-line HTML - comment and a raw `
` block, and either ends the preamble and prints `?`. The
-           indented code block is a third, answered by the pattern's own bound rather than a mask.
+           review runs once per change, at the promotion. On a pull request into any other branch
+           the attested local pass covers every head, `review_on_head=local` where no Copilot
+           round covers it.
+           `review_on_head` and `rounds=` name Copilot's own coverage, never "no review of any
+           kind covers this head". `other_reviewed` names a tracked other reviewer that posted on
+           the head, identity and commit only, and its empty body there is its own "reviewed,
+           nothing to flag" shape, not a gap.
+           `other_rate_limited` names one whose newest comment or review is its own rate-limit
+           notice. `refusal=` reads the newest Copilot review where it is a refusal: `QUOTA` for
+           the account quota or an error whose run log names a rate limit, `ERROR` for any other
+           error refusal, `YES` for any other refusal. `status` exits 0 over a refusal, and `wait`
+           gives it 41.
+           `unresolved` counts every open thread whoever opened it, its breakdown attributing the
+           known logins. Both `threads=` and `unresolved=` read one 100-thread page, a trailing
+           `+` and a `THREADS TRUNCATED` block naming a cut page. `suppressed=`,
+           `previously_missed=`, and `cr_outside_diff=N (on_head=X earlier=Y)` count findings
+           collapsed into review bodies over every round, split into the head's and earlier ones,
+           each printed whole since no thread carries it, a trailing `+` marking a cut reviews
+           window. `qodo_open=N` counts Qodo's findings comment entries with no Resolved or Dismissed badge, `unknown`
+           where that comment can sit behind the window. `overview=T/M` is the open findings the
+           round covering the head states beside the threads that round opened, `?` where it
+           states no count, and `FINDINGS WITH NO THREAD` names findings the round names that no
+           thread on the pull request carries. Each of these is owed the triage a suppressed
+           finding gets, and none decides an exit code.
   reply    Answer one thread selected by its text, and resolve it on request. Exists
            because the hand-run form keeps failing the same way: a node id typed into a
            mutation, which resolves globally and so writes to a real thread somewhere
@@ -250,97 +96,34 @@
            thread resolved, 64 = the write scope could not be established or excludes the target.
   wait     Request a review where none is outstanding, then poll until Copilot's review lands on the
            current head, then print the digest. The auto-request is skipped once a review past
-           --min-rounds already covers the head, once Copilot has already answered outside a
-           formal review, or once one is already in the pending request set, so calling `wait`
-           again on the same PR never double-requests. It is also skipped under 46's and 47's quota
-           readings below, since a request into a reached limit spends quota and returns the same
-           refusal. It is skipped too on a pull request into a branch other than the default, whose
-           every head an attested local pass covers. An attested head is covered at once. The wait
-           then polls its checks instead, only while they can still move its merge, as 30 below
-           lists. One with no attestation exits 49 naming the `attest` step.
-           --request asks for a round anyway. The request goes out unasked on a pull request into
-           the default branch. It also goes out where a partial or a review history past the window
-           is on record. The attestation comment also carries the findings count the pass recorded,
-           shown and not gated. `wait` reads the Copilot reviewer's bot id from the repository's own
-           most recently updated PRs rather than a fixed id: the last HISTORY_PRS, widened once to
-           HISTORY_PRS_WIDE where that narrow window carries no Copilot activity at all, since an
-           outage that outlasts HISTORY_PRS PRs would otherwise empty it on every call for as long
-           as the outage runs. Requests nothing (falling back to polling only) where both windows
-           come up empty, since a repository with no Copilot review in either has nothing to read
-           the id from and a fabricated one is never an option. The loop runs in-process, so a
-           45-minute wait costs one agent turn, not 90.
+           --min-rounds covers the head, once Copilot has answered outside a formal review, once
+           one is pending, and under a refusal or quota reading below, since a request into a
+           reached limit spends quota and returns the same refusal. It is skipped on a pull
+           request into a branch other than the default too, whose every head an attested local
+           pass covers: an attested head has its checks polled instead while they can still move
+           its merge, and one with no attestation exits 49. --request asks for a round anyway.
+           The bot id is read from the repository's most recently updated pull requests, the last
+           HISTORY_PRS, widened once to HISTORY_PRS_WIDE, and nothing is requested where neither
+           carries any Copilot activity. The loop runs in-process, so a 45-minute wait costs one
+           agent turn, not 90.
            Exit 0 = review present, or on a held head an attested local pass with its required
-           checks settled as far as the rollup window reads them, with the merge reading CLEAN,
-           UNSTABLE, or HAS_HOOKS, or with the pull request closed, 30 = still pending at timeout
-           (pending is not failure), on a held head a required check still settling, any check while
-           no required one has posted, none posted on a BLOCKED, BEHIND, or DRAFT merge, or the
-           merge still UNKNOWN, printed as `status=CHECKS_PENDING`, or a round requested while the
-           held poll ran, printed as `status=PENDING` unless 40's outside answer or 46's or 47's
-           quota reading outranks it,
-           40 = Copilot answered outside a formal review, so read the printed body.
-           40 reports the shape of that answer and reads nothing of its cause: an answer
-           carrying no commit covers no head, so the wait ends and the reader decides.
-           41 = the review carrying the head says it did not review, so it covers nothing.
-           42, 43, 45, and 50 = the review landed and `status`'s readings apply to it.
-           A wait ending on a round that covered half the diff, or on output nothing here can
-           read, has ended on something other than a review of this pull request, and one ending
-           on a 50 has ended on a review whose finding no count carries. 50 outranks 44, so on a
-           head carrying a 50 a stuck check shows only in the digest. A 42 can
-           be decided by an earlier round whose partial coverage carries to a head stating none,
-           in which case the round the wait ended on is not the round the code came from.
-           44 = the review loop closed, the merge reads BLOCKED, and a required check is in a shape
-           no wait clears: queued with nothing acting on it, expected and never posted, running far
-           past what the job costs, or failed, though on a held head a required check running long
-           is still polled, as 30 states. A check merely still running normally is not this and
-           exits 0, or on a held head is polled while it can still move the merge, which includes
-           a context the base branch's rules require and the head has not yet registered. Neither is a
-           stuck check its rollup node reads as not required, since the rollup carries checks no
-           ruleset requires, nor any stuck check on a merge that is not BLOCKED. Nor is a failed
-           check from an older run whose workflow has a newer run on the head not yet finished.
-           The digest names that one as superseded. The digest reports the check in every case,
-           so a shape outside 44 is still named rather than lost.
-           46 = the newest Copilot review on the pull request, on this head or an earlier one, is a
-           refusal naming the account quota, or one saying only that it encountered an error,
-           printed above under COPILOT REFUSED THIS ROUND. The weekly rate limit posts that error
-           body and writes its cause to the reviewer's own Actions run, so that run's job log is
-           read: a logged rate limit reports as the quota with its reset time, and anything else, an
-           unreadable log included, as a possible quota hit. Either way no request is sent, and a
-           request already pending after a refusal on an earlier head is still polled for. That is
-           an account-level state a re-request or a further wait does not clear, unlike 41's other
-           causes (a file count over the limit, cleared by splitting the pull request), so it is its
-           own code rather than folded into 41: proceed on the other reviewers' coverage instead of
-           retrying.
-           47 = this pull request's current head carries no Copilot activity of its own, and the
-           reviewer's own most recent activity found in the repository, a review or comment on any
-           other pull request, is that same account-quota refusal with nothing having answered it
-           since. A refusal on this pull request itself is 46 instead. The poll that would otherwise
-           have run is skipped for this reason, printed as a `note:` line before the digest, rather
-           than spent finding the same account state out a call late, and no request is sent, while
-           a request already pending is still polled for. Pass --ignore-quota-signal to request and
-           poll --timeout anyway once the quota is believed to have reset. 46 is read from this pull
-           request's own reviews and always takes priority over 47, so a genuine 0/40/41/42/43/45 on
-           this pull request outranks 47 whenever both would otherwise apply, and so does a 50, and
-           on a held head covered by an attested local pass a 30 or a 44. A genuine round the final
-           read shows on the head rules 47 out, and so does any review of this pull request, on any
-           head, submitted after the refusal and not itself a quota refusal, since it answers that
-           refusal as one anywhere in the repository would. A genuine round already on the head when
-           the wait begins leaves the request and the poll to run as usual.
-           A pending request remains pending until a review, an answer, or the timeout. GitHub's
-           effort-labeled review lifecycle does not always emit `copilot_work_started`, so that
-           event is not evidence that distinguishes queued work from abandoned work.
-           48 = the auto-request returned success and recorded nothing on the pull request,
-           neither a pending reviewer nor a review-request event. Observed once, while the
-           requesting account's Copilot allowance was exhausted, where no refusal was posted to
-           read and clearing the set and requesting again changed nothing. It is decided one
-           poll interval after the request, and the rest of the poll is skipped, since no
-           request exists to answer. It ranks under 0/40/41/42/43/44/45/46/50 and above 47.
-           `status` cannot report it, since a request that recorded nothing leaves nothing for a
-           later read to find.
-           49 = no Copilot round covers this head and none was requested. The pull request merges
-           into a branch other than the default and no attestation vouches for the head. Run the
-           local strict review, record it, push, and run `attest`, or pass --request.
-           64 = the write scope could not be established or excludes the target, checked before
-           the auto-request or any poll, so a cross-owner target reads and writes nothing here.
+           checks settled. 30 = still pending at the timeout, a required check still settling on
+           a held head printed as `status=CHECKS_PENDING`, or a round past --min-rounds not yet
+           landed. 40 = no Copilot review covers the head: the reviewer answered outside a formal
+           review, the request returned success and recorded nothing on the pull request, or the
+           reviewer writes under a login no query filters on. 41 = the newest round is a refusal
+           or a quota state, the kind printed in the digest and its status line: a refusal on the
+           head, the pull request's newest review being a quota or error refusal on any head, or
+           the reviewer's newest activity elsewhere in the repository being a quota refusal
+           nothing answered since while this head carries none of its own. Proceed on the other
+           reviewers' coverage rather than retrying, and pass --ignore-quota-signal once the
+           quota is believed to have reset. 42 and 50 = the review landed and `status`'s readings
+           apply to it. 44 = the review loop closed, the merge reads BLOCKED, and a required check
+           is in a shape no wait clears, queued with nothing acting on it, expected and never
+           posted, running far past what the job costs, or failed. 49 = no Copilot round covers
+           this head and none was requested, the pull request merging into a branch other than
+           the default with no attestation vouching for the head. 64 = the write scope could not
+           be established or excludes the target, checked before the auto-request or any poll.
 
 Reading is the bulk of this and the writing commands are a trade rather than a free win. A
 mutation spelled as a `gh` command in a shell is read by the gh-write-guard PreToolUse hook, and
@@ -355,7 +138,6 @@
 import argparse
 import fnmatch
 import functools
-import html
 import io
 import itertools
 import json
@@ -365,103 +147,37 @@
 import sys
 import tarfile
 import time
-import unicodedata
 import urllib.parse
-from collections import Counter
 from collections.abc import Callable, Iterable, Iterator
 from datetime import UTC, datetime
 from pathlib import Path
-from typing import NamedTuple
 
 import gh_graphql as shared
+import pr_review_copilot as adapter
 
-# The directory this script sits in, and the anchor every scope answer is read from.
-# One value serves the owner probe and the refusal naming it, so the two cannot disagree.
+# The directory this script sits in, the anchor every scope answer is read from.
 HERE = Path(__file__).resolve().parent
 
 REVIEWER = "copilot-pull-request-reviewer"
-# Other review bots this repository has trialed alongside Copilot.
-# Tracked at the identity level only, login and commit oid, never body prose, except where a reader below names one explicitly.
-# Each format read here is its own reader, and doing that well is a separate task per bot.
+# Other review bots tracked at the identity level only, login and commit oid, never body prose.
 CODERABBIT_LOGIN = "coderabbitai"
 QODO_LOGIN = "qodo-free-for-open-source-projects"
-# Named rather than inlined at each of their own readers below, so a login rename updates one spelling instead of silently leaving a hardcoded copy matching nothing.
+# Named once so a login rename updates one spelling.
 OTHER_REVIEWERS = (CODERABBIT_LOGIN, QODO_LOGIN)
 KNOWN_REVIEWERS = (REVIEWER, *OTHER_REVIEWERS)
 
 # A check dispatched to a runner and not begun, in the spellings a CheckRun carries.
-# PENDING here means dispatched and not begun, which a StatusContext's means the opposite of.
-# That one is translated away in check_nodes, where the node shape is still known.
-# Reading QUEUED alone scores the rest of these as running.
+# A StatusContext's PENDING means the opposite, so `check_nodes` translates it away.
 NOT_STARTED = frozenset({"QUEUED", "WAITING", "PENDING", "REQUESTED"})
-# A required status nothing has posted, which is a StatusContext's state and only ever that.
-# It is not a starved job and must not borrow that remedy, since no runner is owed it at all.
-# Left out of both sets it reaches the conclusion branch, where it reports as a red check.
+# A required status nothing has posted, only ever a StatusContext's state, and not a starved job.
 NOT_POSTED = frozenset({"EXPECTED"})
-# What counts as a check having passed, rather than as one still deciding or failed.
-# SKIPPED and NEUTRAL are passes, since the fleet aggregator pattern skips the conditional jobs.
-# Treating a skip as unfinished reports four blockers on every green pull request here.
+# SKIPPED and NEUTRAL count as passed, since the fleet aggregator skips conditional jobs.
 CHECK_OK = frozenset({"SUCCESS", "SKIPPED", "NEUTRAL"})
-# How long a queued check is simply a check starting.
-# Observed pickup on a healthy run here is one to two minutes.
-# This is the pickup grace's five minutes for the same reason that one is.
+# How long a queued check is simply starting, the pickup grace's five minutes.
 CHECK_GRACE = 300
-# How long a running check runs before its duration is worth reporting.
-# Generous on purpose, since this repository's lint job legitimately takes eleven minutes.
-# A fleet repository building and testing .NET takes longer still.
-# A threshold that flags those trains the reader to skim the genuinely hung job too.
+# How long a running check runs before its duration is worth reporting, generous so it does not flag a slow job.
 CHECK_STALL = 1800
 
-# A review body can carry a collapsed block of findings withheld from the inline threads.
-# Those appear nowhere in `reviewThreads`, so polling threads alone reports a clean pass.
-# The alternation is the runbook's, since the heading wording has changed once already.
-# Matching one phrasing alone reports zero on a review that has them.
-SUPPRESSED = re.compile(r"Suppressed comments|low confidence", re.IGNORECASE)
-# The second overview format's own section for a finding against code the pull request did not change.
-# Anchored to the opening of its line, past whatever markup a heading wears, rather than matched anywhere in it.
-# The wording is ordinary English, so a body-wide match reads a sentence such as `restores a guard previously missed (2) rounds ago` as this section.
-# `marker_blocks` accepts a line that is not a heading on a `(N)` alone, which is what lets that sentence through.
-# So the anchor is what separates a heading from prose naming one.
-# The opener admits heading markup and anything outside ASCII, and nothing else.
-# One count may follow it, since a later revision opens the heading on its count, as `2 previously missed issues`.
-# A count opening a line is how a sentence opens too, so `marker_blocks` reads such a line as prose unless it is a heading.
-# `OPENING_COUNT` reads that count past this same opener, so whatever markup the anchor admits, the prose check strips.
-# An emoji is what this format already puts on its verdict headings, and a spelling that admitted no such character read a heading wearing one as no section at all.
-# That failure is silent rather than loud, the heading itself being vetted and `normal` dropping the emoji before the comparison, so the digest reports every shape read while the findings reach nobody.
-# Widened to any non-word character instead, ordinary punctuation opened the run and a sentence such as `- Previously missed (2) findings were re-raised` became the section, printing the prose around it as the finding.
-# Punctuation is what prose opens with and markup is what a heading opens with, so the class is the markup rather than the complement of a word.
-# The whitespace is spelled out rather than taken from `\s`, which is Unicode-aware and so overlaps the non-ASCII alternative on every non-ASCII space.
-# Two alternatives able to consume the same character make the run ambiguous, and the parse then doubles per character of it on a line that does not go on to say this, which is a hang rather than a slow read.
-# A body carrying 30 non-breaking spaces in a line took minutes, and every alternative here now opens on a character the others cannot.
-# An emphasis marker is admitted only where no space follows it, which is what tells `**Previously missed (1)**` from the list item `* Previously missed (2) findings`.
-# A bullet is the one prose opener that is also heading markup, and `marker_blocks` accepts a line on a `(N)` alone.
-# So the list item read as the section and printed the prose around it as findings.
-# One character per iteration rather than a run of them, since a repeated group that can split a run of stars more than one way is ambiguous and parses exponentially in it.
-# What this still admits is non-ASCII punctuation, an em dash or a typographic quote opening a sentence, which reads that sentence as the section.
-# It is narrower than the spelling before it, which admitted ASCII punctuation as well, and the remedy for the rest is a class of non-ASCII symbols rather than the whole of non-ASCII.
-HEADING_OPENER = r"(?:]*>|[ \t>#]|[*_](?![ \t])|[^\x00-\x7f])*"
-PREVIOUSLY_MISSED = re.compile(
-    rf"^{HEADING_OPENER}(?:[0-9]+[ \t]+)?Previously missed\b",
-    re.IGNORECASE,
-)
-# CodeRabbit's own equivalent, collapsed into the review body like `SUPPRESSED` rather than raised as an inline comment.
-CR_OUTSIDE_DIFF = re.compile(r"Outside diff range comments", re.IGNORECASE)
-# A refusal declines the round as a formal review carrying the head and no threads.
-# That is the clean pass byte for byte, so every coverage check passes over a round that never ran.
-# The alternation is the runbook's for the same reason the one above is.
-# One phrasing is one rewording away from reading a refusal as a review.
-# The dot covers the apostrophe in the typographic spelling and the ASCII one alike.
-# It also keeps the published filter usable inside single quotes, which neither survives.
-REFUSAL = re.compile(
-    r"wasn.t able to review|was not able to review|unable to review", re.IGNORECASE
-)
-# The account-level cause among the refusal wordings, as opposed to a per-pull-request one like the file count.
-# Read against `refusal_of`'s own return rather than the raw body.
-# That way the exemptions built for that anchor, the opening line and the fenced quotation, protect this reading too instead of needing their own.
-# This script's own corpus and this file both quote the sentence below its overview, same as the refusal wording itself does.
-# Observed once here: "Copilot was unable to review this pull request because the user who requested the review has reached their quota limit."
-QUOTA = re.compile(r"reached (?:their|its|his|her|your|my) quota limit", re.IGNORECASE)
-ERROR_REFUSAL = re.compile(r"encountered an error", re.IGNORECASE)
 COPILOT_RUN_PATH = "dynamic/agents/copilot-pull-request-reviewer"
 RUN_ERROR_TYPE = re.compile(r"errorType: '([a-z_]+)'")
 RUN_RATE_LIMIT = re.compile(
@@ -469,523 +185,15 @@
 )
 ANSI = re.compile(r"\x1b\[[0-9;]*m")
 ISO_STAMP = re.compile(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ")
-# A structural marker rather than prose, so reading it needs no per-bot wording model the way `QUOTA` above needs one for Copilot's free-text refusal.
-# Observed on CodeRabbit, a plain PR comment rather than a formal review: "".
-# The service name is captured rather than assumed.
-# A second bot using the same auto-generated-comment convention is read without a new pattern.
-# Any other shape stays unread unless a pattern of its own, like the reply one below, reads it.
-# That reply's marker names the product rather than the `coderabbit.ai` service, so `RATE_LIMIT_SERVICE` supplies the service by login.
-RATE_LIMITED = re.compile(r"auto-generated comment:\s*rate limited by\s*(\S+?)\s*-->")
-RATE_LIMITED_REPLY = re.compile(
-    r"\s*(?:\s*)*"
-    r"
\s*[^<\n]*Action not completed\s*\s*Review rate limited\." -) -RATE_LIMIT_SERVICE = {CODERABBIT_LOGIN: "coderabbit.ai"} -# Anchored to the `

` tag rather than a bare substring, since prose elsewhere can mention the phrase without being the comment it names. -QODO_REVIEW_HEADING = re.compile(r"

\s*Code Review by Qodo\s*

", re.IGNORECASE) -# Only the numbered heading counts as a finding, told apart from Qodo's own nested sub-summaries by starting with a number and a period (`1.`, `2.`, ...). -QODO_FINDING = re.compile(r"\s*\d+\.\s") -# A finding's own title can quote `Resolved`/`Dismissed` without carrying the badge, so the glyph is required rather than just the word. -# Escaped (U+2713, U+2717) rather than typed literally, per the repository's ASCII charset rule. -QODO_BADGE = re.compile(r"[^<]*(?:\u2713 Resolved|\u2717 Dismissed)[^<]*") -# A round states how much of the diff it read on a line of its own. -# A round that read part of it is the clean pass elsewhere, same commit and threads and digest. -# Five such rounds landed across three merged pull requests here. -# One of them read 2 of 3 changed files across both its rounds and merged. -# This is the third instance of the shape the two patterns above answer. -# It is also the only one nothing was reading. -# The line is anchored at its start rather than matched body-wide, both spellings being structural. -# Over 333 review bodies every coverage statement opens its line and not one sits mid-sentence. -# 272 of them open with the reviewer's own name and 32 are the `Review details` bullet. -# A body-wide match reports the pull request adding this check as a partial round. -# That is the false positive the suppressed matcher and the refusal matcher have each had once. -# The cost of the anchor is named rather than hidden. -# A wording that moves the statement off the line start reads as no statement at all. -# Two openers rather than one alternation, because the text each needs beside it differs. -# The bullet's own label is the marker, so it is a coverage line whatever follows the counts. -# Requiring the trailing words there made a bullet that drops them read as no statement at all. -# The sentence opener is the reviewer's name, which prose also opens a line with. -# That one keeps the text requirement, since the name alone does not say the line states coverage. -COVERAGE_BULLET = re.compile(r"\s*[-*]\s*\*\*Files reviewed:", re.IGNORECASE) -COVERAGE_SENTENCE = re.compile(r"\s*Copilot\b", re.IGNORECASE) -# A blockquote marker (`>` per line, Markdown's own quoting convention) sits in front of every line CodeRabbit wraps its outside-diff section in. -# `HEADING`'s `\s*` does not match `>`, so a heading under one reads as prose without this stripped first. -# Read by two callers for opposite purposes, which is why it is defined here rather than beside either. -# `marker_blocks` strips it to find a heading underneath, and `coverage_statements` refuses the line outright. -# A quoted marker is a quotation whichever convention quotes it, and the coverage reader has no use for what a blockquote carries. -BLOCKQUOTE = re.compile(r"^>+\s?") -# The severity the second overview format now renders as a theme-switched `picture` element. -# Its only textual carrier is the `img` `alt`, every other part being a URL that changes with the icon set. -# The set is versioned in those URLs and has already been bumped once, so matching them would pin this reader to one revision. -# Reduced to the `alt` text rather than dropped, since the severity is the half of a finding entry worth reading. -# Either quoting is read, both being valid HTML and the attribute's own spelling being exactly the kind of presentation this reader exists not to depend on. -# Read in one only, a change of quoting leaves the badge unreduced, which prints two icon URLs per finding and can report the entry as a shape nothing here knows. -# Neither gap may cross a `picture` tag, or one match spans from the first element to a later element's `img`. -# An entry whose own `img` carries no `alt`, which the icon set drifting is exactly how to get, then pairs with the next entry's. -# Everything between, that entry's title and its whole finding text, is replaced by the later severity and lost from the only place these findings appear. -# Bounded, such an entry keeps its markup and reads as an unrecognized shape, which is the failure that reports itself. -SEVERITY_BADGE = re.compile( - r"]*>(?:(?!]*\salt=(?:\"([^\"]*)\"|'([^']*)')[^>]*>" - r"(?:(?!", - re.DOTALL | re.IGNORECASE, -) -# What is left of a finding entry's own heading once the badge above is reduced to its text. -# A finding entry cannot be vetted the way a section heading is, its title being different on every finding. -# The badge is therefore what identifies the shape, and the title after it is free text by design. -# The severity alone does not separate the two, a section being free to name one in its own heading. -# Every vetted section heading here states its count and a finding's title states none, so the absence of one is the other half of the test. -# Without it a section this has no reader for is vetted on its first word, which turns a shape that reports itself into one that is silently passed over. -SEVERITY_TEXT = re.compile(r"(critical|high|medium|low)\s+severity\b", re.IGNORECASE) -# The count as `normal` leaves it rather than as the heading wrote it. -# `normal` rewrites every `(\d+)` to `(N)` before a marker is ever compared, so a reader keyed on the digits finds none and reads every section heading as carrying no count. -NORMALIZED_COUNT = re.compile(r"\((?:\d+|N)\)") -# Ask the reviewer for a stable coverage shape instead of adapting only to changing prose. -# Keep the prose readers for reviews made before the marker shipped. -# Searched within its line rather than matched as the whole of one, because the reviewer writes it both ways. -# It carries no whitespace of its own at either end, which a search has no use for and pays for: an unanchored run of `\s*` is quadratic in the whitespace run it sits in. -# Left in place from the spelling that matched a whole line, a line of 16000 spaces took half a second and 65000 took nine, where the marker itself is what a search is looking for. -# The instruction it is emitted from asks only that the body end with it, and one of the two overview formats ends a prose sentence with it instead. -# Anchored to the whole line, that format read as a round stating no coverage at all, over a body carrying the counts in plain sight. -# The anchor was never what made the marker trustworthy: an HTML comment renders invisibly, so a body that wants one seen has to quote it, and a quotation is refused before this is ever consulted. -# The digit runs are matched unbounded and judged in `read_coverage` rather than bounded here, which is the difference between a line this cannot believe and a line that is not a statement at all. -# Bounded here, a marker stating a count longer than any review states stopped matching, so the line left the gate silently and a round carrying one read as full on whatever else it said. -# `int` also raises on a run past 4300 digits, so the judgment has to happen somewhere, and the place that can answer `unvetted` is the reader rather than the pattern. -FLEET_REVIEW = re.compile( - r"", - re.IGNORECASE, -) -# The count pair itself, in the two spellings the corpus carries. -# The comment tail one of them ends on is deliberately not part of the unit. -# It says how many comments the round raised, which is not coverage. -# A fifth wording of it would fail every merge over a sentence ending read correctly. -# The plural is optional, since a one-file round reading `1 changed file` means what it says. -# Blocking on that is the cry-wolf case, a fleet-wide stop over a grammatical agreement. -# The bullet's trailing words are optional for the reason its label alone identifies the line. -# Detection and parsing disagreeing there turned a readable `4/4` into a block on a readable line. -# What is left blocking is a bullet carrying no counts, which genuinely states no coverage. -COVERAGE_COUNTS = re.compile( - r"reviewed\s+(\d+)\s+out of\s+(\d+)\s+changed files?" - r"|\*\*Files reviewed:\*\*\s*(\d+)\s*/\s*(\d+)(?:\s+changed files?)?", - re.IGNORECASE, -) -LOOSE_COUNTS = re.compile(r"reviewed\D{0,40}?(\d+)\s*(?:out of|of|/)\s*(\d+)", re.IGNORECASE) -EMPHASIS_MARK = re.compile(r"[*_`]") - - -HTML_SPACE = r"[ \t\n\f\r]" -# A block start ends a tag's name on cmark's whitespace, which a vertical tab joins. -BLOCK_SPACE = r"[ \t\n\v\f\r]" - - -def attributes(spanning: bool = False, lone_space: bool = True) -> str: - """The pattern for a tag's attributes after its name, through the `>` that closes it. - - A quoted value may hold a `>`. Anything else that is not an attribute ends the tag unread, so - an opener quoted as `
]*>` is not one. A `spanning` reader takes a line break where - HTML does, between attributes and inside a quoted value, and any other reads one line. - - Without `lone_space`, whitespace must lead to an attribute, and its name to a letter. That is - how a reader refuses the `` or `` a code span masked to a space leaves, - and it refuses `` with them. Any other reader takes a name as CommonMark does. - - One tail serves every reader here of a tag's attributes, and it stays lenient. A tail kept per - site was fixed at one and not at its siblings. `TAG_ATTRIBUTE` is CommonMark's stricter grammar - for any inline tag, which is what decides whether a backtick inside one opens a span. - """ - space, quoted = (HTML_SPACE, "") if spanning else (r"[ \t\f]", r"\n") - value = rf"\"[^\"{quoted}]*\"|'[^'{quoted}]*'|[^\s\"'<>]+" - lead = "[A-Za-z_:]" if lone_space else "[A-Za-z]" - attribute = rf"{space}+{lead}[\w.:-]*(?:{space}*={space}*(?:{value}))?" - if lone_space: - return rf"(?:{attribute})*{space}*/?>" - return rf"(?:(?:{attribute})+{space}*)?/?>" - - -ATTRIBUTES = attributes() -HTML_TAG = re.compile(rf"\n]*)?/?>") -BARE_TAG = re.compile(r"<(?!!--)[^<>]*>") -MARKER_REACH = 300 -FILE_ROW = re.compile( - r"^(?![^\n]*)" - rf"|<\?{IN_PARAGRAPH}*?\?>" - rf"|\n]|{PARAGRAPH_BREAK})*>" - rf"|" - r"|<[A-Za-z][A-Za-z0-9+.-]{1,31}:[^\x00-\x20<>]*>" - r"|<[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?" - r"(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*>)" -) - - -class CodeSpans: - """The inline code spans in a body, read the way GitHub reads them, left to right. - - A code span, raw inline HTML, and an autolink bind by which one opens first. A backtick inside - an HTML comment, a tag's quoted value, or an autolink that opened earlier is literal, so it - opens no span. Read alone, that backtick paired with a later one, and a live tag between the two - read as quoted. - - So one pattern reads all three, each match consuming its own text, and only a span is - reported. A span carries its backtick run as group 1, which is what tells it from the rest. - - Some readings differ from GitHub's and stay known limits that tests pin, since no reviewer - body has carried any of them. A paragraph's end is read from its line alone. So a span here - can pair across a line ending a list item's or a quotation's paragraph on GitHub. It pairs - across a top-level setext underline too. A backtick run after an even run of backslashes opens a - span on GitHub and none here. One inside an inline link's destination or title opens none on - GitHub and pairs here. - """ - - def __init__(self) -> None: - self.pattern = re.compile( - rf"(? Iterator[re.Match[str]]: - """Every span in `text`, in order.""" - return (m for m in self.pattern.finditer(text) if m.group(1) is not None) - - def search(self, text: str) -> re.Match[str] | None: - """The first span in `text`, or None.""" - return next(self.finditer(text), None) - - def sub(self, repl: str | Callable[[re.Match[str]], str], text: str) -> str: - """`text` with each span replaced by `repl`, and the HTML and autolinks left as they are.""" - - def one(m: re.Match[str]) -> str: - if m.group(1) is None: - return m.group() - return repl if isinstance(repl, str) else repl(m) - - return self.pattern.sub(one, text) - - -# An inline code span is a quotation for the same reason a fenced block is. -# A reviewer naming `` in prose was read as opening one. -# Bounded to a paragraph, and an escaped tick opens nothing, since either masks a section. -# Only the opener takes that guard, a backslash being literal inside a span rather than an escape. -# Replaced by a space, since deleting joins the sides into a tag the body never carried. -CODE_SPAN = CodeSpans() - - -# The round's own file summary table, whose first column is a path and whose second is prose. -# The header row is the marker rather than the `
` around it. -# One measured round carries the table with no ``, and two summary spellings wrap it. -# Over the same 348 bodies, 91 carry a table and every table row in the corpus belongs to one. -# A row outside this shape is a shape nothing has seen rather than a table read wrongly. -TABLE_HEADER = re.compile(r"\s*\|\s*File\s*\|", re.IGNORECASE) -# The alignment row under the header, which is punctuation rather than a file. -TABLE_RULE = re.compile(r"\s*\|[\s:|-]+\|\s*$") -TABLE_ROW = re.compile(r"\s*\|([^|]*)\|") -TABLE_GLOB = frozenset("*?") -TABLE_GAP = " ... " -TABLE_SPAN = re.compile(r"`([^`]+)`") -TABLE_SEPARATORS = re.compile(r"[\s,]*") -# The readings a round's coverage carries, worst first. -# A head carries more than one round only through a re-request. -# Where two disagree, the one naming files it did not read is the one to answer. -# `UNSTATED` sits last rather than beside the failures, being the absence of a statement. -# A round that did state full coverage settles the question over one that stated nothing. -UNVETTED, PARTIAL, FULL, UNSTATED = "unvetted", "partial", "full", "unstated" -# Not a state a round reports, but the reading that carries an earlier round's forward. -CARRIED = "carried" -TABLE = "table" -LOCAL = "local" -NO_HEAD_TABLE = "no round covering the head carries a file table of its own" -SEVERITY = (UNVETTED, PARTIAL, FULL, UNSTATED) -# Upper-case for the two that block a merge, for the reason `review_on_head=NO` is upper-case. -# `unstated` rather than `unknown`, since a body carrying no count is a shape this knows. -# What this script does not know is the separate `shapes` field, and one word for both hides it. -# The constant carries that name too, so no reader has to map a name here onto another word. -COVERAGE_FIELD = { - UNVETTED: "UNVETTED", - PARTIAL: "PARTIAL", - FULL: "full", - UNSTATED: "unstated", - TABLE: "table", - LOCAL: "local", -} - -# Every structural marker the reviewer's own bodies carry, measured over the same 333. -# A body is read for these rather than trusted, because every reader below keys on one of them. -# A heading this script has no spelling for is a section it will not find, reported as absent. -# That is the shape of all three failures already on record here, each caught after it landed. -# Two overview formats are carried rather than one, the second arriving after that measurement. -# Its own markers are listed beside the first's, since a round in either format can land next. -# Counts are normalized to `(N)` and non-ASCII is dropped before comparing, and `unvetted` folds letter case at the comparison itself. -# The verdict headings carry a colored circle, so the emoji is what would drift most cheaply. -# Dropping it also keeps this file inside the charset rule that governs the repository. -CLEAN_VERDICTS = {"### Approval recommended", "### Ready to approve"} -FLAGGING_VERDICTS = { - "### Changes recommended", - "### Needs a closer look", - "### Not ready to approve", - "### Human review recommended", -} -VETTED_HEADINGS = ( - { - "## Pull request overview", - "## Copilot review overview", - "### Reviewed changes", - "### Suppressed comments (N)", - } - | CLEAN_VERDICTS - | FLAGGING_VERDICTS -) -NARRATIVE_SUMMARY = "What changed in this PR" -TOTAL, OPEN, RESOLVED = "total", "open", "resolved" -OVERVIEW_SECTIONS = { - "Open (N)": OPEN, - "(N) open findings": TOTAL, - "(N) open finding": TOTAL, - "(N) open issues": TOTAL, - "(N) open issue": TOTAL, - "Resolved since last review (N)": RESOLVED, - "(N) resolved since last review": RESOLVED, -} -PREVIOUSLY_MISSED_SUMMARIES = { - "Previously missed (N)", - "(N) previously missed issues", - "(N) previously missed issue", -} -SUPPRESSED_SUMMARIES = {"Suppressed comments (N)", "Comments suppressed due to low confidence (N)"} -VETTED_SUMMARIES = ( - set(OVERVIEW_SECTIONS) - | { - "Pull request overview", - NARRATIVE_SUMMARY, - "Show a summary per file", - "File summaries", - "Review details", - } - | SUPPRESSED_SUMMARIES - | PREVIOUSLY_MISSED_SUMMARIES -) -VETTED_LABELS = {"Files reviewed", "Comments generated", "Review effort level", "Review effort"} -# Inline emphasis around a marker is presentation rather than identity. -# The second overview format wraps every `` in `` where the first wrapped none. -# Vetting the tags along with the text blocks on markup changing under a section that has not. -# That is the same cheap drift the verdict headings already drop their colored circle for. -EMPHASIS = re.compile(r"", re.IGNORECASE) -MARKDOWN_HEADING = re.compile(rf"\s*{ATX_HEADING}") -# The `Review details` metadata bullets, of which the coverage line is one. -# The bullet stays required, so the second format's bare bold metadata lines are not read here. -# Dropping it reads that format's own `**Changes:**` prose label as metadata and blocks on it. -# Each bare line that carries a reading has its own pattern below instead. -LABEL_LINE = re.compile(r"\s*[-*]\s+\*\*([^*]+):\*\*") -# Two spellings, one per overview format. -# The first states it as a `Review details` bullet. -# The second has no `Review details` section and states it as a bare bold line. -# Reading the first alone printed `effort=unknown` over a body stating the level outright. -# A later revision opens the second on an emoji, a non-ASCII run excluding whitespace so `\s*` cannot overlap it. -EFFORT_LINE = re.compile( - r"\s*(?:[-*]\s+)?(?:[^\x00-\x7f\s]+\s*)?\*\*Review effort(?: level)?:\*\*\s*" - r"(?:(Default)\s*\(\s*(Lite|Balanced|Max)\s*\)|(Lite|Balanced|Max))\s*$", - re.IGNORECASE, -) -# The second overview format states its own version in the marker its body opens with. -# Keyed on that marker rather than on the heading wording, a version being what it states. -# Anchored to a line of its own, since the marker is an HTML comment and renders invisibly. -# A body naming it mid-sentence is a body about the format rather than one written in it. -# A writer who wants it seen at all has to quote it, which is why a code span is masked first. -# Bounded to three spaces of indent, which is the rule `FENCE` reads a fence by. -# A fourth makes the line a code block, and so a quotation the fence guard never sees. -CCR_OVERVIEW = re.compile(r"^ {0,3}\s*$", re.MULTILINE) -# That format's own finding total, which the first format states nowhere. -# Line-anchored for the reason a coverage line is, prose being able to carry the words mid-line. -# Bounded to three spaces for the reason the marker above is, a fourth making it a code block. -# The largest total wins, so a quoted number otherwise beat the round's own. -# `None` is a total of zero spelled in words, which a round raising nothing states. -# Read as no total at all it printed `?`, and this file's own rule is that the two differ. -# The rest of the line is taken whole rather than its first number. -# The format states a count per severity, so a round stating `2 . 3 ` raised five. -CCR_FINDINGS = re.compile(r"^ {0,3}\*\*Findings:\*\*(.*)$", re.MULTILINE) -CCR_OPEN_FINDINGS = re.compile( - r"^ {0,3}\*\*(\d+|No) open (?:findings?|issues?)\*\*[ \t]*(?:[^\x00-\x7f\s]+[ \t]*)?\r?$", - re.MULTILINE | re.IGNORECASE, -) -# The markup the format writes a count beside, replaced by one sentinel before a count is read. -# Masked rather than matched around, because a badge carries digits of its own in its attributes. -# `2 ` read `18` as a severity count on that reasoning. -# Dropping the markup outright would join the digits either side of it into one number instead. -# The tag alternative is bounded by `[^<>]`, so it cannot span from one tag into another. -# An unmatched `<` earlier in the line otherwise paired with a later tag's closing `>`. -# Every count between the two was swallowed with it. -# It opens on a name character for the same reason, a `<` followed by a space being prose. -# The link alternative tolerates one level of nested parentheses and brackets, a URL carrying a -# `)` of its own having otherwise ended the match early and left its anchor id on the line. -# A reference-style link is its own alternative, its label being a number as often as a word. -COUNT_MARKUP = re.compile( - r"]*>" - r"|!?\[[^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*\]\([^()]*(?:\([^()]*\)[^()]*)*\)" - r"|!?\[[^\[\]]*\]\[[^\[\]]*\]" -) -# What opens a block of its own, and so ends a blockquote rather than continuing it. -# Markdown's lazy continuation carries paragraph text only, which of the three coverage spellings is the reviewer's own sentence alone. -# The bullet spelling and the marker each open a block, so each is the round's own line again however the lines above it are quoted. -# Read as continuations they reported `unstated` over a round stating full coverage, which blocks a merge on a satisfied item. -# A setext underline is not one, since it cannot underline a lazy line and so continues the quotation as text. -# The caller also holds the four-space bound, an indented line being a code block, which cannot interrupt a paragraph and so cannot end a quotation either. -STARTS_BLOCK = re.compile(INTERRUPTS_PARAGRAPH) -# A control character, so no body can carry one of its own and be read as having a count here. -MARKUP_MASK = "\x00" -# Every integer the markup did not swallow, which is how this format states each severity. -# Bounded to four digits, because a review states tens of findings and never thousands. -# A longer run is an identifier, so the mask is not the only thing saying an anchor id is not one. -# That bound is also what keeps `int` from being handed a digit run long enough to raise. -# A digit touching a `.` is part of a decimal, so `confidence < 0.5` contributes no count. -COUNT_LOOSE = re.compile(r"(?` otherwise never ends the preamble and a section's own total becomes the round's. -# Anchored to a line for the reason the marker and the total above are. -# Bounded as `DETAILS_TAG`'s opener is, so `
` ends the preamble and `` does not. -# Matched anywhere instead, a round naming `
` in its overview prose ended the preamble. -# That threw its stated total away, printing `?` and no shortfall over a round withholding findings. -DETAILS_OPEN = re.compile(rf"^ {{0,3}}{tag_opener('details')}", re.IGNORECASE | re.MULTILINE) -# A login that reads as this reviewer without being the spelling every query here filters on. -# A rename leaves every filter matching nothing, so a review that landed reads as none at all. -# A wait then polls out its whole timeout against a review sitting in plain sight. -# `copilot-swe-agent` is the coding agent rather than the reviewer, and does not match this. +# A login that reads as this reviewer without being the spelling every query filters on. +# `copilot-swe-agent` is the coding agent and does not match. READS_AS_REVIEWER = re.compile(r"copilot.*review", re.IGNORECASE) -# The repository this script is hosted in, named because an unrecognized shape is fixed here. -# It is a literal rather than the pull request's own repository. -# That one is where the shape was seen, not where the reader failing on it lives. +# The repository this script is hosted in, where an unrecognized shape is fixed, not where it was seen. HUB = "ptr727/ProjectTemplate" -# The opening tag takes an attribute, as `DETAILS_TAG` already allows on its own pair. -# This reader was the one exception, and the observed format does emit `
`, so a -# `` read as no summary at all missed a section while reporting no shape. -# An attribute name opens on a letter, which is what tells one from whitespace alone. -# Masking a code span inside `` otherwise fuses a `` the body never had. -SUMMARY = re.compile( - rf"{tag_opener('summary')}{attributes(spanning=True, lone_space=False)}(.*?)", - re.DOTALL | re.IGNORECASE, -) -TAGS = re.compile( - rf"|{tag_opener('details', 'summary')}{ATTRIBUTES}", re.IGNORECASE -) -COUNT = re.compile(r"\((\d+)\)") -# A count opening a line past any opener `PREVIOUSLY_MISSED` admits, which is how `marker_blocks` tells prose. -OPENING_COUNT = re.compile(rf"{HEADING_OPENER}[0-9]+[ \t]") -LEADING_COUNT = re.compile(r"^([#*_ ]*)([0-9]+)(?= )") -# What makes a line a heading rather than prose mentioning the phrase, in either markup. -# A line that is neither still qualifies where it carries a `(N)` and does not open on a count. -# The section has appeared as a bare line too, and a closing `(N)` is what prose does not carry. -# A count opening the line is not that signal, since a sentence opens on one as readily as a heading does. -DETAILS_OPENER = re.compile(rf"{tag_opener('details')}{ATTRIBUTES}[ \t]*", re.IGNORECASE) -SUMMARY_OPENER = re.compile(tag_opener("summary"), re.IGNORECASE) -HEADING = re.compile( - rf"\s*(?:{ATX_HEADING}|(?:{DETAILS_OPENER.pattern})?{SUMMARY_OPENER.pattern})", re.IGNORECASE -) -# How many of the newest reviews and comments both queries read. -# A narrow window drops the reviewer's answer behind ordinary discussion, reporting no answer. -# A test holds this equal to the number the queries carry, since a drift between them reads clean. +# How many of the newest reviews and comments both queries read, held equal to the queries by a test. WINDOW = 100 FILES_WINDOW = 100 @@ -997,40 +205,26 @@ def one(m: re.Match[str]) -> str: ATTEST_HEAD_DELAYS = (3, 5, 10, 15, 15, 12) _attest_sleep = time.sleep # What a git ref may not hold before it is interpolated into a REST path. -# Refused rather than allow-listed, git permitting more than a branch name usually carries. -# An allow-list of the usual ASCII refused `release/1.0+build` and any non-ASCII name alike. -# Each of those is a ref git accepts, and refusing one refuses the carry on every pull request. -# What is refused instead is the set that changes the path rather than traveling along it. -# `#` truncates the path at a fragment, `?` at a query, and `%` opens an escape. -# A space and a control character are not path characters at all. +# Refused rather than allow-listed, since git permits more than a branch name usually carries. +# The set refused is what changes the path: `#`, `?`, `%`, whitespace, and control characters. UNSAFE_REF = re.compile(r"[\s#?%]|[\x00-\x1f\x7f]") -# A dot segment travels up the path and reaches another repository, which no ref shape excuses. -# Git forbids `..` in a ref name, so this refuses a value that never came from a ref at all. +# A dot segment travels up the path and reaches another repository. DOT_SEGMENT = re.compile(r"(?:^|/)\.\.(?:/|$)") -# How many rollup contexts the full query asks for, which is not the window above. -# The query is built from this and the truncation line quotes it, so the two cannot drift. -# Naming it beside a hard-coded literal only documented the literal, which a case then held. -# A case is not the guarantee though, since it holds only where someone runs it. +# How many rollup contexts the full query asks for, built into the query so the two cannot drift. CHECKS_WINDOW = 100 -# How many of the repository's own pull requests, and how much of each one's own reviewer history within them, the repo-wide history read looks across. -# Smaller than WINDOW on purpose, since this is a best-effort signal rather than the certainty WINDOW's own two queries are read for. -# Neither carries a `hasPreviousPage` guard for that same reason. -# A caller finding the signal wrong once quota has plainly reset already has --ignore-quota-signal for it, which is a cheaper remedy than paginating this window out. +# How many pull requests, and how much reviewer history within each, the repo-wide history read covers. +# Smaller than WINDOW and without a `hasPreviousPage` guard, since this is a best-effort signal. HISTORY_PRS = 20 HISTORY_REVIEWS = 20 HISTORY_COMMENTS = 5 -# The one-time widened retry `copilot_history` reaches for where HISTORY_PRS carries no Copilot activity at all, rather than reverting every caller to blind polling for the rest of an outage that outlasts it. -# GitHub's own connection ceiling for a single `first`, the same reason FILES_WINDOW and CHECKS_WINDOW hold it. -# Reaching further back needs cursor pagination, which this best-effort signal is not worth paying for, so one wider try is where this stops. +# The one-time widened retry `copilot_history` makes where HISTORY_PRS carries no Copilot activity. +# GitHub's connection ceiling for a single `first`, so further reach would need pagination. HISTORY_PRS_WIDE = 100 -# Liveness query: timestamps and ids only, no comment or review bodies. -# A liveness check does not need the finding text, and re-fetching bodies was 76% of polls. -# It does need the reviewer's non-review answers. -# A wait reading formal reviews alone treats a refusal as an unmet condition. +# Liveness query: timestamps and ids only, no bodies, plus the reviewer's non-review answers. Q_LIVE = """ query($o:String!,$r:String!,$n:Int!){ repository(owner:$o,name:$r){ pullRequest(number:$n){ @@ -1041,16 +235,10 @@ def one(m: re.Match[str]) -> str: }}} """ -# The reviewer's own review and comment history, read live from the repository's own pull requests rather than hand-typed or cached across runs. -# Two callers share this one query. -# The bot's node id belongs to the reviewer account rather than to any one PR or review, so it is identical wherever it is found and recency does not matter once one is found. -# A repo-wide reading of the reviewer's own most recent activity is the other caller, and recency is the whole point there, so `submittedAt`, `createdAt`, and `body` ride along for a reader that does not stop at the first bot id. -# Ordered by `UPDATED_AT` rather than `CREATED_AT`, since a fresh review round bumps a pull request's own update time regardless of how long ago it was opened, where creation order can leave a re-reviewed older pull request outside the window entirely. -# `reviews(last:$reviews)` reads the newest rounds a pull request carries rather than the oldest, and `comments(last:$comments)` catches a plain answer that supersedes a formal review without needing every comment a busy pull request holds. -# `$prs` is a variable rather than baked into the document, unlike the other windows in this file, because `copilot_history` runs this same query twice on an empty narrow read, once at HISTORY_PRS and, only then, once at HISTORY_PRS_WIDE. -# One document read at two widths costs nothing a second document would not, and it keeps the two reads provably identical apart from that one number. -# `pullRequests` names no `states` argument, because the connection's omitted default is every state rather than `OPEN`. -# Merged pull requests therefore fill the window alongside open ones. +# The reviewer's own review and comment history, read live from the repository's pull requests. +# Two callers share it: the bot id lookup, and the repo-wide recency reading that needs the timestamps. +# Ordered by `UPDATED_AT` so a re-reviewed older pull request stays inside the window. +# `$prs` is a variable so one document serves both widths, and no `states` argument means merged pull requests count. Q_BOT_ID = """ query($o:String!,$r:String!,$prs:Int!,$reviews:Int!,$comments:Int!){ repository(owner:$o,name:$r){ @@ -1075,9 +263,7 @@ def one(m: re.Match[str]) -> str: requestReviews(input:{pullRequestId:$pr, botIds:[$bot], union:true}){ pullRequest{ id __REQUEST_STATE__ } }} """.replace("__REQUEST_STATE__", REQUEST_STATE) -# The rollup rides this query rather than a REST call, so reading the checks costs no round-trip. -# It is asked of the last commit because a rollup hangs off a commit object. -# A case holds that commit equal to `headRefOid`, since a rollup a push ago still renders whole. +# The rollup rides this query and hangs off the last commit, which a case holds equal to `headRefOid`. HELD_FIELDS = """ headRefOid baseRefName state mergeable mergeStateStatus baseRepository{ defaultBranchRef{ name } } @@ -1113,11 +299,9 @@ def one(m: re.Match[str]) -> str: }}} """.replace("__FILES_WINDOW__", str(FILES_WINDOW)) # Substituted rather than interpolated, because GraphQL is braces from end to end. -# An f-string would need every one of them doubled, which is unreadable against the schema. # The description and the branch it describes, read together so neither is stale against the other. -# No review or comment connection here, since a description is neither. Q_CLAIMS = """ query($o:String!,$r:String!,$n:Int!){ repository(owner:$o,name:$r){ pullRequest(number:$n){ headRefOid body }}} @@ -1126,16 +310,8 @@ def one(m: re.Match[str]) -> str: # A `uses:` reference quoted in a description, in the spelling a workflow writes it. BODY_USES = re.compile(r'uses:\s*(?P[A-Za-z0-9_.\-]+/[^\s`"\']+@[^\s`"\']+)') # A commit the description claims this branch carries, being a verb plus a SHA rather than a SHA. -# The free scan was built first and the corpus rejected it outright. -# Over 25 merged pull requests it raised four findings and every one was correct prose. -# Those were a develop commit named as history, a SHA in quoted output, and two in another repo. -# Nothing in the shape of a bare SHA separates one of those from a genuine claim. -# Separating them by meaning is the similarity heuristic `spec/section-model.md` rejects. -# A path arm measured on the same corpus did worse, flagging 54 of 215 backticked candidates, mostly bare basenames and other repos. -# The verb is what makes a SHA a claim about this branch rather than a mention of one. -# This alternation raises exactly one reference over the same 25, and that one is true. -# The vocabulary is an inclusion list, so a phrasing nobody thought of costs a detection. -# Being incomplete in that direction is the safe one, since it never invents a finding. +# A bare SHA scan flagged only correct prose, so the verb is what makes it a claim about this branch. +# The vocabulary is an inclusion list, so a phrasing it misses costs a detection and never invents a finding. BODY_CLAIM = re.compile( r"\b(?:fixed|landed|shipped|added|introduced|corrected|resolved|carried|amended)" r"\s+(?:in|by|as)\s+`?(?P[0-9a-f]{7,40})`?", @@ -1144,19 +320,14 @@ def one(m: re.Match[str]) -> str: # What `gh` prints when GitHub answered, as opposed to when nothing was reached at all. HTTP_STATUS = re.compile(r"\(HTTP (\d{3})\)") # The two GitHub returns for an object that is not there. -# A network error carries no status, and 401 and 403 are credentials and a rate limit. -# Reading one of those as absence reports a correct description as stale. -# Everything outside this set is therefore "not read" rather than "not there". +# Everything outside this set is "not read" rather than "not there". ABSENT = {"404", "422"} # What a reference reads as where GitHub never answered for it. UNREAD = "unread" -# Longer than the ordinary read's, since this one downloads a repository rather than a field. +# Longer than the ordinary read's, since this one downloads a repository. TARBALL_TIMEOUT = 120 -# Threads for the reply path, paginated. -# A first page read as the whole set reports no match on a thread that is simply further along. -# `line` is read for the confirmation line rather than for matching, since a push moves it. -# That is how a reply keyed on a line number went to a thread that had shifted underneath it. +# Threads for the reply path, paginated, with `line` read for the confirmation line and not for matching. Q_THREADS = """ query($o:String!,$r:String!,$n:Int!,$after:String){ repository(owner:$o,name:$r){ pullRequest(number:$n){ @@ -1188,8 +359,7 @@ def one(m: re.Match[str]) -> str: LOCAL_REVIEW = Path(__file__).resolve().parent / "local_review.py" # The conversation-comment and thread mutations the runbook publishes. -# `url` is fetched because it is the one field that confirms a comment or reply carried a body. -# A reply that posted empty still returns a comment, and three did, each then resolved. +# `url` is fetched because it confirms the comment or reply carried a body. M_COMMENT = """ mutation($subjectId:ID!,$body:String!){ addComment(input:{subjectId:$subjectId, body:$body}){ @@ -1212,11 +382,8 @@ def one(m: re.Match[str]) -> str: def gh_graphql(query: str, **variables) -> dict: """Run one GraphQL document and return its `data`, ending the run on a failed read. - The transport is `gh_graphql.request`, which raises `GraphQLError` and never exits. This is - the exit contract of this script, where a failed read prints what the transport had to show - and ends the run with the transport's one-line message, at exit 1. - - Only an error set made of `workflowRun` paths is tolerated. + The transport raises `GraphQLError` and never exits, so a failed read prints its detail and + ends the run at exit 1. Only an error set made of `workflowRun` paths is tolerated. """ try: response = shared.request(query, variables, tolerate=_is_workflow_run_error) @@ -1231,11 +398,7 @@ def gh_graphql(query: str, **variables) -> dict: def _is_workflow_run_error(error: object) -> bool: - """True where the error is a per-field failure on `workflowRun` and nothing else. - - A token without Actions read access can fail that one field, and the field is null in `data`. - `check_nodes` then keys Actions runs by suite instead, so the digest still reads. - """ + """True where the error is a per-field failure on `workflowRun` and nothing else.""" path = error.get("path") if isinstance(error, dict) else None return isinstance(path, list) and bool(path) and path[-1] == "workflowRun" @@ -1251,10 +414,7 @@ def gql(query: str, owner: str, repo: str, num: int) -> dict: def follow( query: str, owner: str, repo: str, num: int, connection: str, after: str | None = None ) -> Iterator[dict]: - """Each page of the pull request's `connection`, from the one past `after` to the last. - - One cursor walk for every paged read, so a fix to how a page is followed lands once. - """ + """Each page of the pull request's `connection`, from the one past `after` to the last.""" def fetch(cursor: str | None) -> dict: extra: dict[str, str] = {"after": cursor} if cursor else {} @@ -1270,14 +430,9 @@ def fetch(cursor: str | None) -> dict: def page_files(owner: str, repo: str, num: int, pr: dict) -> None: """Read the rest of `pr`'s changed-file list into it, past the full read's first page. - `FILES_WINDOW` is the connection's own ceiling on one page, so a longer list is paged. - `FILES_CAP` is GitHub's documented ceiling on the whole list, which the API need not flag, - so a list reaching it stays marked as cut short. A page read at a head other than the first - page's leaves the list unread instead, under `FILES_UNREAD`, which `files_shortfall` - reports and `full_read` reads again. A list cut short or unread is compared against - nothing, where a list marked whole but missing a path reads exactly like a path the - reviewer left out. A page that fails to read ends the run as any other failed read does, - since that failure is already loud. + A list reaching `FILES_CAP` stays marked as cut short, and a page read at another head leaves + it unread under `FILES_UNREAD`. A list cut short or unread is compared against nothing. A + failed page read ends the run. """ files = pr.get("files") if not isinstance(files, dict): @@ -1300,11 +455,7 @@ def page_files(owner: str, repo: str, num: int, pr: dict) -> None: def reviewer_requested(pr: dict) -> bool: - """True where the reviewer sits in the pending request set. - - Read from GraphQL rather than `gh pr view --json reviewRequests`, which omits a Bot - reviewer entirely and reports an empty set while the reviewer is sitting in it. - """ + """True where the reviewer sits in the pending request set.""" return any( (n.get("requestedReviewer") or {}).get("login") == REVIEWER for n in ((pr.get("reviewRequests") or {}).get("nodes") or []) @@ -1312,28 +463,11 @@ def reviewer_requested(pr: dict) -> bool: def copilot_history(owner: str, repo: str) -> list[tuple[int, dict]]: - """The reviewer's own reviews and comments across the repository's most recently updated - pull requests, newest activity first regardless of which connection it came from. - - Read at HISTORY_PRS first and, only where that comes back carrying no usable bot id, read - again at the wider HISTORY_PRS_WIDE. A narrow window emptying out is the ordinary case, a - repository whose most recent activity genuinely carries none of the reviewer's, and costs - nothing beyond the one call either caller below was always going to make. It stops being - ordinary once an outage outlasts HISTORY_PRS pull requests: every one of them then carries - the same silence, the narrow window empties out too, and both callers would otherwise fall - back to blind polling for the rest of the outage with no way to tell that outage apart from a - repository that has simply never seen a Copilot review, a shape reproduced over four - consecutive pull requests. The wider read is what tells the two apart. - - Emptying out is not the only way the narrow window fails a bot-id lookup, though: it can - carry real activity and still have none, when every entry within it is a plain comment. A - formal review, `copilot_bot_id`'s only source for the id, can sit just outside the narrow - window while a newer comment sits inside it, and returning the narrow read as soon as it has - anything at all left that review permanently unread. Widening is keyed on - `copilot_bot_id(entries)` rather than on emptiness for exactly that case, so a comment-only - narrow window still triggers the wider read the same way an empty one does. The ordinary case - -- a narrow window already carrying a review -- still costs one call rather than two, since - that is the common shape a usable bot id already satisfies. + """The reviewer's own reviews and comments across the most recently updated pull requests. + + Newest activity first, whichever connection it came from. Read at HISTORY_PRS and, where that + carries no usable bot id, read again at HISTORY_PRS_WIDE, so a long outage or a comment-only + window does not read as a repository that never saw a Copilot review. """ entries = _copilot_history_window(owner, repo, HISTORY_PRS) if entries and copilot_bot_id(entries) is not None: @@ -1342,27 +476,12 @@ def copilot_history(owner: str, repo: str) -> list[tuple[int, dict]]: def _copilot_history_window(owner: str, repo: str, prs: int) -> list[tuple[int, dict]]: - """One read of `copilot_history`'s traversal, over the `prs` most recently updated pull - requests. Split out so the narrow and widened reads share every line but the one count. - - Paired with the pull request number each came from, since a repo-wide reading has to name - where it looked rather than just assert one. Sorted by timestamp rather than trusted to - arrive in that order, since the two connections are read separately and merged. - - Unfiltered, including the caller's own pull request if it appears in the window. No pull - request is special-cased out: `copilot_bot_id` is happy to read a valid id from anywhere, - including an earlier round on the very pull request `wait` is running against, and - `quota_signal` treats an earlier round on that same pull request as real evidence about the - account rather than a self-reference to discard. A refusal on the caller's own current head - is caught directly, at higher priority, before either reading here is ever consulted. - - A plain comment is read alongside a formal review, tagged `_kind` so `copilot_bot_id` can - still tell them apart, because `answered_outside_review` already treats a comment as - meaningful reviewer activity for one pull request, and a repo-wide reading that only checked - reviews could keep reporting a stale refusal after a newer plain comment answered it. - - One call serves both the bot-id lookup and the repo-wide quota reading below, since both - need the same traversal and a caller needing either otherwise pays for it twice. + """One read of `copilot_history`'s traversal over the `prs` most recently updated pull + requests. + + Entries pair with their pull request number and sort by timestamp. Nothing is filtered out, the + caller's own pull request included. A plain comment is tagged `_kind` so `copilot_bot_id` can + tell it from a formal review. """ data = gh_graphql( Q_BOT_ID, o=owner, r=repo, prs=prs, reviews=HISTORY_REVIEWS, comments=HISTORY_COMMENTS @@ -1382,11 +501,7 @@ def _copilot_history_window(owner: str, repo: str, prs: int) -> list[tuple[int, def history_entry(number: int, node: dict, kind: str) -> tuple[int, dict]: - """One reviewer review or comment in the shape `copilot_history` returns, stamped and tagged. - - Shared with `standing_quota`, which merges this pull request's own reviews into the history - `wait` read, so the two can never spell the entry differently. - """ + """One reviewer review or comment in the shape `copilot_history` returns, stamped and tagged.""" stamp = node.get("submittedAt" if kind == "review" else "createdAt") or "" return number, {**node, "_at": stamp, "_kind": kind} @@ -1397,16 +512,7 @@ def newest_first(entries: list[tuple[int, dict]]) -> list[tuple[int, dict]]: def copilot_bot_id(history: list[tuple[int, dict]]) -> str | None: - """The Copilot reviewer bot's node id from an already-fetched history, or None where none - carries one. - - Read from the review entries only, since a comment's author carries no node id in the query - that fetches it, that field belonging to the review connection's `... on Bot{ id }` selection. - None is a real answer, not a failure to retry: a repository's very first PR, or one Copilot - has never reviewed, carries no review to read the id from. The caller falls back to polling - only rather than guessing, since a fabricated or reused id resolves globally and a wrong one - would silently target another repository's PR. - """ + """The Copilot reviewer bot's node id from an already-fetched history, or None.""" for _number, entry in history: if entry.get("_kind") != "review": continue @@ -1417,17 +523,10 @@ def copilot_bot_id(history: list[tuple[int, dict]]) -> str | None: def quota_signal(history: list[tuple[int, dict]]) -> tuple[int, dict] | None: - """The reviewer's own most recent activity anywhere in this repository, review or comment, - where it is a quota refusal, paired with the pull request number it came from. - - The most recent rather than any match, since a repository can carry an old refusal and a - later working round both, and only the most recent record says which is still true. A - genuine review anywhere since the refusal spends it, the same reading `refusing_review` - already gives one pull request's own history, and so does a later plain comment, since - `answered_outside_review` treats one the same way for that one pull request. Reading across - pull requests rather than one is what a repository-wide account state needs, since the pull - request in front of a caller can carry none of its own reviewer activity to read that state - from at all. + """The reviewer's newest activity anywhere in this repository where it is a quota refusal. + + Returned paired with the pull request number it came from, else None. A genuine review or a + later plain comment since the refusal spends it. """ newest = history[0] if history else None return newest if newest and quota_refusal(newest[1]) else None @@ -1438,12 +537,8 @@ def standing_quota( ) -> tuple[int, dict] | None: """`quota_signal` over `history` as this pull request's own read leaves it, or None. - None where a genuine round covers the head, since the reading is about a head carrying no - Copilot activity of its own. This pull request's reviews are merged in rather than trusted to - sit in `history`, which reads only the most recently updated pull requests, so a review of it, - on any head, submitted after the refusal answers that refusal as one anywhere else would. `wait` - reads this on its opening snapshot and on its final read, so both apply one rule, though a - push between them can change what the rule finds. + None where a genuine round covers the head. This pull request's reviews are merged in, so a + review of it submitted after the refusal answers that refusal. """ if reviewed_head(pr): return None @@ -1452,37 +547,18 @@ def standing_quota( def rate_limited_by(pr: dict, login: str) -> str | None: - """The service name a rate-limit marker gives, where this login's newest comment or review - on this pull request carries one. `None` otherwise. CodeRabbit's reply to an explicit review - command, `RATE_LIMITED_REPLY`, is read from its markers and its fixed `Action not completed` - block alone. Its marker says `CodeRabbit` rather than the `coderabbit.ai` the other shape - gives, so `RATE_LIMIT_SERVICE` names the service by login and both shapes read alike. A login - missing there stays unread. - - Reads both connections. Both observed shapes ride a plain PR comment, and a future bot using - the same convention might ride a formal review instead. A plain comment - carries no commit, so the reading is not scoped to the head. Current pull request - only, unlike Copilot's `quota_signal`. That one generalizes from a pattern of silence across - several pull requests, while this reads one notice rather than a history. + """The service a tracked reviewer's newest comment or review names as rate limiting it, or + None. """ nodes = reviewer_nodes(pr, "comments", login) + reviewer_nodes(pr, "reviews", login) if not nodes: return None newest = max(nodes, key=lambda n: n.get("createdAt") or n.get("submittedAt") or "") - body = newest.get("body") or "" - if match := RATE_LIMITED.search(body): - return match.group(1) - if RATE_LIMITED_REPLY.search(body): - return RATE_LIMIT_SERVICE.get(login) - return None + return reading(newest, login).rate_limited def newest_request_event(pr: dict) -> str | None: - """The id of the newest review-request event naming the reviewer, or None where there is none. - - The id is compared rather than a count, since a count over a bounded window stops moving once - the window is full. - """ + """The id of the newest review-request event naming the reviewer, or None where there is none.""" ids = [ n.get("id") for n in ((pr.get("timelineItems") or {}).get("nodes") or []) @@ -1494,14 +570,9 @@ def newest_request_event(pr: dict) -> str | None: def request_recorded(before: dict, after: dict) -> bool | None: """Whether a review request that returned success left anything on the pull request. - True where the reviewer sits in the pending set afterwards, or where a review-request event - naming it is newer than the newest one read before the request. False where neither holds, - which is the shape an exhausted Copilot allowance left: every mutation succeeded, and none - added an event or a pending reviewer. None where the answer lacks either field, since an - unread state is not a reading of one, and the wait then polls as it did before this existed. - None too where a login that reads as the reviewer's but is spelled otherwise answers, since - a drifted login would otherwise read a recorded request as an unrecorded one and blame the - account for it. + True where the reviewer sits in the pending set afterwards, or a review-request event naming it + is newer than the newest one read before. False where neither holds, the shape an exhausted + Copilot allowance leaves. None where either field is missing or the login is spelled otherwise. """ if after.get("reviewRequests") is None or after.get("timelineItems") is None: return None @@ -1521,23 +592,11 @@ def request_copilot_review( ) -> tuple[str, bool | None]: """Ask Copilot to review the current head, and say in one line what happened. - This exists because `wait` used to only ever poll, never request, so a PR whose auto-seed - never fired or whose prior request was superseded by a later push sat waiting the full - timeout for a review nothing had asked for, twice in one session before this was written. - `union:true` adds the bot to the request set rather than replacing it, so a human reviewer - requested alongside it stays requested. Raises where `gh_graphql` does, on the mutation - itself, the same as every other write in this script: a failed write is reported, never - quietly swallowed into a fallback that would recreate the exact blind-poll failure this - function exists to prevent, from a different cause. The one quiet path is finding no bot id - to request with at all, which is not a failure, since a repository with no Copilot review - anywhere carries nothing to read the id from. The id itself is the caller's to find, via - `copilot_bot_id` over a `copilot_history` read it already paid for, which already tried both - the narrow HISTORY_PRS window and the wider HISTORY_PRS_WIDE one before coming up empty. - - The second value is `request_recorded` over the state read before the request and the one - the mutation answers with, and None where nothing was requested. An answer reading as - unrecorded is read once more with the same query and judged the same way, `settle` seconds - later, since GitHub can take a moment to record a request it has already accepted. + `union:true` adds the bot to the request set, so a human reviewer stays requested. A failed + mutation raises as every other write does. Finding no bot id is the one quiet path. + + The second value is `request_recorded` over the state before and after the request, None where + nothing was requested. An unrecorded answer is read once more `settle` seconds later. """ if not bot_id: return ( @@ -1564,12 +623,7 @@ def request_copilot_review( def reviewer_nodes(pr: dict, field: str, login: str = REVIEWER) -> list[dict]: - """This login's own nodes under `field`, oldest first as the API returns them. - - `login` defaults to the fully-modeled reviewer, so every existing call keeps reading - Copilot's own nodes unchanged. A caller reading another known reviewer's presence - generically, identity and commit only, no body parsing, passes it explicitly. - """ + """This login's own nodes under `field`, oldest first as the API returns them.""" return [ n for n in ((pr.get(field) or {}).get("nodes") or []) @@ -1578,17 +632,9 @@ def reviewer_nodes(pr: dict, field: str, login: str = REVIEWER) -> list[dict]: def answered_outside_review(pr: dict) -> dict | None: - """The reviewer's newest plain comment, where it postdates its newest formal review. - - The test is the shape of the answer rather than its cause, which this reads nothing of: - a comment carries no commit, so it satisfies no coverage check whatever it says. - Treating that shape as an unmet condition is what leaves a wait with nothing at its end. - A comment older than the newest review is spent, since the review it preceded did land. - """ + """The reviewer's newest plain comment, where it postdates its newest formal review.""" comments = reviewer_nodes(pr, "comments") - # A blind review window leaves no honest baseline to date a comment against. - # An empty one dates every comment as newer, so each reads as an answer. - # Reporting nothing keeps the wait polling, where a wrong answer ends it outright. + # A blind review window leaves no honest baseline to date a comment against, so report nothing. if not comments or window_blind(pr, "reviews"): return None newest = max(comments, key=lambda n: n.get("createdAt") or "") @@ -1600,118 +646,50 @@ def answered_outside_review(pr: dict) -> dict | None: def window_blind(pr: dict, field: str, login: str = REVIEWER) -> bool: """True where this login's own nodes can sit behind the window, so the view cannot decide. - `login` defaults to the fully-modeled reviewer, so every existing caller keeps reading - Copilot's own blind spot unchanged. A caller reading another known reviewer's own window, - Qodo's `comments` connection carrying its findings comment, passes it explicitly. - - Each query reads the newest nodes rather than this login's, so ordinary traffic is what - pushes theirs out of reach. Nodes arrive in creation order, so anything behind the window is - older than everything inside it: one of this login's in view bounds every hidden one as - older still, which settles the question rather than leaving it open. `hasPreviousPage` is - what says anything is back there at all, since a full window and a window holding the lot - are the same length. + `login` defaults to the fully-modeled reviewer. Nodes arrive in creation order, so one of this + login's in view bounds every hidden one as older. `hasPreviousPage` says whether anything is + back there at all. """ older = ((pr.get(field) or {}).get("pageInfo") or {}).get("hasPreviousPage") return bool(older) and not reviewer_nodes(pr, field, login) def threads_truncated(pr: dict) -> bool: - """True where `reviewThreads(first:100)` cut off before this pull request's actual thread - count, so `threads=`/`unresolved=` below undercount rather than reading the true total. - - Unlike `window_blind`'s `last`-windowed connections, `reviewThreads` reads forward from the - first page in the connection's own creation order, so `hasNextPage` here means the threads - left unread are the newest ones, not the oldest, exactly the ones most likely to still be - open. That inversion is why this is its own guard rather than a second use of `window_blind`: - that one settles the question from what is already in view, and there is no such settling - available here, only the fact that something was cut, undercounted ever since `unresolved` - widened from Copilot's own threads to every open thread. - """ + """True where `reviewThreads(first:100)` cut off before the actual thread count.""" return bool(((pr.get("reviewThreads") or {}).get("pageInfo") or {}).get("hasNextPage")) def reviews_truncated(pr: dict) -> bool: - """True where the `reviews` connection's own page cut off before this pull request's actual - round count, so a suppressed or outside-diff-range finding raised on an older, windowed-out - round is missing from `suppressed=`/`cr_outside_diff=` below rather than merely counted as - stale. - - Unlike `window_blind`, which settles a coverage or dating question once even one of a - login's own reviews sits in view, a finding count needs every round read, not just a - recent-enough one: an unread round can carry a finding of its own regardless of whether a - newer round from the same login is visible. `hasPreviousPage` on this `last`-windowed - connection means the reviews left unread are the oldest, exactly where an unanswered - finding is most likely to still sit unresolved. + """True where the `reviews` connection cut off before this pull request's actual round count. + + A finding count needs every round read, so an older windowed-out round can hide a suppressed or + outside-diff-range finding. `hasPreviousPage` means the unread reviews are the oldest. """ return bool(((pr.get("reviews") or {}).get("pageInfo") or {}).get("hasPreviousPage")) def refusal_of(node: dict) -> str: - """The review's body where its opening line says the reviewer did not review, otherwise empty. - - Read over the opening rather than the whole body, because a refusal replaces the review and - is the only thing the body carries, where a review that merely quotes the wording carries it - below its own overview. This script and its documentation are that quotation, so a body-wide - match would report the pull request adding this check as a refusal, which is the false - positive the suppressed-block matcher already had once. - - The opening is one line rather than two, and the second line is where the cost of widening - it shows: a review's first line is its heading and its second is the overview prose, which - is exactly where a review describing this check states the wording. Reading two lines passed - every case here except that one, which is the case that matters. A refusal introduced by a - heading would sit below the opening and be missed, and answering that shape means telling it - from an overview rather than reading one line further. - - The second overview format's version marker is skipped rather than read as that opening, - since it is markup that renders invisibly and a refusal wearing it opens on the line below. - That leaves the heading-introduced refusal named above missing in both formats alike rather - than in one, which is where it was before this format arrived. Such a round states no - coverage either, so it reaches the maintainer as an unproven diff rather than as a clean - pass, which is a worse remedy than a refusal's own and not a false green. - """ + """The review's body where the adapter reads it as a refusal, otherwise empty.""" body = node.get("body") or "" - opening = next( - (ln for ln in body.splitlines() if ln.strip() and not CCR_OVERVIEW.fullmatch(ln)), "" - ) - return body if REFUSAL.search(opening) else "" + return body if reading(node).refusal != "none" else "" def quota_refusal(node: dict) -> bool: - """True where a refusal on this node names the account quota rather than another cause. - - Read from `refusal_of`'s own return rather than the raw body, so its exemptions protect - this reading too: a node that is not a refusal at all returns `""` here, on which `QUOTA` - cannot match, rather than this needing its own opening-line anchor and fenced-quote guard. - The distinction matters because the two remedies are opposite. A file-count refusal is - cleared by splitting the pull request. A quota one is an account-level state that a - re-request or a wait does not touch, so treating the two alike sends a reader at a remedy - that does nothing here. - """ - return bool(QUOTA.search(refusal_of(node))) + """True where a refusal on this node names the account quota rather than another cause.""" + return reading(node).refusal == "quota" def possible_quota(node: dict) -> bool: - """True where a refusal on this node names an error rather than any cause. - - The weekly rate limit posts exactly this body, its cause written only to the job log, so it - reads as a possible quota hit rather than as a transient failure. A re-request into a reached - limit spends quota it cannot recover and returns the same body, which is why one is enough. - """ - return bool(ERROR_REFUSAL.search(refusal_of(node))) + """True where a refusal on this node names an error rather than any cause.""" + return reading(node).refusal == "error" @functools.cache def run_cause(owner: str, repo: str, oid: str, before: str) -> tuple[str, str] | None: """The error type and rate-limit sentence the reviewer's own failed run logged, or None. - An error refusal's body names no cause, and the run that produced it does: the reviewer runs - as an Actions workflow on the reviewed commit, and its job log states the weekly limit and - when it resets. The run read is the newest failed one on that commit created no later than - the review, so a later run on the same commit is not read as this round's. - - None wherever any read fails or finds nothing, which leaves the round a possible quota hit - rather than a confirmed one or a cleared one. Memoized for the run, so the digest and the exit - code read one log once. + The run read is the newest failed one on that commit created no later than the review. None + wherever any read fails or finds nothing. Memoized for the run. """ if not oid or not ISO_STAMP.fullmatch(before): return None @@ -1751,13 +729,7 @@ def confirmed_quota(owner: str, repo: str, node: dict) -> str: def stopping_refusal(pr: dict) -> dict | None: - """The reviewer's newest review on this pull request, on any head, where it is a quota refusal or an error. - - Read across heads rather than on the head alone, since a push after such a refusal moves the - head and the account state the refusal reports does not move with it. A genuine round since - spends it, the newest review being the one read, and so does a plain comment of the - reviewer's since, which `answered_outside_review` already reads as spending one. - """ + """The reviewer's newest review on any head, where it is a quota refusal or an error.""" if answered_outside_review(pr): return None newest = newest_of(reviewer_nodes(pr, "reviews")) @@ -1767,15 +739,7 @@ def stopping_refusal(pr: dict) -> dict | None: def refusing_review(pr: dict) -> dict | None: - """The reviewer's newest review carrying the current head, where that review is a refusal. - - Head-scoped, unlike a suppressed finding, because a refusal is a statement about one commit: - a push retires it, and the round the push raises either reviews that head or refuses it in - its own right. - - A genuine round on the same head after the refusal spends it, so the newest review on the - head is the one read rather than the newest refusal. - """ + """The reviewer's newest review carrying the current head, where that review is a refusal.""" head = pr["headRefOid"] newest = newest_of( [n for n in reviewer_nodes(pr, "reviews") if (n.get("commit") or {}).get("oid") == head] @@ -1786,18 +750,9 @@ def refusing_review(pr: dict) -> dict | None: def newest_of(nodes: list[dict]) -> dict | None: """The newest of these nodes by submission time, the later arrival winning a tie. - `max` returns the first maximal element and `reviewer_nodes` returns these oldest first, so - a tie on `submittedAt` selected the oldest round rather than the newest. GitHub stamps two - rounds on one commit with the same second often enough for that to decide a digest, and the - position in the connection is the only later-arriving signal there is once the timestamps - agree. - - A node carrying no timestamp sorts oldest, a round that has not been submitted not being the - one describing the head. - - Shared rather than spelled per reader, because `effort=` and `overview=` are read from a - round each and a digest line whose fields disagree about which round it describes is worse - than either field being wrong on its own. + `reviewer_nodes` returns oldest first and GitHub often stamps two rounds with the same second, + so position breaks the tie. A node with no timestamp sorts oldest. Shared so `effort=` and + `overview=` describe the same round. """ if not nodes: return None @@ -1807,13 +762,8 @@ def newest_of(nodes: list[dict]) -> dict | None: def head_reviews(pr: dict) -> list[dict]: """The reviewer's own reviews that cover the current head, refusals excluded. - A refusal is not coverage. It is a formal review, `state: COMMENTED`, carrying the head's - commit and raising no threads, so it satisfies every check a clean pass does and renders a - digest identical to one. That is how a pull request of 301 changed files, one over the - reviewer's limit, sat one command from merging on a review that never ran. - - One list rather than a predicate beside a filter, because coverage and the count of rounds on - the head are read from the same set and a second spelling of it drifts from the first. + A refusal is a formal review with the head's commit and no threads, so it satisfies every check + a clean pass does. One list serves coverage and the round count. """ head = pr["headRefOid"] return [ @@ -1824,46 +774,18 @@ def head_reviews(pr: dict) -> list[dict]: def reviewed_head(pr: dict) -> bool: - """True where one of the reviewer's own reviews covers the current head's commit. - - The liveness query carries no bodies, so a refusal reads there as ordinary coverage. That is - deliberate rather than a gap: it ends the wait, which is what a terminal outcome should do, - and the full read every wait finishes with is what tells the two apart. No exit code and no - merge decision is taken from the liveness reading. - """ + """True where one of the reviewer's own reviews covers the current head's commit.""" return bool(head_reviews(pr)) def head_review_done(pr: dict, min_rounds: int) -> bool: """True once a round past position `min_rounds` in the reviewer's own history covers the head. - Positions are read off `reviewer_nodes(pr, "reviews")`, every one of the reviewer's own - reviews on this pull request, on any head, refusals included, oldest first: the exact list - `status` counts for its own `rounds=`. A caller that already read that count, then - re-requested a review on an already-covered head, passes it through `wait --min-rounds` - instead, so this holds out for a round sitting past it. - - The round satisfying `min_rounds` and the round satisfying coverage must be the same round, - which is why this walks one list rather than checking `reviewed_head(pr)` and a count as two - independent clauses. Two clauses would let a refusal past the baseline satisfy the count - while an untouched, older genuine round still satisfies `reviewed_head`, reporting done on a - round that answered the re-request by declining it. A caller passing 0, every caller that - predates this flag among them, reduces to `reviewed_head` exactly, since position 0 is every - position a non-empty list has. - - Counting `reviewer_nodes(pr, "reviews")` rather than `head_reviews(pr)`, the head-scoped, - refusal-excluded list `reviewed_head` itself narrows to, matters independently of the above: - a push during the wait moves the head, which empties a head-scoped list and reads a brand - new head's first genuine round as still short of a baseline measured against a head that no - longer exists, where this list carries forward since a push adds to it rather than resetting - it. Positions still land past `min_rounds` correctly once the head moves, since a review on - the superseded head sits at an earlier position than one on the new head, never a later one. - - The same `last:100` window both `Q_LIVE` and `Q_FULL` place on their own `reviews` - connection bounds this the way it bounds `status`'s own `rounds=`: a pull request whose - Copilot rounds have aged out of that window under other reviewers' own traffic undercounts - here exactly as `status` would, reading a landed round as still short of the baseline rather - than crediting it, so this fails toward a caller waiting longer, not toward a false success. + Positions are read off `reviewer_nodes(pr, "reviews")`, every review on any head, refusals + included, oldest first, the list `status` counts for `rounds=`. One list is walked so the round + satisfying `min_rounds` is the round satisfying coverage. A push adds to the list rather than + resetting it, so positions stay valid when the head moves. The `last:100` window can undercount + an aged-out round, which fails toward waiting longer. Passing 0 reduces to `reviewed_head`. """ revs = reviewer_nodes(pr, "reviews") head = pr["headRefOid"] @@ -1874,324 +796,16 @@ def head_review_done(pr: dict, min_rounds: int) -> bool: def review_effort(pr: dict) -> tuple[str, str]: - """The newest head review's effective effort and selection source. - - GitHub can render an inherited choice as `Default (Lite)`, `Default (Balanced)`, or - `Default (Max)`. A bare level is explicit. The setting remains user-controlled, and this - reader only reports metadata that the completed review body exposes. - """ + """The newest head review's effective effort and selection source.""" newest = newest_of(head_reviews(pr)) if newest is None: return "unknown", "unknown" - plain = strip_fences(newest.get("body") or "") - for line in plain.splitlines(): - match = EFFORT_LINE.fullmatch(line) - if match: - source = "default" if match.group(1) else "explicit" - return (match.group(2) or match.group(3)).lower(), source - return "unknown", "unknown" - - -def code_indented(line: str) -> bool: - """Whether the line opens four or more columns in, the indentation of a Markdown code block. - - Measured in columns rather than characters, a tab being four of them and so an indented code - block on its own, which a character count reads as one column. Only spaces and tabs indent, - so a line opening on any other whitespace is ordinary text. - """ - expanded = line.expandtabs(4) - return len(expanded) - len(expanded.lstrip(" ")) >= 4 - - -def is_coverage_line(line: str) -> bool: - """Whether this line is the reviewer stating its file coverage, rather than prose about it.""" - if FLEET_REVIEW.search(line): - return True - if COVERAGE_BULLET.match(line): - return True - return bool(COVERAGE_SENTENCE.match(line)) and "changed file" in line.lower() - - -def coverage_statements(body: str) -> list[str]: - """The lines this round states its file coverage on, quotations excluded. - - An inline code span is a quotation the same as a fenced block, so a span carrying a coverage - line reads as one this round stated rather than one it quoted. - - A blockquoted line is the third such convention and is dropped whole rather than unwrapped. - The line anchor used to exclude one for free, the marker reader having required the marker to - be the whole of its line and a `>` not being whitespace. Reading the marker within its line - took that exclusion away, so the quotation it was refusing is refused here instead, where the - other two already are. The prose readers beside it are unaffected either way, each being - anchored to a line opener that a `>` already fails. - - The quotation runs to the blank line that closes it rather than to the end of the line opening - it, which is Markdown's own lazy continuation: a line carrying no `>` under one that does is - still rendered inside the quotation. Refusing only the marked line reads the line after a - quotation's first as this round's own statement. - - Continuation carries paragraph text and nothing else, so a line opening a block of its own ends - the quotation above it. Of the three spellings read here only the reviewer's own sentence is - paragraph text, the bullet and the marker each opening a block, and treating those as quoted - reported no coverage at all over a round that stated it in full. - - A line indented four or more columns is the fourth convention, an indented code block, and a - marker on one is dropped from the line rather than the line being dropped whole. The indent - opens a code block only where nothing runs on into it, since an indented line under paragraph - text is that paragraph's lazy continuation and renders as part of it, and a list item's own - text runs on the same way. A heading, a setext underline, a thematic break, and a line opening - an HTML comment each end their own block, and a code line carries its block on to the next. `CCR_OVERVIEW` - and `CCR_FINDINGS` bound their openers to three spaces for the same reason, and the marker, - being read within its line, takes that bound here instead of in its pattern. The rest of the - line is still read, the bullet and the sentence being left to their own readers as before, and - the marker comes off before the line is kept, because every reader downstream reads the - kept line with its indentation already stripped. - """ - plain = CODE_SPAN.sub(" ", strip_fences(body or "", to_end=True)) - found = [] - quoted = False - continues = False - for ln in plain.splitlines(): - stripped = ln.lstrip(" \t") - if not stripped: - # A blank line is what ends a blockquote, so the next line starts outside one again. - quoted = False - continues = False - continue - indented = code_indented(ln) - code = indented and not continues - continues = not code and not re.match( - rf"{ATX_HEADING}|{THEMATIC_BREAK}|(?:=+|-+){LINE_END}|", h) for h in html ) rate_limited = next( - (m.groupdict().get("service") or "" for p in vocab["rate_limit"] if (m := p.search(text))), + ( + m.groupdict().get("service") or vocab["rate_limit_service"] + for p in vocab["rate_limit"] + if (m := p.search(text)) + ), None, ) @@ -326,6 +331,8 @@ def _read(body: str, reviewer: str, threads: tuple[str, ...] | None) -> Reading: if coverage == "none" or rank[state] > rank[coverage]: coverage, coverage_line = state, m.group(0) + # A body in another layout is one note, rather than one note per part of it. + vet = vocab["vetted"] and (marked or not vocab["format_marker"]) if vocab["vetted"] and vocab["format_marker"]: if not text.strip(): notes.append("the body is empty") @@ -351,7 +358,7 @@ def _read(body: str, reviewer: str, threads: tuple[str, ...] | None) -> Reading: ("", None), ) if match is None: - if vocab["vetted"] and node.parent is None: + if vet and node.parent is None: notes.append(f"a collapsed section this reader has no spelling for: `{name}`") continue claimed.append((node.start, end + 1)) @@ -389,7 +396,7 @@ def inside(token: Token) -> bool: if kind and verdict == "unknown": verdict, verdict_heading = kind, name headline = headline_after(tokens, i + 3, lines) - elif not kind and vocab["vetted"] and not matched(vocab["headings"], name): + elif not kind and vet and not matched(vocab["headings"], name): notes.append(f"a heading this reader has no spelling for: `{name}`") elif token.type == "paragraph_open": inline = tokens[i + 1] @@ -409,10 +416,11 @@ def inside(token: Token) -> bool: open_count = (open_count or 0) + stated(found_kind[1]) elif matched(vocab["finding_lists"], name): listed += items_after(tokens, i + 3) - elif vocab["vetted"] and is_label(inline) and not matched(vocab["labels"], name): + elif vet and is_label(inline) and not matched(vocab["labels"], name): notes.append(f"a label this reader has no spelling for: `{name}`") elif token.type == "table_open" and vocab["table_header"]: - table = (table or []) + table_paths(tokens, i, vocab["table_header"]) + if (rows := table_paths(tokens, i, vocab["table_header"])) is not None: + table = (table or []) + rows i += 1 named = max(open_count or 0, listed) @@ -473,17 +481,14 @@ def entries_in( def headline_after(tokens: list[Token], start: int, lines: list[str]) -> str: - """The prose under a verdict heading, up to the next block that is not a plain paragraph.""" - said = [] - i = start - while i < len(tokens) and tokens[i].type == "paragraph_open" and tokens[i].level == 0: - inline = tokens[i + 1] - if is_label(inline) or (inline.children and inline.children[0].type == "strong_open"): - break - a, b = tokens[i].map or (0, 0) - said.append(" ".join(" ".join(lines[a:b]).split())) - i += 3 - return " ".join(said) + """The paragraph directly under a verdict heading, unless it is a label or a bold count line.""" + if start >= len(tokens) or tokens[start].type != "paragraph_open": + return "" + inline = tokens[start + 1] + if is_label(inline) or (inline.children and inline.children[0].type == "strong_open"): + return "" + a, b = tokens[start].map or (0, 0) + return " ".join(" ".join(lines[a:b]).split()) def is_label(inline: Token) -> bool: @@ -506,7 +511,7 @@ def items_after(tokens: list[Token], start: int) -> int: return count -def table_paths(tokens: list[Token], start: int, header: str) -> list[str]: +def table_paths(tokens: list[Token], start: int, header: str) -> list[str] | None: """The paths in the first column of the table opening at `start`, where its header names one.""" named: list[str] = [] column = -1 @@ -522,7 +527,7 @@ def table_paths(tokens: list[Token], start: int, header: str) -> list[str]: head = False elif token.type == "inline" and column == 0: if head and label(inline_text(token)) != header: - return [] + return None if not head: named.extend(paths(token)) return named diff --git a/scripts/reviewers/coderabbit.json b/scripts/reviewers/coderabbit.json index 7c4e33f5e..df0e26e1f 100644 --- a/scripts/reviewers/coderabbit.json +++ b/scripts/reviewers/coderabbit.json @@ -5,6 +5,7 @@ "comment_heading": "", "refusal_openings": [], "refusal_kinds": {"quota": [], "error": [], "file_count": []}, + "rate_limit_service": "coderabbit.ai", "rate_limit": [ "auto-generated comment:\\s*rate limited by\\s*(?P\\S+?)\\s*-->", "\\s*(?:\\s*)*
\\s*[^<\\n]*Action not completed\\s*\\s*Review rate limited\\." diff --git a/scripts/reviewers/copilot.json b/scripts/reviewers/copilot.json index 4ca11409d..97b64dbec 100644 --- a/scripts/reviewers/copilot.json +++ b/scripts/reviewers/copilot.json @@ -9,6 +9,7 @@ "error": ["encountered an error"], "file_count": ["maximum number of files"] }, + "rate_limit_service": "", "rate_limit": [], "verdicts": { "clean": ["approval recommended", "ready to approve"], diff --git a/scripts/reviewers/qodo.json b/scripts/reviewers/qodo.json index afb27755e..e29bd57f6 100644 --- a/scripts/reviewers/qodo.json +++ b/scripts/reviewers/qodo.json @@ -5,6 +5,7 @@ "comment_heading": "

\\s*Code Review by Qodo\\s*

", "refusal_openings": [], "refusal_kinds": {"quota": [], "error": [], "file_count": []}, + "rate_limit_service": "", "rate_limit": [], "verdicts": {"clean": [], "flagging": []}, "headings": [], From 1c137bc5f20568832bb0fb1ecc42efb0ce94c80a Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Fri, 23 Oct 2026 11:40:27 -0700 Subject: [PATCH 04/22] Retire the Explanations of Copilot's First Body Format Rewrite the scripts README sections for pr_review.py, the adapter, and pr_cleanup.py, dropping the readers and measurements of the retired format, and state the runbook's coverage rule without the statement carry. Co-Authored-By: Claude Opus 5.5 --- .github/copilot-instructions.md | 4 +- scripts/README.md | 99 ++++++++++++++++++--------------- 2 files changed, 55 insertions(+), 48 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 56980d28b..a9ccc1cde 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -28,9 +28,9 @@ For every review: The review automation is `scripts/pr_review.py`, run from a hub checkout. Use its `status`, `wait`, `attest`, `comment`, and `reply --resolve` commands instead of reconstructing GraphQL queries or copying review identifiers by hand. Use `comment` for a suppressed-finding answer in the pull request conversation. Its status gate verifies the current head, diff coverage, output shape, inline threads, body-only findings, and required checks. -A formal review with no findings is complete only when it covers the current head and full diff coverage of the change set that head has is stated, or read from a file table as below. The round covering the head states it, or the newest round that states it at all does and the pull request changes the same set of files at both commits, which is the only condition under which a statement carries forward. Only that newest round is consulted, so an older round whose change set does match carries nothing. Where no statement reaches the head either way, a round covering it whose own file table names exactly the changed files covers it, which is the reading a round at Balanced review effort gives, and a statement that reaches the head, stated on it or carried to it, wins over that table. Where no round covering the head carries a table of its own, the newest round that does, its table naming exactly the changed files, stands in under the bound a statement carries under, the pull request changing the same set of files at both commits. The table stands in only where no Copilot round on the pull request, on any commit, states or appears to state partial coverage, so a pull request that ever had a partial round goes to the maintainer. A round reporting partial coverage of the diff blocks the merge, and so does a refusal, a coverage statement that does not reach this head, meaning absent from every round or carried by none because the change set moved or could not be compared, with no file table or attested local pass standing in for it, an unrecognized output shape, an unresolved thread, or a body-only finding. On a pull request into a branch other than the default, an attested local pass covers the head, `coverage=local` in the digest. A partial round, a truncated review history, or a refusal on the head still blocks that reading. A pull request into the default branch, a promotion among them, always carries a Copilot round on its head. Re-run the loop after every fix push. Never infer review completion from `mergeStateStatus: CLEAN`. +A formal review with no findings is complete only when it covers the current head and full diff coverage of the change set that head has is stated, or read from a file table as below. A round covering the head states it. Where none does, a round covering the head whose own file table names exactly the changed files covers it, which is the reading a round at Balanced review effort gives. Where no round covering the head carries a table of its own, the newest round that does stands in where its table names exactly the changed files. A table stands in only where no Copilot round on the pull request, on any commit, states partial coverage, so a pull request that ever had a partial round goes to the maintainer. A round reporting partial coverage of the diff blocks the merge, and so does a refusal, a head that no coverage statement, file table, or attested local pass covers, an output shape the digest notes and nobody has read by hand, an unresolved thread, or a body-only finding. On a pull request into a branch other than the default, an attested local pass covers the head, `coverage=local` in the digest. A partial round, a truncated review history, or a refusal on the head still blocks that reading. A pull request into the default branch, a promotion among them, always carries a Copilot round on its head. Re-run the loop after every fix push. Never infer review completion from `mergeStateStatus: CLEAN`. -Review effort is user-controlled. The automation observes `Lite`, `Balanced`, or `Max`, including an inherited `Default ()`, and never selects or changes the setting. Effort does not determine coverage or completion. A request can complete without a `copilot_work_started` event, so absence of that event is not a stalled-review verdict. When `wait` returns `PENDING` with `requested=yes`, report the state and rerun `wait` for another bounded interval by default, reading that field as acceptance of the request rather than as delivery of a round. Do not clear the request on that first timeout, because it may still be active. Where a second bounded wait times out as well, read the pending set, clear it only where no human or team reviewer is requested alongside the bot, and rerun `wait`, which then has nothing outstanding to defer to and requests afresh, or polls and says so on its own auto-request line where it finds no reviewer node id to request with. The clear replaces that set rather than adding to it and nothing restores a request it drops, so a stall on a pull request that has a human or team reviewer requested goes to the maintainer, and so does one still pending after the wait that follows a clear. That clear is a recovery step the script does not implement, and `docs/pr-reviewer-reference.md`, in the hub checkout the script is run from, carries it. This recovery replaces only the review request and never changes the effort setting. A `wait` ending `REQUEST_NOT_RECORDED`, exit 48, is a different state and takes none of this recovery: the request returned success and left neither a pending reviewer nor a review-request event, which is how an exhausted Copilot allowance has shown itself, so clearing and requesting again does not clear it and it goes to the maintainer. +Review effort is user-controlled. The automation observes `Lite`, `Balanced`, or `Max`, including an inherited `Default ()`, and never selects or changes the setting. Effort does not determine coverage or completion. A request can complete without a `copilot_work_started` event, so absence of that event is not a stalled-review verdict. When `wait` returns `PENDING` with `requested=yes`, report the state and rerun `wait` for another bounded interval by default, reading that field as acceptance of the request rather than as delivery of a round. Do not clear the request on that first timeout, because it may still be active. Where a second bounded wait times out as well, read the pending set, clear it only where no human or team reviewer is requested alongside the bot, and rerun `wait`, which then has nothing outstanding to defer to and requests afresh, or polls and says so on its own auto-request line where it finds no reviewer node id to request with. The clear replaces that set rather than adding to it and nothing restores a request it drops, so a stall on a pull request that has a human or team reviewer requested goes to the maintainer, and so does one still pending after the wait that follows a clear. That clear is a recovery step the script does not implement, and `docs/pr-reviewer-reference.md`, in the hub checkout the script is run from, carries it. This recovery replaces only the review request and never changes the effort setting. A `wait` ending `REQUEST_NOT_RECORDED`, exit 40, is a different state and takes none of this recovery: the request returned success and left neither a pending reviewer nor a review-request event, which is how an exhausted Copilot allowance has shown itself, so clearing and requesting again does not clear it and it goes to the maintainer. ### Disproved Claims diff --git a/scripts/README.md b/scripts/README.md index e34858392..ba37b2f2a 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -4,14 +4,16 @@ The fleet's checks and review tooling, run by hand, with the deterministic ones **Hosted here and reached, never carried.** These are not declared in [`spec/files.json`][files], so the audit does not expect a downstream repo to ship them, the same footing as `spec/audit.py`. That is the fleet model rather than an omission: a gate holding no per-repo content has one canonical implementation for the fleet. The prose and repository gate implementations live beside their composite actions under `.github/actions/`, which lets reusable workflows reach the implementation at their pinned hub commit through `$/.github/actions/` without checking out the hub. The same-named files in `scripts/` are thin local entry points that call those action-owned implementations, so maintainers and hooks retain the established commands from a hub checkout without creating a second copy of either gate. A repository that cannot reach the hub reports a local check as not run rather than reconstructing it, since a rebuilt gate encodes its author's reading of the rule and agrees with no other repository. -Python only, standard library only, no third-party packages. Every check script is read-only and exits non-zero on a finding. `build_dist.py`, `local_review.py`, `canonical_review.py`, `handoff.py`, and `skills_install.py` below are the exceptions, since a generator, two recorders, an installer, and the handoff chain all exist to write. `build_dist.py --check` and `skills_install.py --report` are read-only modes for CI and for asking without changing anything. `local_review.py status` and `check` answer without recording anything, but they are not read-only in that same sense: reading the working tree stages it, which writes inside `.git` and runs any `filter.*.clean` the repository configures, and only the receipt is left untouched. `canonical_review.py` reads files rather than staging them, so its `list`, `status`, `sweep`, and `report` are read-only outright, and `record` alone writes. +Python only, and standard library only, except `pr_review.py`, `pr_review_copilot.py`, and `pr_cleanup.py`, which declare markdown-it-py in their inline script metadata. Every check script is read-only and exits non-zero on a finding. `build_dist.py`, `local_review.py`, `canonical_review.py`, `handoff.py`, and `skills_install.py` below are the exceptions, since a generator, two recorders, an installer, and the handoff chain all exist to write. `build_dist.py --check` and `skills_install.py --report` are read-only modes for CI and for asking without changing anything. `local_review.py status` and `check` answer without recording anything, but they are not read-only in that same sense: reading the working tree stages it, which writes inside `.git` and runs any `filter.*.clean` the repository configures, and only the receipt is left untouched. `canonical_review.py` reads files rather than staging them, so its `list`, `status`, `sweep`, and `report` are read-only outright, and `record` alone writes. -The directory separates its kinds by name and by tree. A gate checks and exits non-zero on a finding, and its name carries a `_lint` or `_gate` suffix saying what it gates. The `prose_lint.py` and `repo_gate.py` entry points delegate to the action-owned implementations that gate this tree in CI, and `host_gate.py` gates the machine it runs on. A utility does work rather than gating and carries no suffix: `backlog_metrics.py`, `build_dist.py`, `canonical_review.py`, `handoff.py`, `local_review.py`, `pr_review.py`, `skills_install.py`. `gh_graphql.py` is a library with no command line, the GraphQL transport and cursor walker that `handoff.py` and `pr_review.py` import from beside them. The unit tests live apart at the repository root under [`tests/`][tests], one `test_