Files
romm/.github/scripts/test_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

498 lines
20 KiB
Python

from __future__ import annotations
import base64
import itertools
import os
import tempfile
import unittest
import urllib.error
from collections.abc import Callable
from email.message import Message
from typing import Any
import vouch
from vouch import Command, Entry, VouchList
LIST_TEXT = "# header\n\nalice\n-bob spam PRs\ngithub:Carol\n-gitlab:dave\n"
BRANCH = vouch.PENDING_BRANCH
def http_error(code: int) -> urllib.error.HTTPError:
return urllib.error.HTTPError(
"https://api.github.com", code, "error", Message(), None
)
class Branch:
def __init__(self, head: str, text: str) -> None:
self.head = head
self.text = text
self.messages: list[str] = []
self.history = {head}
class FakeGitHub(vouch.GitHub):
"""An in-memory repo with a master branch, the pending branch, pulls and comments."""
def __init__(self, writers: set[str], text: str = LIST_TEXT) -> None:
super().__init__("token", "rommapp/romm")
self.writers = writers
self.shas = (f"sha{n}" for n in itertools.count())
self.branches: dict[str, Branch] = {"master": Branch(next(self.shas), text)}
self.pulls: list[dict[str, Any]] = []
self.comments: list[tuple[int, str]] = []
self.closed: list[int] = []
self.before_load: Callable[[], None] | None = None
self.before_put: Callable[[], None] | None = None
self.after_put: Callable[[], None] | None = None
def fire(self, hook_name: str) -> None:
"""Run a one-shot hook once and clear it."""
hook = getattr(self, hook_name)
if hook:
setattr(self, hook_name, None)
hook()
def has_write(self, login: str) -> bool:
return login in self.writers
def comment(self, number: int, body: str) -> None:
self.comments.append((number, body))
def close(self, number: int) -> None:
self.closed.append(number)
def vouch_list(self, branch: str) -> VouchList:
return VouchList.parse(self.branches[branch].text)
def commit(self, branch: str, text: str, message: str) -> None:
target = self.branches[branch]
target.head, target.text = next(self.shas), text
target.history.add(target.head)
target.messages.append(message)
for pull in self.pulls:
if pull["state"] == "open":
pull["head"]["sha"] = target.head
def merge(self, delete_branch: bool) -> None:
pending = self.branches[BRANCH]
master = self.branches["master"]
master.head, master.text = next(self.shas), pending.text
for pull in self.pulls:
if pull["state"] == "open":
pull["state"], pull["merged_at"] = "closed", "2026-01-01T00:00:00Z"
if delete_branch:
del self.branches[BRANCH]
def close_unmerged(self) -> None:
for pull in self.pulls:
pull["state"] = "closed"
def request(self, method: str, path: str, body: Any = None) -> Any:
path = path.removeprefix("/repos/rommapp/romm")
if path.startswith("/contents/"):
if method == "GET":
self.fire("before_load")
name = path.split("?ref=")[1].replace("%2F", "/")
if name not in self.branches:
raise http_error(404)
branch = self.branches[name]
content = base64.b64encode(branch.text.encode()).decode()
return {"content": content, "sha": branch.head}
self.fire("before_put")
if body["branch"] not in self.branches:
raise http_error(404)
if body["sha"] != self.branches[body["branch"]].head:
raise http_error(409)
text = base64.b64decode(body["content"]).decode()
self.commit(body["branch"], text, body["message"])
self.fire("after_put")
return {}
if method == "GET" and path.startswith("/pulls?state="):
state = path.split("state=")[1].split("&")[0]
return [p for p in reversed(self.pulls) if p["state"] == state]
if method == "GET" and path.startswith("/git/ref/heads/"):
name = path.removeprefix("/git/ref/heads/")
if name not in self.branches:
raise http_error(404)
return {"object": {"sha": self.branches[name].head}}
if method == "POST" and path == "/git/refs":
if BRANCH in self.branches:
raise http_error(422)
master = self.branches["master"]
self.branches[BRANCH] = Branch(master.head, master.text)
return {}
if method == "PATCH" and path == f"/git/refs/heads/{BRANCH}":
master = self.branches["master"]
self.branches[BRANCH] = Branch(master.head, master.text)
return {}
if method == "GET" and path == f"/compare/master...{BRANCH}":
messages = self.branches[BRANCH].messages
return {
"commits": [{"commit": {"message": m}} for m in messages],
"total_commits": len(messages),
}
if method == "POST" and path == "/pulls":
if any(p["state"] == "open" for p in self.pulls):
raise http_error(422)
pull = {
"number": 100 + len(self.pulls),
"state": "open",
"body": body["body"],
"head": {"sha": self.branches[BRANCH].head},
"merged_at": None,
}
self.pulls.append(pull)
return pull
if method == "PATCH" and path.startswith("/pulls/"):
number = int(path.rsplit("/", 1)[1])
pull = next(p for p in self.pulls if p["number"] == number)
if body.get("state") == "open":
# GitHub refuses when the branch was deleted or recreated.
pending = self.branches.get(BRANCH)
if (
pending is None
or pull["head"]["sha"] not in pending.history
or any(p["state"] == "open" for p in self.pulls)
):
raise http_error(422)
pull["state"] = "open"
pull["head"]["sha"] = pending.head
pull["body"] = body["body"]
return pull
raise AssertionError(f"unexpected request {method} {path}")
def comment_event(body: str, actor: str = "maint", **issue: Any) -> dict[str, Any]:
return {
"repository": {"default_branch": "master"},
"comment": {"body": body, "user": {"login": actor}},
"issue": {"number": 7, "user": {"login": "newbie"}, **issue},
}
def pr_event(
author: str, action: str = "opened", sender: str | None = None, **user: Any
) -> dict[str, Any]:
return {
"action": action,
"repository": {"default_branch": "master"},
"sender": {"login": sender or author},
"pull_request": {
"number": 9,
"user": {"login": author, **user},
"author_association": "CONTRIBUTOR",
},
}
class ParseTest(unittest.TestCase):
def test_parses_entries_and_keeps_header(self) -> None:
parsed = VouchList.parse(LIST_TEXT)
self.assertEqual(parsed.header, ["# header", ""])
self.assertEqual(
parsed.entries,
[
Entry("alice"),
Entry("bob", denounced=True, note="spam PRs"),
Entry("Carol", platform="github"),
Entry("dave", platform="gitlab", denounced=True),
],
)
def test_status_is_case_insensitive_and_ignores_other_platforms(self) -> None:
parsed = VouchList.parse(LIST_TEXT)
self.assertEqual(parsed.status("ALICE"), "vouched")
self.assertEqual(parsed.status("bob"), "denounced")
self.assertEqual(parsed.status("carol"), "vouched")
self.assertIsNone(parsed.status("dave"))
def test_rejects_invalid_handles(self) -> None:
for text in ("bad_handle!\n", "renovate[bot]\n", "--leading\n"):
with self.assertRaises(ValueError, msg=text):
VouchList.parse(text)
def test_accepts_legacy_hyphenated_handles(self) -> None:
parsed = VouchList.parse("old--name-\n")
self.assertEqual(parsed.status("old--name-"), "vouched")
def test_render_sorts_case_insensitively(self) -> None:
parsed = VouchList.parse("zed\nAmy\n-bo note\n")
self.assertEqual(parsed.render(), "Amy\n-bo note\nzed\n")
def test_repository_list_is_valid(self) -> None:
path = os.path.join(os.path.dirname(__file__), "..", "VOUCHED.td")
self.assertEqual(vouch.validate(path), 0)
def test_validate_flags_unsorted_and_duplicate_lists(self) -> None:
for text in ("zed\namy\n", "amy\n-Amy\n"):
with tempfile.NamedTemporaryFile("w", suffix=".td", delete=False) as handle:
handle.write(text)
self.addCleanup(os.remove, handle.name)
self.assertEqual(vouch.validate(handle.name), 1, text)
class CommandTest(unittest.TestCase):
def test_parses_commands(self) -> None:
self.assertEqual(vouch.parse_command("!vouch"), Command("vouch", None, ""))
self.assertEqual(
vouch.parse_command("!unvouch @al-ice"), Command("unvouch", "al-ice", "")
)
self.assertEqual(
vouch.parse_command("!denounce @bob ai slop\nmore text"),
Command("denounce", "bob", "ai slop"),
)
self.assertEqual(
vouch.parse_command("!denounce repeated slop"),
Command("denounce", None, "repeated slop"),
)
def test_ignores_other_text(self) -> None:
for body in ("", "lgtm", "please !vouch", "!vouched", "!vouch @bad_name"):
self.assertIsNone(vouch.parse_command(body), body)
def test_apply_command(self) -> None:
parsed = VouchList.parse(LIST_TEXT)
self.assertIsNone(
vouch.apply_command(parsed, Command("vouch", None, ""), "alice")
)
self.assertEqual(
vouch.apply_command(parsed, Command("vouch", None, ""), "bob"),
"vouch for bob",
)
self.assertEqual(parsed.status("bob"), "vouched")
self.assertEqual(
vouch.apply_command(parsed, Command("denounce", None, "spam"), "eve"),
"denounce eve",
)
self.assertIn("-eve spam", parsed.render())
self.assertEqual(
vouch.apply_command(parsed, Command("unvouch", None, ""), "eve"),
"remove eve",
)
self.assertIsNone(
vouch.apply_command(parsed, Command("unvouch", None, ""), "eve")
)
class VerdictTest(unittest.TestCase):
def setUp(self) -> None:
self.parsed = VouchList.parse(LIST_TEXT)
def verdict(self, login: str, **overrides: Any) -> vouch.Verdict:
options: dict[str, Any] = {
"is_bot": False,
"association": "NONE",
"has_write": lambda: False,
}
options.update(overrides)
return vouch.verdict(self.parsed, login, **options)
def test_vouched_and_exempt_authors_are_allowed(self) -> None:
self.assertEqual(self.verdict("alice"), "allow")
self.assertEqual(self.verdict("renovate[bot]", is_bot=True), "allow")
self.assertEqual(self.verdict("member", association="MEMBER"), "allow")
self.assertEqual(self.verdict("writer", has_write=lambda: True), "allow")
def test_others_are_unvouched_or_denounced(self) -> None:
self.assertEqual(self.verdict("stranger"), "unvouched")
self.assertEqual(self.verdict("bob"), "denounced")
class CheckTest(unittest.TestCase):
def test_closes_unvouched_pr_with_a_vouch_request_link(self) -> None:
gh = FakeGitHub(writers=set())
event = pr_event("stranger")
vouch.check(gh, event, event["pull_request"], "pull request")
self.assertEqual(gh.closed, [9])
self.assertIn("template=vouch_request.yml", gh.comments[0][1])
def test_keeps_vouched_pr_open(self) -> None:
gh = FakeGitHub(writers=set())
event = pr_event("alice")
vouch.check(gh, event, event["pull_request"], "pull request")
self.assertEqual((gh.closed, gh.comments), ([], []))
def test_skips_pr_a_maintainer_reopened(self) -> None:
gh = FakeGitHub(writers={"maint"})
event = pr_event("stranger", action="reopened", sender="maint")
vouch.check(gh, event, event["pull_request"], "pull request")
self.assertEqual(gh.closed, [])
def test_issues_close_only_for_denounced_authors(self) -> None:
gh = FakeGitHub(writers=set())
for author, closed in (("stranger", []), ("bob", [5])):
event: dict[str, Any] = {
"action": "opened",
"repository": {"default_branch": "master"},
"sender": {"login": author},
"issue": {
"number": 5,
"user": {"login": author},
"author_association": "NONE",
},
}
vouch.check(gh, event, event["issue"], "issue")
self.assertEqual(gh.closed, closed, author)
class ManageTest(unittest.TestCase):
REQUEST: dict[str, Any] = {"type": {"name": vouch.VOUCH_REQUEST_TYPE}}
def test_ignores_commands_from_non_writers(self) -> None:
gh = FakeGitHub(writers=set())
vouch.manage(gh, comment_event("!vouch", actor="newbie"))
vouch.manage(gh, comment_event("!vouch @bad_name", actor="newbie"))
self.assertEqual((gh.pulls, gh.comments), ([], []))
def test_answers_a_malformed_command_from_a_writer(self) -> None:
gh = FakeGitHub(writers={"maint"})
vouch.manage(gh, comment_event("!vouched"))
vouch.manage(gh, comment_event("!denounce @bob, spam"))
self.assertEqual(gh.pulls, [])
self.assertEqual(len(gh.comments), 1)
self.assertIn(vouch.COMMAND_USAGE, gh.comments[0][1])
def test_refuses_a_target_the_list_cannot_hold(self) -> None:
gh = FakeGitHub(writers={"maint"})
vouch.manage(gh, comment_event("!vouch", user={"login": "renovate[bot]"}))
self.assertNotIn(BRANCH, gh.branches)
self.assertEqual(
gh.comments, [(7, "No change: renovate[bot] isn't a GitHub user handle.")]
)
def test_vouch_request_opens_a_pending_pr_that_closes_the_request(self) -> None:
gh = FakeGitHub(writers={"maint"})
vouch.manage(gh, comment_event("!vouch", **self.REQUEST))
self.assertEqual(gh.vouch_list(BRANCH).status("newbie"), "vouched")
self.assertIsNone(gh.vouch_list("master").status("newbie"))
body = gh.pulls[0]["body"]
self.assertIn("- Vouch for newbie (#7, by maint)", body)
self.assertIn("Closes #7", body)
self.assertEqual(
gh.comments[-1],
(7, "Queued: vouch for newbie. It takes effect once #100 is merged."),
)
def test_vouching_someone_else_keeps_the_request_open(self) -> None:
gh = FakeGitHub(writers={"maint"})
vouch.manage(gh, comment_event("!vouch @frank", **self.REQUEST))
self.assertNotIn("Closes", gh.pulls[0]["body"])
def test_later_commands_add_to_the_open_pending_pr(self) -> None:
gh = FakeGitHub(writers={"maint"})
vouch.manage(gh, comment_event("!vouch"))
vouch.manage(gh, comment_event("!denounce @eve slop"))
self.assertEqual(len(gh.pulls), 1)
pending = gh.vouch_list(BRANCH)
self.assertEqual(
(pending.status("newbie"), pending.status("eve")), ("vouched", "denounced")
)
self.assertIn(
"- Vouch for newbie (#7, by maint)\n- Denounce eve (#7, by maint)",
gh.pulls[0]["body"],
)
def test_retries_when_another_run_commits_first(self) -> None:
gh = FakeGitHub(writers={"maint"})
gh.before_put = lambda: vouch.manage(gh, comment_event("!vouch @frank"))
vouch.manage(gh, comment_event("!vouch"))
pending = gh.vouch_list(BRANCH)
self.assertEqual(
(pending.status("frank"), pending.status("newbie")), ("vouched", "vouched")
)
self.assertEqual(len(gh.pulls), 1)
self.assertIn("Vouch for frank", gh.pulls[0]["body"])
self.assertIn("Vouch for newbie", gh.pulls[0]["body"])
def test_redoes_a_commit_that_a_concurrent_reset_dropped(self) -> None:
gh = FakeGitHub(writers={"maint"})
def reset_then_commit() -> None:
gh.request("PATCH", f"/git/refs/heads/{BRANCH}", {"force": True})
vouch.commit_change(
gh,
comment_event("!vouch @frank"),
Command("vouch", "frank", ""),
"frank",
)
gh.after_put = reset_then_commit
vouch.manage(gh, comment_event("!vouch"))
pending = gh.vouch_list(BRANCH)
self.assertEqual(
(pending.status("frank"), pending.status("newbie")), ("vouched", "vouched")
)
self.assertEqual(len(gh.pulls), 1)
self.assertIn("Vouch for newbie", gh.pulls[0]["body"])
self.assertEqual(
gh.comments[-1],
(7, "Queued: vouch for newbie. It takes effect once #100 is merged."),
)
def test_retries_when_the_branch_is_deleted_mid_command(self) -> None:
gh = FakeGitHub(writers={"maint"})
vouch.manage(gh, comment_event("!vouch"))
gh.before_load = lambda: gh.merge(delete_branch=True)
vouch.manage(gh, comment_event("!vouch @frank"))
self.assertEqual(len(gh.pulls), 2)
self.assertEqual(gh.vouch_list(BRANCH).status("frank"), "vouched")
self.assertNotIn("newbie", gh.pulls[1]["body"])
def test_builds_on_a_branch_another_run_has_not_opened_a_pr_for(self) -> None:
gh = FakeGitHub(writers={"maint"})
vouch.commit_change(
gh, comment_event("!vouch @frank"), Command("vouch", "frank", ""), "frank"
)
vouch.manage(gh, comment_event("!vouch"))
self.assertEqual(gh.vouch_list(BRANCH).status("frank"), "vouched")
self.assertIn("Vouch for frank", gh.pulls[0]["body"])
def test_restarts_from_master_after_a_merge(self) -> None:
for delete_branch in (True, False):
gh = FakeGitHub(writers={"maint"})
vouch.manage(gh, comment_event("!vouch"))
gh.merge(delete_branch)
vouch.manage(gh, comment_event("!vouch @frank"))
self.assertEqual(len(gh.pulls), 2, delete_branch)
self.assertNotIn("newbie", gh.pulls[1]["body"], delete_branch)
def test_keeps_the_queue_and_reopens_a_pr_closed_without_merging(self) -> None:
gh = FakeGitHub(writers={"maint"})
vouch.manage(gh, comment_event("!vouch"))
gh.close_unmerged()
vouch.manage(gh, comment_event("!vouch @frank"))
self.assertEqual(len(gh.pulls), 1)
self.assertEqual(gh.pulls[0]["state"], "open")
self.assertEqual(gh.pulls[0]["head"]["sha"], gh.branches[BRANCH].head)
pending = gh.vouch_list(BRANCH)
self.assertEqual(
(pending.status("frank"), pending.status("newbie")), ("vouched", "vouched")
)
self.assertIn("Vouch for newbie", gh.pulls[0]["body"])
self.assertEqual(
gh.comments[-1],
(7, "Queued: vouch for frank. It takes effect once #100 is merged."),
)
def test_starts_over_when_a_closed_pr_branch_was_deleted(self) -> None:
gh = FakeGitHub(writers={"maint"})
vouch.manage(gh, comment_event("!vouch"))
gh.close_unmerged()
del gh.branches[BRANCH]
vouch.manage(gh, comment_event("!vouch @frank"))
self.assertEqual([p["state"] for p in gh.pulls], ["closed", "open"])
self.assertNotIn("newbie", gh.pulls[1]["body"])
def test_reports_a_no_op(self) -> None:
gh = FakeGitHub(writers={"maint"})
vouch.manage(gh, comment_event("!vouch @alice"))
self.assertEqual(gh.pulls, [])
self.assertEqual(
gh.comments, [(7, "No change: alice is already in that state.")]
)
if __name__ == "__main__":
unittest.main()