Files
romm/.github/scripts/vouch.py
Georges-Antoine Assi 6aa1198634 feat(ci): add a vouch and denouncement contribution system (#5835)
* feat(ci): add a vouch and denouncement contribution system

Pull requests from authors who aren't vouched in .github/VOUCHED.td are
closed automatically, and denounced users' issues and pull requests are
closed too. Maintainers manage the list with !vouch, !unvouch and
!denounce comments, which queue changes on a single vouch/updates pull
request, since master is protected.

Adapted from Ghostty's vouch system (ghostty-org/ghostty#10559) with our
own stdlib-only script instead of the mitchellh/vouch actions. Adds a
vouch request issue form, an AI usage policy, and the matching
CONTRIBUTING sections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ci): keep concurrent vouch commands and close only the vouched request

Addresses Greptile review on #5835:
- Drop the concurrency group, which kept only one waiting run, and retry
  on conflicting commits instead. The pending PR body is rebuilt from the
  branch's commit messages so concurrent runs can't lose a line.
- Only close a vouch request when the vouched user is its author.
- Shorten the module docstring, workflow comments and VOUCHED.td header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: code-review

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: simplify

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: polish

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: prose

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: simplify code-review fixes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ci): keep the vouch queue when its PR is closed without merging

Only a merged PR resets vouch/updates now. A PR closed to rerun CI keeps
its commits, and the next command reopens it instead of opening a new one.
Deleting the branch drops the queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(ci): ask vouch requesters about their development experience

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(ci): tighten the vouch request experience prompt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(ci): ask vouch requesters what they've built and how they work

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(vouch): vouch for Covin90 and tmgast

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(vouch): vouch for milktoastrat and BrandonKowalski

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 17:12:10 -05:00

566 lines
20 KiB
Python

"""Enforce and manage the vouch list in `.github/VOUCHED.td`, using only the stdlib."""
from __future__ import annotations
import base64
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Literal, cast
API_URL = "https://api.github.com"
LIST_PATH = ".github/VOUCHED.td"
PENDING_BRANCH = "vouch/updates"
VOUCH_REQUEST_TYPE = "Vouch request"
VOUCH_REQUEST_TEMPLATE = "vouch_request.yml"
COMMIT_PREFIX = "chore(vouch): "
MAX_ATTEMPTS = 5
BRANCH_BUSY = f"{PENDING_BRANCH} kept changing; rerun the workflow"
# Status codes for a write that lost a race with another run.
CONFLICT_CODES = frozenset({404, 409, 422})
USAGE = """usage: vouch.py check-pr | check-issue | manage | validate PATH
check-pr close the event's PR when its author is unvouched or denounced
check-issue close the event's issue when its author is denounced
manage apply a !vouch, !unvouch or !denounce comment
validate fail when the list at PATH is malformed or unsorted"""
TRUSTED_ASSOCIATIONS = frozenset({"OWNER", "MEMBER", "COLLABORATOR"})
MANAGER_PERMISSIONS = frozenset({"admin", "write"})
# GitHub logins are letters, digits and hyphens, up to 39 characters long, and never
# start with a hyphen. Older accounts can have double or trailing hyphens.
HANDLE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]{0,38}$")
COMMAND_PREFIX = r"^!(?P<keyword>vouch|unvouch|denounce)"
COMMAND_RE = re.compile(
COMMAND_PREFIX + r"(?:[ \t]+@(?P<user>\S+))?(?:[ \t]+(?P<reason>.+))?$"
)
COMMAND_PREFIX_RE = re.compile(COMMAND_PREFIX + r"\b")
COMMAND_USAGE = "`!vouch [@user]`, `!unvouch [@user]` or `!denounce [@user] [reason]`"
Keyword = Literal["vouch", "unvouch", "denounce"]
Status = Literal["vouched", "denounced"]
Verdict = Literal["allow", "unvouched", "denounced"]
@dataclass(frozen=True)
class Entry:
handle: str
platform: str | None = None
denounced: bool = False
note: str = ""
@property
def key(self) -> str:
return self.handle.lower()
@property
def is_github(self) -> bool:
return self.platform in (None, "github")
def matches(self, login: str) -> bool:
return self.is_github and self.key == login.lower()
def render(self) -> str:
prefix = "-" if self.denounced else ""
platform = f"{self.platform}:" if self.platform else ""
note = f" {self.note}" if self.note else ""
return f"{prefix}{platform}{self.handle}{note}"
def parse_entry(line: str) -> Entry:
token, _, note = line.strip().partition(" ")
denounced = token.startswith("-")
token = token.removeprefix("-")
platform, sep, handle = token.partition(":")
if not sep:
platform, handle = "", platform
if not HANDLE_RE.match(handle):
raise ValueError(f"invalid handle in {LIST_PATH}: {line!r}")
return Entry(handle, platform or None, denounced, note.strip())
class VouchList:
"""Holds the list file's comment header and its entries, sorted by handle."""
def __init__(self, header: list[str], entries: list[Entry]) -> None:
self.header = header
self.entries = entries
@classmethod
def parse(cls, text: str) -> VouchList:
header: list[str] = []
entries: list[Entry] = []
for line in text.splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#"):
if not entries:
header.append(line.rstrip())
continue
entries.append(parse_entry(stripped))
return cls(header, entries)
def render(self) -> str:
ordered = sorted(self.entries, key=lambda e: (e.key, e.platform or ""))
return "\n".join([*self.header, *(e.render() for e in ordered)]) + "\n"
def status(self, login: str) -> Status | None:
for entry in self.entries:
if entry.matches(login):
return "denounced" if entry.denounced else "vouched"
return None
def remove(self, login: str) -> bool:
kept = [e for e in self.entries if not e.matches(login)]
removed = len(kept) != len(self.entries)
self.entries = kept
return removed
def set(self, login: str, *, denounced: bool, note: str = "") -> None:
self.remove(login)
self.entries.append(Entry(login, None, denounced, note))
@dataclass(frozen=True)
class Command:
keyword: Keyword
user: str | None
reason: str
def parse_command(body: str) -> Command | None:
"""Read a command from the first line of a comment, ignoring any text below it."""
lines = body.strip().splitlines()
match = COMMAND_RE.match(lines[0].strip() if lines else "")
if not match:
return None
user = match["user"]
if user is not None and not HANDLE_RE.match(user):
return None
keyword = cast(Keyword, match["keyword"])
return Command(keyword, user, (match["reason"] or "").strip())
def apply_command(vouch_list: VouchList, command: Command, target: str) -> str | None:
"""Apply a command and describe the change, or return None when nothing changed."""
current = vouch_list.status(target)
if command.keyword == "vouch":
if current == "vouched":
return None
vouch_list.set(target, denounced=False)
return f"vouch for {target}"
if command.keyword == "unvouch":
if current is None:
return None
vouch_list.remove(target)
return f"remove {target}"
if current == "denounced":
return None
vouch_list.set(target, denounced=True, note=command.reason)
return f"denounce {target}"
def verdict(
vouch_list: VouchList,
login: str,
*,
is_bot: bool,
association: str,
has_write: Callable[[], bool],
) -> Verdict:
"""Judge an author, calling `has_write` (an API request) only when nothing else decides."""
status = vouch_list.status(login)
if status == "vouched" or is_bot or association in TRUSTED_ASSOCIATIONS:
return "allow"
if status == "denounced":
return "denounced"
return "allow" if has_write() else "unvouched"
def commit_message(change: str, issue_number: int, actor: str, closes: bool) -> str:
lines = [
f"{COMMIT_PREFIX}{change}",
"",
f"Requested in #{issue_number} by {actor}.",
]
if closes:
lines.append(f"Closes #{issue_number}")
return "\n".join(lines)
def pending_pr_body(messages: list[str]) -> str:
"""Build the pending PR's description from the commit messages on its branch."""
changes: list[str] = []
closes: list[str] = []
for message in messages:
subject, _, rest = message.partition("\n")
if not subject.startswith(COMMIT_PREFIX):
continue
change = subject.removeprefix(COMMIT_PREFIX)
requested = re.search(r"^Requested in (#\d+) by (\S+)\.$", rest, re.MULTILINE)
source = f" ({requested[1]}, by {requested[2]})" if requested else ""
changes.append(f"- {change[0].upper()}{change[1:]}{source}")
for number in re.findall(r"^Closes #(\d+)$", rest, re.MULTILINE):
if number not in closes:
closes.append(number)
parts = [
f"Applies maintainer `!vouch`, `!unvouch` and `!denounce` comments to `{LIST_PATH}`."
" Each change takes effect once this PR is merged.",
"\n".join(changes),
]
if closes:
parts.append("\n".join(f"Closes #{number}" for number in closes))
parts.append(
"> [!NOTE]\n"
"> The workflow token can't trigger other workflows, so CI hasn't run on this PR."
" Close and reopen it to run the required checks before merging; queued changes"
" stay on the branch while it is closed. To drop them, delete the branch."
)
return "\n\n".join(parts) + "\n"
class GitHub:
def __init__(self, token: str, repo: str) -> None:
self.token = token
self.repo = repo
def request(self, method: str, path: str, body: Any = None) -> Any:
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(f"{API_URL}{path}", data=data, method=method)
req.add_header("Accept", "application/vnd.github+json")
req.add_header("Authorization", f"Bearer {self.token}")
req.add_header("X-GitHub-Api-Version", "2022-11-28")
if data is not None:
req.add_header("Content-Type", "application/json")
# The URL always starts with API_URL, so no other scheme can reach urlopen.
# trunk-ignore(bandit/B310)
with urllib.request.urlopen(req, timeout=30) as response:
raw = response.read()
return json.loads(raw) if raw else None
def repo_path(self, path: str) -> str:
return f"/repos/{self.repo}{path}"
def has_write(self, login: str) -> bool:
try:
result = self.request(
"GET", self.repo_path(f"/collaborators/{login}/permission")
)
except urllib.error.HTTPError as error:
if error.code == 404:
return False
raise
return result.get("permission") in MANAGER_PERMISSIONS
def load_list(self, ref: str) -> tuple[VouchList, str]:
result = self.request(
"GET",
self.repo_path(f"/contents/{LIST_PATH}?ref={urllib.parse.quote(ref)}"),
)
text = base64.b64decode(result["content"]).decode()
return VouchList.parse(text), result["sha"]
def comment(self, number: int, body: str) -> None:
self.request(
"POST", self.repo_path(f"/issues/{number}/comments"), {"body": body}
)
def close(self, number: int) -> None:
self.request(
"PATCH",
self.repo_path(f"/issues/{number}"),
{"state": "closed", "state_reason": "not_planned"},
)
def server_url() -> str:
return os.environ.get("GITHUB_SERVER_URL", "https://github.com")
def unvouched_message(repo: str) -> str:
base = f"{server_url()}/{repo}"
return (
"Thanks for your interest in contributing to RomM! Pull requests are only accepted"
" from vouched contributors, so this one was closed automatically.\n\n"
f"To get vouched, open a [vouch request]({base}/issues/new?template={VOUCH_REQUEST_TEMPLATE})"
" describing what you want to change and why. Once a maintainer vouches for you"
" and that change is merged, open a new pull request. See the"
f" [contributing guide]({base}/blob/master/CONTRIBUTING.md#first-time-contributors)"
" for details."
)
def denounced_message(kind: str) -> str:
return f"This account is on RomM's denounced list, so this {kind} was closed automatically."
def reopened_by_maintainer(gh: GitHub, event: dict[str, Any], author: str) -> bool:
sender = event["sender"]["login"]
return event["action"] == "reopened" and sender != author and gh.has_write(sender)
def check(gh: GitHub, event: dict[str, Any], item: dict[str, Any], kind: str) -> None:
author = item["user"]["login"]
if reopened_by_maintainer(gh, event, author):
print(f"{kind} reopened by a maintainer, skipping")
return
default_branch = event["repository"]["default_branch"]
vouch_list, _ = gh.load_list(default_branch)
result = verdict(
vouch_list,
author,
is_bot=item["user"].get("type") == "Bot",
association=item.get("author_association", "NONE"),
has_write=lambda: gh.has_write(author),
)
print(f"{author}: {result}")
if result == "allow" or (kind == "issue" and result == "unvouched"):
return
message = (
denounced_message(kind) if result == "denounced" else unvouched_message(gh.repo)
)
gh.comment(item["number"], message)
gh.close(item["number"])
def pending_prs(gh: GitHub, state: str = "open") -> list[dict[str, Any]]:
owner = gh.repo.split("/")[0]
return cast(
list[dict[str, Any]],
gh.request(
"GET", gh.repo_path(f"/pulls?state={state}&head={owner}:{PENDING_BRANCH}")
),
)
def prepare_pending_branch(gh: GitHub, default_branch: str) -> None:
"""Create the pending branch, or reset it when its last PR was merged."""
if pending_prs(gh):
return
head = gh.request("GET", gh.repo_path(f"/git/ref/heads/{default_branch}"))
base_sha = head["object"]["sha"]
try:
gh.request(
"POST",
gh.repo_path("/git/refs"),
{"ref": f"refs/heads/{PENDING_BRANCH}", "sha": base_sha},
)
return
except urllib.error.HTTPError as error:
if error.code != 422:
raise
# The branch exists. Reset it only if its head was merged. A PR closed without
# merging (often to rerun CI) keeps its commits and is reopened by sync_pending_pr.
branch = gh.request("GET", gh.repo_path(f"/git/ref/heads/{PENDING_BRANCH}"))
branch_sha = branch["object"]["sha"]
if any(
pr["merged_at"] and pr["head"]["sha"] == branch_sha
for pr in pending_prs(gh, "closed")
):
gh.request(
"PATCH",
gh.repo_path(f"/git/refs/heads/{PENDING_BRANCH}"),
{"sha": base_sha, "force": True},
)
def commit_change(
gh: GitHub, event: dict[str, Any], command: Command, target: str
) -> tuple[str, str] | None:
"""Commit the command to the pending branch, retrying when another run wins a race.
Returns:
The change and its commit message, or None when nothing changed.
"""
issue = event["issue"]
closes = (
command.keyword == "vouch"
and "pull_request" not in issue
and target.lower() == issue["user"]["login"].lower()
and (issue.get("type") or {}).get("name") == VOUCH_REQUEST_TYPE
)
actor = event["comment"]["user"]["login"]
for _ in range(MAX_ATTEMPTS):
try:
prepare_pending_branch(gh, event["repository"]["default_branch"])
vouch_list, sha = gh.load_list(PENDING_BRANCH)
change = apply_command(vouch_list, command, target)
if change is None:
return None
message = commit_message(change, issue["number"], actor, closes)
gh.request(
"PUT",
gh.repo_path(f"/contents/{LIST_PATH}"),
{
"message": message,
"content": base64.b64encode(vouch_list.render().encode()).decode(),
"sha": sha,
"branch": PENDING_BRANCH,
},
)
return change, message
except urllib.error.HTTPError as error:
if error.code not in CONFLICT_CODES:
raise
raise RuntimeError(BRANCH_BUSY)
def reopen_pending_pr(gh: GitHub, body: str) -> dict[str, Any] | None:
"""Reopen the latest pending PR when it was closed without merging.
Returns:
The reopened PR, or None when there is none to reopen.
"""
closed = pending_prs(gh, "closed")
if not closed or closed[0]["merged_at"]:
return None
number = closed[0]["number"]
try:
return cast(
dict[str, Any],
gh.request(
"PATCH",
gh.repo_path(f"/pulls/{number}"),
{"state": "open", "body": body},
),
)
except urllib.error.HTTPError as error:
# GitHub refuses when the branch was deleted or another run reopened it first.
if error.code != 422:
raise
return None
def sync_pending_pr(
gh: GitHub, default_branch: str
) -> tuple[dict[str, Any], list[str]]:
"""Open the pending PR, or refresh its description from the branch's commits.
Returns:
The pending PR and the commit messages its description was built from.
"""
compare = gh.repo_path(f"/compare/{default_branch}...{PENDING_BRANCH}")
for _ in range(MAX_ATTEMPTS):
messages = [
c["commit"]["message"] for c in gh.request("GET", compare)["commits"]
]
body = pending_pr_body(messages)
open_prs = pending_prs(gh)
if not open_prs:
reopened = reopen_pending_pr(gh, body)
if reopened is not None:
return reopened, messages
try:
created = gh.request(
"POST",
gh.repo_path("/pulls"),
{
"title": f"{COMMIT_PREFIX}update the vouch list",
"head": PENDING_BRANCH,
"base": default_branch,
"body": body,
},
)
return cast(dict[str, Any], created), messages
except urllib.error.HTTPError as error:
if error.code != 422:
raise
continue
pending = open_prs[0]
if pending.get("body") != body:
gh.request(
"PATCH", gh.repo_path(f"/pulls/{pending['number']}"), {"body": body}
)
# Another run may have committed while this one built the body.
if gh.request("GET", compare)["total_commits"] == len(messages):
return pending, messages
raise RuntimeError(BRANCH_BUSY)
def manage(gh: GitHub, event: dict[str, Any]) -> None:
comment = event["comment"]
issue = event["issue"]
command = parse_command(comment["body"])
if command is None and not COMMAND_PREFIX_RE.match(comment["body"].strip()):
return
actor = comment["user"]["login"]
if not gh.has_write(actor):
print(f"{actor} lacks write access, ignoring the command")
return
if command is None:
gh.comment(issue["number"], f"Couldn't read that command. Use {COMMAND_USAGE}.")
return
target = command.user or issue["user"]["login"]
if not HANDLE_RE.match(target):
gh.comment(issue["number"], f"No change: {target} isn't a GitHub user handle.")
return
for _ in range(MAX_ATTEMPTS):
committed = commit_change(gh, event, command, target)
if committed is None:
gh.comment(
issue["number"], f"No change: {target} is already in that state."
)
return
change, message = committed
pending, messages = sync_pending_pr(gh, event["repository"]["default_branch"])
# A run resetting the branch at the same time can drop the commit, so redo it.
if any(m.startswith(message) for m in messages):
gh.comment(
issue["number"],
f"Queued: {change}. It takes effect once #{pending['number']} is merged.",
)
return
raise RuntimeError(BRANCH_BUSY)
def validate(path: str) -> int:
with open(path, encoding="utf-8") as handle:
text = handle.read()
try:
vouch_list = VouchList.parse(text)
except ValueError as error:
print(error, file=sys.stderr)
return 1
counts = Counter(e.key for e in vouch_list.entries if e.is_github)
duplicates = sorted(k for k, n in counts.items() if n > 1)
if duplicates:
print(f"{path} lists these handles more than once: {', '.join(duplicates)}")
return 1
if vouch_list.render() != text:
print(f"{path} isn't sorted by handle, or has comments after the first entry")
return 1
return 0
def main(argv: list[str]) -> int:
if len(argv) == 3 and argv[1] == "validate":
return validate(argv[2])
if len(argv) != 2 or argv[1] not in ("check-pr", "check-issue", "manage"):
print(USAGE, file=sys.stderr)
return 2
with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as handle:
event = json.load(handle)
gh = GitHub(os.environ["GITHUB_TOKEN"], os.environ["GITHUB_REPOSITORY"])
if argv[1] == "check-pr":
check(gh, event, event["pull_request"], "pull request")
elif argv[1] == "check-issue":
check(gh, event, event["issue"], "issue")
else:
manage(gh, event)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))