BlueGit

ict rusty-teams

ci(pr): a PR gate checks contributor PRs before review

- pr-gate.yml (pull_request_target, reads the PR as data): title, template sections, problem or linked issue, accepted issue for feat or over 400 lines, screenshot for UI code, Windows note, two reviews, no planning folders
- one checklist comment, status: needs info, back to draft until it passes; replaces pr-title.yml
- stale-prs.yml closes PRs that stay needs info for 14 days
- template gets Problem and Tests sections; CONTRIBUTING lists the gates

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

metis Daniel Däschle · pushed by metis

Authored 2026-11-25 · 6 days ago

Hash
89e3a65fad4de3eb5344dd7bb2632f130df65888
Parent
a90a74ad
9 files changed +533 −33
.github/pull_request_template.md +13 −3
@@ -1,16 +1,26 @@
1 1 ## Summary
2 2
3 <!-- What changes and why, in a few sentences. "Closes #123" if there is an issue. -->
3 <!-- What changes, in a few sentences. "Closes #123" if there is an issue. -->
4
5 ## Problem
6
7 <!-- Only without an issue. What is wrong or missing, when a user hits it (steps or when/then), what should happen instead. -->
4 8
5 9 ## AI model
6 10
7 11 <!-- Which tool and model wrote the change, e.g. "Claude Code, Opus 4.5" or "Copilot, GPT-5". "None" if written by hand. -->
8 12
13 ## Tests
14
15 <!-- Ran: the commands and manual checks that ran. Not run: what you could not run, e.g. Windows-only code without a Windows build. -->
16
9 17 ## Review
10 18
11 19 <!-- At least two independent reviews of the diff (see AGENTS.md). One line per review (what ran it), then one line per finding: fixed, or not fixed and why. -->
12 20
13 21 ## Screenshot
14 22
15 <!-- For every change that is visible in the UI: one shot of the changed area. Delete the section otherwise.
16 Use demo data (`cargo run -p app -- --demo` or `scripts/headless-shot.sh`), never a real account. -->
23 <!-- Every change to UI code: one shot of the changed area, taken with demo data (`cargo run -p app -- --demo` or `scripts/headless-shot.sh`), never a real account.
24 No visible change? Tick the box and say why. -->
25
26 - [ ] No visible change:
@@ -1,16 +1,26 @@
1## Summary
1## Summary
2
2
3<!-- What changes and why, in a few sentences. "Closes #123" if there is an issue. -->
3<!-- What changes, in a few sentences. "Closes #123" if there is an issue. -->
4
5## Problem
6
7<!-- Only without an issue. What is wrong or missing, when a user hits it (steps or when/then), what should happen instead. -->
4
8
5## AI model
9## AI model
6
10
7<!-- Which tool and model wrote the change, e.g. "Claude Code, Opus 4.5" or "Copilot, GPT-5". "None" if written by hand. -->
11<!-- Which tool and model wrote the change, e.g. "Claude Code, Opus 4.5" or "Copilot, GPT-5". "None" if written by hand. -->
8
12
13## Tests
14
15<!-- Ran: the commands and manual checks that ran. Not run: what you could not run, e.g. Windows-only code without a Windows build. -->
16
9## Review
17## Review
10
18
11<!-- At least two independent reviews of the diff (see AGENTS.md). One line per review (what ran it), then one line per finding: fixed, or not fixed and why. -->
19<!-- At least two independent reviews of the diff (see AGENTS.md). One line per review (what ran it), then one line per finding: fixed, or not fixed and why. -->
12
20
13## Screenshot
21## Screenshot
14
22
15<!-- For every change that is visible in the UI: one shot of the changed area. Delete the section otherwise.
23<!-- Every change to UI code: one shot of the changed area, taken with demo data (`cargo run -p app -- --demo` or `scripts/headless-shot.sh`), never a real account.
16 Use demo data (`cargo run -p app -- --demo` or `scripts/headless-shot.sh`), never a real account. -->
24 No visible change? Tick the box and say why. -->
25
26- [ ] No visible change:
.github/scripts/pr_gate.py added +306 −0
@@ -0,0 +1,306 @@
1 """Checks whether a pull request is ready for review (CONTRIBUTING.md, "When a PR is ready for review").
2
3 Run by .github/workflows/pr-gate.yml under pull_request_target: it reads the PR as data
4 through the API and never checks out or runs code from the PR.
5 """
6
7 import json
8 import os
9 import re
10 import sys
11 import urllib.error
12 import urllib.parse
13 import urllib.request
14 from dataclasses import dataclass, field
15 from typing import Any
16
17 TITLE_PATTERN = re.compile(r"^(feat|fix|perf|refactor|docs|test|chore|ci|build)(\([a-z0-9-]+\))?!?: \S")
18 UI_PATH_PATTERN = re.compile(r"^crates/app/src/(views|settings|components|widgets)/|^crates/app/src/[^/]+_view\.rs$|/locales/")
19 IMAGE_PATTERN = re.compile(r"!\[[^\]]*\]\(|<img\s|<video\s|github\.com/user-attachments/|\.(png|jpe?g|gif|webp|mp4|webm)\b", re.IGNORECASE)
20 ISSUE_REFERENCE_PATTERN = re.compile(
21 r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?):?\s+(?:https://github\.com/danieldaeschle/rusty-teams/issues/|#)(\d+)", re.IGNORECASE
22 )
23 NO_VISUAL_CHECKBOX_PATTERN = re.compile(r"^\s*[-*]\s*\[[xX]\]\s*no visible change", re.IGNORECASE | re.MULTILINE)
24 FORBIDDEN_PATH_PATTERN = re.compile(r"^(openspec|\.specify|\.kiro)/")
25 WINDOWS_CODE_PATTERN = re.compile(r"^\+.*(cfg\((all\()?windows|target_os\s*=\s*\"windows\")", re.MULTILINE)
26 WINDOWS_PATH_PATTERN = re.compile(r"(^|/)(win32|windows)(/|_[a-z]+\.rs$)|_win(dows)?\.rs$")
27 LOCKFILE_NAMES =("Cargo.lock", "package-lock.json", "pnpm-lock.yaml", "yarn.lock")
28
29 MAX_CHANGED_LINES = 400
30 MIN_PROBLEM_CHARACTERS = 80
31 MIN_REVIEW_LINES = 2
32 REQUIRED_SECTIONS = ("Summary", "AI model", "Tests", "Review")
33 SECTION_ALIASES = {"tests": ("test plan", "testing", "test")}
34
35 LABEL_NEEDS_INFO = "status: needs info"
36 LABEL_NEEDS_REVIEW = "status: needs review"
37 STATUS_LABEL_PREFIX = "status: "
38 EXEMPT_ASSOCIATIONS = ("OWNER", "MEMBER", "COLLABORATOR")
39 LABEL_ACCEPTED = "status: accepted"
40 LABEL_NO_VISUAL = "gate: no visual"
41 LABEL_SKIP = "gate: skip"
42
43 COMMENT_MARKER = "<!-- pr-gate -->"
44
45
46 @dataclass
47 class ChangedFile:
48 path: str
49 additions: int = 0
50 deletions: int = 0
51 patch: str = ""
52
53
54 @dataclass
55 class PullRequest:
56 title: str
57 body: str
58 labels: list[str] = field(default_factory=list)
59 files: list[ChangedFile] = field(default_factory=list)
60 linked_issue_labels: dict[int, list[str]] = field(default_factory=dict)
61
62
63 def strip_comments(text: str) -> str:
64 return re.sub(r"<!--.*?-->", "", text or "", flags=re.DOTALL)
65
66
67 def parse_sections(body: str) -> dict[str, str]:
68 sections: dict[str, str] = {}
69 current_heading = None
70 current_lines: list[str] = []
71 for line in strip_comments(body).splitlines():
72 heading = re.match(r"^##\s+(.+?)\s*$", line)
73 if heading:
74 if current_heading is not None:
75 sections[current_heading] = "\n".join(current_lines).strip()
76 current_heading = heading.group(1).strip().lower()
77 current_lines = []
78 elif current_heading is not None:
79 current_lines.append(line)
80 if current_heading is not None:
81 sections[current_heading] = "\n".join(current_lines).strip()
82 return sections
83
84
85 def find_section(sections: dict[str, str], name: str) -> str | None:
86 names = (name.lower(), *SECTION_ALIASES.get(name.lower(), ()))
87 for heading, content in sections.items():
88 if any(heading == wanted or heading.startswith(wanted + " ") or heading.startswith(wanted + ":") for wanted in names):
89 return content
90 return None
91
92
93 def linked_issue_numbers(body: str) -> list[int]:
94 return sorted({int(number) for number in ISSUE_REFERENCE_PATTERN.findall(strip_comments(body))})
95
96
97 def changed_lines(files: list[ChangedFile]) -> int:
98 return sum(changed.additions + changed.deletions for changed in files if changed.path.rsplit("/", 1)[-1] not in LOCKFILE_NAMES)
99
100
101 def title_type(title: str) -> str:
102 return title.split("(", 1)[0].split(":", 1)[0].split("!", 1)[0].strip()
103
104
105 def non_empty_lines(text: str) -> list[str]:
106 return [line for line in text.splitlines() if line.strip()]
107
108
109 def check(pull_request: PullRequest) -> list[str]:
110 """Returns one line per missing item, empty when the PR is ready for review."""
111 missing: list[str] = []
112 sections = parse_sections(pull_request.body)
113 issue_numbers = linked_issue_numbers(pull_request.body)
114 paths = [changed.path for changed in pull_request.files]
115
116 if not TITLE_PATTERN.match(pull_request.title):
117 missing.append("**Title**: use `type(scope): message` from the user's view, e.g. `fix(chat): a sent image no longer blinks`.")
118
119 for name in REQUIRED_SECTIONS:
120 if not find_section(sections, name):
121 missing.append(f"**{name}**: the `## {name}` section is missing or empty.")
122
123 if not issue_numbers:
124 problem = find_section(sections, "Problem") or ""
125 if len(problem) < MIN_PROBLEM_CHARACTERS:
126 missing.append(
127 "**Problem**: no linked issue (`Closes #123`), so a `## Problem` section must describe it: "
128 "what is wrong or missing, when a user hits it (steps or when/then) and what should happen instead."
129 )
130
131 size = changed_lines(pull_request.files)
132 needs_accepted_issue = title_type(pull_request.title) == "feat" or size > MAX_CHANGED_LINES
133 if needs_accepted_issue:
134 accepted = any(LABEL_ACCEPTED in pull_request.linked_issue_labels.get(number, []) for number in issue_numbers)
135 if not accepted:
136 reason = "a feature" if title_type(pull_request.title) == "feat" else f"{size} changed lines (over {MAX_CHANGED_LINES})"
137 missing.append(
138 f"**Issue first**: this PR is {reason}. Link an issue that a maintainer marked `{LABEL_ACCEPTED}`, "
139 "or split the change into smaller PRs."
140 )
141
142 if any(UI_PATH_PATTERN.search(path) for path in paths) and LABEL_NO_VISUAL not in pull_request.labels:
143 screenshot = find_section(sections, "Screenshot") or ""
144 has_image = bool(IMAGE_PATTERN.search(strip_comments(pull_request.body)))
145 if not has_image and not NO_VISUAL_CHECKBOX_PATTERN.search(screenshot):
146 missing.append(
147 "**Screenshot**: the change touches UI code. Add a shot of the changed area taken with `--demo` data, "
148 "or tick `No visible change` and say why."
149 )
150
151 tests = find_section(sections, "Tests") or ""
152 touches_windows = any(WINDOWS_CODE_PATTERN.search(changed.patch) or WINDOWS_PATH_PATTERN.search(changed.path) for changed in pull_request.files)
153 if tests and touches_windows and "windows" not in tests.lower():
154 missing.append("**Tests**: the change touches Windows-only code. Say whether you built and ran it on Windows.")
155
156 review = find_section(sections, "Review") or ""
157 if review and len(non_empty_lines(review)) < MIN_REVIEW_LINES:
158 missing.append("**Review**: list at least two independent reviews of the diff and what happened to each finding (AGENTS.md).")
159
160 forbidden = sorted({path.split("/", 1)[0] for path in paths if FORBIDDEN_PATH_PATTERN.match(path)})
161 if forbidden:
162 missing.append(f"**Scope**: remove planning folders from the PR: {', '.join(f'`{name}/`' for name in forbidden)}.")
163
164 if any(path.startswith("vendor/") for path in paths) and "vendor" not in strip_comments(pull_request.body).lower():
165 missing.append("**Scope**: the PR changes `vendor/`. Say in the summary why the fix belongs in the fork.")
166
167 return missing
168
169
170 def render_comment(missing: list[str]) -> str:
171 if not missing:
172 return f"{COMMENT_MARKER}\n**PR gate: ready for review.** Thanks, a maintainer will take a look."
173 items = "\n".join(f"- [ ] {item}" for item in missing)
174 return (
175 f"{COMMENT_MARKER}\n**PR gate: not ready for review yet.** Please add:\n\n{items}\n\n"
176 "Edit the description or push, and this comment updates itself. When everything is there, mark the PR "
177 "ready for review. The rules are in CONTRIBUTING.md under \"When a PR is ready for review\". "
178 f"A PR that stays `{LABEL_NEEDS_INFO}` for 14 days is closed; it can be reopened any time."
179 )
180
181
182 class GitHub:
183 def __init__(self, repository: str, token: str):
184 self.base_url = f"https://api.github.com/repos/{repository}"
185 self.token = token
186
187 def request(self, method: str, url: str, payload=None) -> Any:
188 full_url = url if url.startswith("https://") else self.base_url + url
189 data = json.dumps(payload).encode() if payload is not None else None
190 request = urllib.request.Request(full_url, data=data, method=method)
191 request.add_header("Authorization", f"Bearer {self.token}")
192 request.add_header("Accept", "application/vnd.github+json")
193 request.add_header("X-GitHub-Api-Version", "2022-11-28")
194 with urllib.request.urlopen(request) as response:
195 content = response.read()
196 return json.loads(content) if content else None
197
198 def paged(self, url: str) -> list:
199 results, page = [], 1
200 while True:
201 separator = "&" if "?" in url else "?"
202 batch = self.request("GET", f"{url}{separator}per_page=100&page={page}")
203 results.extend(batch)
204 if len(batch) < 100:
205 return results
206 page += 1
207
208
209 def load_pull_request(github: GitHub, number: int) -> tuple[dict, PullRequest]:
210 raw = github.request("GET", f"/pulls/{number}")
211 files = [
212 ChangedFile(item["filename"], item.get("additions", 0), item.get("deletions", 0), item.get("patch", ""))
213 for item in github.paged(f"/pulls/{number}/files")
214 ]
215 body = raw.get("body") or ""
216 issue_labels: dict[int, list[str]] = {}
217 for issue_number in linked_issue_numbers(body):
218 try:
219 issue = github.request("GET", f"/issues/{issue_number}")
220 issue_labels[issue_number] = [label["name"] for label in issue.get("labels", [])]
221 except urllib.error.HTTPError:
222 issue_labels[issue_number] = []
223 labels = [label["name"] for label in raw.get("labels", [])]
224 return raw, PullRequest(raw["title"], body, labels, files, issue_labels)
225
226
227 def is_exempt(raw: dict, labels: list[str]) -> bool:
228 return LABEL_SKIP in labels or raw["user"]["type"] == "Bot" or raw.get("author_association") in EXEMPT_ASSOCIATIONS
229
230
231 def upsert_comment(github: GitHub, number: int, text: str) -> None:
232 for comment in github.paged(f"/issues/{number}/comments"):
233 if COMMENT_MARKER in (comment.get("body") or "") and comment["user"]["type"] == "Bot":
234 if comment["body"] != text:
235 github.request("PATCH", f"/issues/comments/{comment['id']}", {"body": text})
236 return
237 github.request("POST", f"/issues/{number}/comments", {"body": text})
238
239
240 def add_label(github: GitHub, number: int, labels: list[str], name: str) -> None:
241 if name not in labels:
242 github.request("POST", f"/issues/{number}/labels", {"labels": [name]})
243
244
245 def remove_label(github: GitHub, number: int, labels: list[str], name: str) -> None:
246 if name not in labels:
247 return
248 try:
249 github.request("DELETE", f"/issues/{number}/labels/{urllib.parse.quote(name)}")
250 except urllib.error.HTTPError as error:
251 if error.code != 404:
252 raise
253
254
255 def update_labels(github: GitHub, number: int, labels: list[str], ready: bool) -> None:
256 """Sets only the gate's own labels; the maintainers' status labels stay as they are."""
257 if not ready:
258 add_label(github, number, labels, LABEL_NEEDS_INFO)
259 return
260 remove_label(github, number, labels, LABEL_NEEDS_INFO)
261 if not any(label.startswith(STATUS_LABEL_PREFIX) and label != LABEL_NEEDS_INFO for label in labels):
262 add_label(github, number, labels, LABEL_NEEDS_REVIEW)
263
264
265 def convert_to_draft(github: GitHub, node_id: str) -> None:
266 query = "mutation($id: ID!) { convertPullRequestToDraft(input: {pullRequestId: $id}) { clientMutationId } }"
267 try:
268 github.request("POST", "https://api.github.com/graphql", {"query": query, "variables": {"id": node_id}})
269 except urllib.error.HTTPError as error:
270 print(f"::warning::could not convert to draft: {error}")
271
272
273 def run_gate(github: GitHub, number: int, enforce: bool) -> bool:
274 raw, pull_request = load_pull_request(github, number)
275 if raw["state"] != "open":
276 return True
277 if is_exempt(raw, pull_request.labels):
278 print(f"#{number}: exempt")
279 return True
280 is_draft = bool(raw.get("draft"))
281 if is_draft and enforce and LABEL_NEEDS_INFO not in pull_request.labels:
282 print(f"#{number}: draft, gate runs when it is marked ready for review")
283 return True
284 missing = check(pull_request)
285 upsert_comment(github, number, render_comment(missing))
286 update_labels(github, number, pull_request.labels, ready=not missing)
287 if missing and enforce and not is_draft:
288 convert_to_draft(github, raw["node_id"])
289 print(f"#{number}: {'ready' if not missing else 'missing ' + str(len(missing))}")
290 for item in missing:
291 print(f" - {item}")
292 return is_draft or not missing
293
294
295 def main() -> int:
296 github = GitHub(os.environ["GITHUB_REPOSITORY"], os.environ["GITHUB_TOKEN"])
297 number = os.environ.get("PR_NUMBER", "").strip()
298 if number:
299 return 0 if run_gate(github, int(number), enforce=True) else 1
300 for raw in github.paged("/pulls?state=open"):
301 run_gate(github, raw["number"], enforce=False)
302 return 0
303
304
305 if __name__ == "__main__":
306 sys.exit(main())
@@ -0,0 +1,306 @@
1"""Checks whether a pull request is ready for review (CONTRIBUTING.md, "When a PR is ready for review").
2
3Run by .github/workflows/pr-gate.yml under pull_request_target: it reads the PR as data
4through the API and never checks out or runs code from the PR.
5"""
6
7import json
8import os
9import re
10import sys
11import urllib.error
12import urllib.parse
13import urllib.request
14from dataclasses import dataclass, field
15from typing import Any
16
17TITLE_PATTERN = re.compile(r"^(feat|fix|perf|refactor|docs|test|chore|ci|build)(\([a-z0-9-]+\))?!?: \S")
18UI_PATH_PATTERN = re.compile(r"^crates/app/src/(views|settings|components|widgets)/|^crates/app/src/[^/]+_view\.rs$|/locales/")
19IMAGE_PATTERN = re.compile(r"!\[[^\]]*\]\(|<img\s|<video\s|github\.com/user-attachments/|\.(png|jpe?g|gif|webp|mp4|webm)\b", re.IGNORECASE)
20ISSUE_REFERENCE_PATTERN = re.compile(
21 r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?):?\s+(?:https://github\.com/danieldaeschle/rusty-teams/issues/|#)(\d+)", re.IGNORECASE
22)
23NO_VISUAL_CHECKBOX_PATTERN = re.compile(r"^\s*[-*]\s*\[[xX]\]\s*no visible change", re.IGNORECASE | re.MULTILINE)
24FORBIDDEN_PATH_PATTERN = re.compile(r"^(openspec|\.specify|\.kiro)/")
25WINDOWS_CODE_PATTERN = re.compile(r"^\+.*(cfg\((all\()?windows|target_os\s*=\s*\"windows\")", re.MULTILINE)
26WINDOWS_PATH_PATTERN = re.compile(r"(^|/)(win32|windows)(/|_[a-z]+\.rs$)|_win(dows)?\.rs$")
27LOCKFILE_NAMES =("Cargo.lock", "package-lock.json", "pnpm-lock.yaml", "yarn.lock")
28
29MAX_CHANGED_LINES = 400
30MIN_PROBLEM_CHARACTERS = 80
31MIN_REVIEW_LINES = 2
32REQUIRED_SECTIONS = ("Summary", "AI model", "Tests", "Review")
33SECTION_ALIASES = {"tests": ("test plan", "testing", "test")}
34
35LABEL_NEEDS_INFO = "status: needs info"
36LABEL_NEEDS_REVIEW = "status: needs review"
37STATUS_LABEL_PREFIX = "status: "
38EXEMPT_ASSOCIATIONS = ("OWNER", "MEMBER", "COLLABORATOR")
39LABEL_ACCEPTED = "status: accepted"
40LABEL_NO_VISUAL = "gate: no visual"
41LABEL_SKIP = "gate: skip"
42
43COMMENT_MARKER = "<!-- pr-gate -->"
44
45
46@dataclass
47class ChangedFile:
48 path: str
49 additions: int = 0
50 deletions: int = 0
51 patch: str = ""
52
53
54@dataclass
55class PullRequest:
56 title: str
57 body: str
58 labels: list[str] = field(default_factory=list)
59 files: list[ChangedFile] = field(default_factory=list)
60 linked_issue_labels: dict[int, list[str]] = field(default_factory=dict)
61
62
63def strip_comments(text: str) -> str:
64 return re.sub(r"<!--.*?-->", "", text or "", flags=re.DOTALL)
65
66
67def parse_sections(body: str) -> dict[str, str]:
68 sections: dict[str, str] = {}
69 current_heading = None
70 current_lines: list[str] = []
71 for line in strip_comments(body).splitlines():
72 heading = re.match(r"^##\s+(.+?)\s*$", line)
73 if heading:
74 if current_heading is not None:
75 sections[current_heading] = "\n".join(current_lines).strip()
76 current_heading = heading.group(1).strip().lower()
77 current_lines = []
78 elif current_heading is not None:
79 current_lines.append(line)
80 if current_heading is not None:
81 sections[current_heading] = "\n".join(current_lines).strip()
82 return sections
83
84
85def find_section(sections: dict[str, str], name: str) -> str | None:
86 names = (name.lower(), *SECTION_ALIASES.get(name.lower(), ()))
87 for heading, content in sections.items():
88 if any(heading == wanted or heading.startswith(wanted + " ") or heading.startswith(wanted + ":") for wanted in names):
89 return content
90 return None
91
92
93def linked_issue_numbers(body: str) -> list[int]:
94 return sorted({int(number) for number in ISSUE_REFERENCE_PATTERN.findall(strip_comments(body))})
95
96
97def changed_lines(files: list[ChangedFile]) -> int:
98 return sum(changed.additions + changed.deletions for changed in files if changed.path.rsplit("/", 1)[-1] not in LOCKFILE_NAMES)
99
100
101def title_type(title: str) -> str:
102 return title.split("(", 1)[0].split(":", 1)[0].split("!", 1)[0].strip()
103
104
105def non_empty_lines(text: str) -> list[str]:
106 return [line for line in text.splitlines() if line.strip()]
107
108
109def check(pull_request: PullRequest) -> list[str]:
110 """Returns one line per missing item, empty when the PR is ready for review."""
111 missing: list[str] = []
112 sections = parse_sections(pull_request.body)
113 issue_numbers = linked_issue_numbers(pull_request.body)
114 paths = [changed.path for changed in pull_request.files]
115
116 if not TITLE_PATTERN.match(pull_request.title):
117 missing.append("**Title**: use `type(scope): message` from the user's view, e.g. `fix(chat): a sent image no longer blinks`.")
118
119 for name in REQUIRED_SECTIONS:
120 if not find_section(sections, name):
121 missing.append(f"**{name}**: the `## {name}` section is missing or empty.")
122
123 if not issue_numbers:
124 problem = find_section(sections, "Problem") or ""
125 if len(problem) < MIN_PROBLEM_CHARACTERS:
126 missing.append(
127 "**Problem**: no linked issue (`Closes #123`), so a `## Problem` section must describe it: "
128 "what is wrong or missing, when a user hits it (steps or when/then) and what should happen instead."
129 )
130
131 size = changed_lines(pull_request.files)
132 needs_accepted_issue = title_type(pull_request.title) == "feat" or size > MAX_CHANGED_LINES
133 if needs_accepted_issue:
134 accepted = any(LABEL_ACCEPTED in pull_request.linked_issue_labels.get(number, []) for number in issue_numbers)
135 if not accepted:
136 reason = "a feature" if title_type(pull_request.title) == "feat" else f"{size} changed lines (over {MAX_CHANGED_LINES})"
137 missing.append(
138 f"**Issue first**: this PR is {reason}. Link an issue that a maintainer marked `{LABEL_ACCEPTED}`, "
139 "or split the change into smaller PRs."
140 )
141
142 if any(UI_PATH_PATTERN.search(path) for path in paths) and LABEL_NO_VISUAL not in pull_request.labels:
143 screenshot = find_section(sections, "Screenshot") or ""
144 has_image = bool(IMAGE_PATTERN.search(strip_comments(pull_request.body)))
145 if not has_image and not NO_VISUAL_CHECKBOX_PATTERN.search(screenshot):
146 missing.append(
147 "**Screenshot**: the change touches UI code. Add a shot of the changed area taken with `--demo` data, "
148 "or tick `No visible change` and say why."
149 )
150
151 tests = find_section(sections, "Tests") or ""
152 touches_windows = any(WINDOWS_CODE_PATTERN.search(changed.patch) or WINDOWS_PATH_PATTERN.search(changed.path) for changed in pull_request.files)
153 if tests and touches_windows and "windows" not in tests.lower():
154 missing.append("**Tests**: the change touches Windows-only code. Say whether you built and ran it on Windows.")
155
156 review = find_section(sections, "Review") or ""
157 if review and len(non_empty_lines(review)) < MIN_REVIEW_LINES:
158 missing.append("**Review**: list at least two independent reviews of the diff and what happened to each finding (AGENTS.md).")
159
160 forbidden = sorted({path.split("/", 1)[0] for path in paths if FORBIDDEN_PATH_PATTERN.match(path)})
161 if forbidden:
162 missing.append(f"**Scope**: remove planning folders from the PR: {', '.join(f'`{name}/`' for name in forbidden)}.")
163
164 if any(path.startswith("vendor/") for path in paths) and "vendor" not in strip_comments(pull_request.body).lower():
165 missing.append("**Scope**: the PR changes `vendor/`. Say in the summary why the fix belongs in the fork.")
166
167 return missing
168
169
170def render_comment(missing: list[str]) -> str:
171 if not missing:
172 return f"{COMMENT_MARKER}\n**PR gate: ready for review.** Thanks, a maintainer will take a look."
173 items = "\n".join(f"- [ ] {item}" for item in missing)
174 return (
175 f"{COMMENT_MARKER}\n**PR gate: not ready for review yet.** Please add:\n\n{items}\n\n"
176 "Edit the description or push, and this comment updates itself. When everything is there, mark the PR "
177 "ready for review. The rules are in CONTRIBUTING.md under \"When a PR is ready for review\". "
178 f"A PR that stays `{LABEL_NEEDS_INFO}` for 14 days is closed; it can be reopened any time."
179 )
180
181
182class GitHub:
183 def __init__(self, repository: str, token: str):
184 self.base_url = f"https://api.github.com/repos/{repository}"
185 self.token = token
186
187 def request(self, method: str, url: str, payload=None) -> Any:
188 full_url = url if url.startswith("https://") else self.base_url + url
189 data = json.dumps(payload).encode() if payload is not None else None
190 request = urllib.request.Request(full_url, data=data, method=method)
191 request.add_header("Authorization", f"Bearer {self.token}")
192 request.add_header("Accept", "application/vnd.github+json")
193 request.add_header("X-GitHub-Api-Version", "2022-11-28")
194 with urllib.request.urlopen(request) as response:
195 content = response.read()
196 return json.loads(content) if content else None
197
198 def paged(self, url: str) -> list:
199 results, page = [], 1
200 while True:
201 separator = "&" if "?" in url else "?"
202 batch = self.request("GET", f"{url}{separator}per_page=100&page={page}")
203 results.extend(batch)
204 if len(batch) < 100:
205 return results
206 page += 1
207
208
209def load_pull_request(github: GitHub, number: int) -> tuple[dict, PullRequest]:
210 raw = github.request("GET", f"/pulls/{number}")
211 files = [
212 ChangedFile(item["filename"], item.get("additions", 0), item.get("deletions", 0), item.get("patch", ""))
213 for item in github.paged(f"/pulls/{number}/files")
214 ]
215 body = raw.get("body") or ""
216 issue_labels: dict[int, list[str]] = {}
217 for issue_number in linked_issue_numbers(body):
218 try:
219 issue = github.request("GET", f"/issues/{issue_number}")
220 issue_labels[issue_number] = [label["name"] for label in issue.get("labels", [])]
221 except urllib.error.HTTPError:
222 issue_labels[issue_number] = []
223 labels = [label["name"] for label in raw.get("labels", [])]
224 return raw, PullRequest(raw["title"], body, labels, files, issue_labels)
225
226
227def is_exempt(raw: dict, labels: list[str]) -> bool:
228 return LABEL_SKIP in labels or raw["user"]["type"] == "Bot" or raw.get("author_association") in EXEMPT_ASSOCIATIONS
229
230
231def upsert_comment(github: GitHub, number: int, text: str) -> None:
232 for comment in github.paged(f"/issues/{number}/comments"):
233 if COMMENT_MARKER in (comment.get("body") or "") and comment["user"]["type"] == "Bot":
234 if comment["body"] != text:
235 github.request("PATCH", f"/issues/comments/{comment['id']}", {"body": text})
236 return
237 github.request("POST", f"/issues/{number}/comments", {"body": text})
238
239
240def add_label(github: GitHub, number: int, labels: list[str], name: str) -> None:
241 if name not in labels:
242 github.request("POST", f"/issues/{number}/labels", {"labels": [name]})
243
244
245def remove_label(github: GitHub, number: int, labels: list[str], name: str) -> None:
246 if name not in labels:
247 return
248 try:
249 github.request("DELETE", f"/issues/{number}/labels/{urllib.parse.quote(name)}")
250 except urllib.error.HTTPError as error:
251 if error.code != 404:
252 raise
253
254
255def update_labels(github: GitHub, number: int, labels: list[str], ready: bool) -> None:
256 """Sets only the gate's own labels; the maintainers' status labels stay as they are."""
257 if not ready:
258 add_label(github, number, labels, LABEL_NEEDS_INFO)
259 return
260 remove_label(github, number, labels, LABEL_NEEDS_INFO)
261 if not any(label.startswith(STATUS_LABEL_PREFIX) and label != LABEL_NEEDS_INFO for label in labels):
262 add_label(github, number, labels, LABEL_NEEDS_REVIEW)
263
264
265def convert_to_draft(github: GitHub, node_id: str) -> None:
266 query = "mutation($id: ID!) { convertPullRequestToDraft(input: {pullRequestId: $id}) { clientMutationId } }"
267 try:
268 github.request("POST", "https://api.github.com/graphql", {"query": query, "variables": {"id": node_id}})
269 except urllib.error.HTTPError as error:
270 print(f"::warning::could not convert to draft: {error}")
271
272
273def run_gate(github: GitHub, number: int, enforce: bool) -> bool:
274 raw, pull_request = load_pull_request(github, number)
275 if raw["state"] != "open":
276 return True
277 if is_exempt(raw, pull_request.labels):
278 print(f"#{number}: exempt")
279 return True
280 is_draft = bool(raw.get("draft"))
281 if is_draft and enforce and LABEL_NEEDS_INFO not in pull_request.labels:
282 print(f"#{number}: draft, gate runs when it is marked ready for review")
283 return True
284 missing = check(pull_request)
285 upsert_comment(github, number, render_comment(missing))
286 update_labels(github, number, pull_request.labels, ready=not missing)
287 if missing and enforce and not is_draft:
288 convert_to_draft(github, raw["node_id"])
289 print(f"#{number}: {'ready' if not missing else 'missing ' + str(len(missing))}")
290 for item in missing:
291 print(f" - {item}")
292 return is_draft or not missing
293
294
295def main() -> int:
296 github = GitHub(os.environ["GITHUB_REPOSITORY"], os.environ["GITHUB_TOKEN"])
297 number = os.environ.get("PR_NUMBER", "").strip()
298 if number:
299 return 0 if run_gate(github, int(number), enforce=True) else 1
300 for raw in github.paged("/pulls?state=open"):
301 run_gate(github, raw["number"], enforce=False)
302 return 0
303
304
305if __name__ == "__main__":
306 sys.exit(main())
.github/scripts/test_pr_gate.py added +116 −0
@@ -0,0 +1,116 @@
1 import unittest
2
3 from pr_gate import LABEL_ACCEPTED, LABEL_NO_VISUAL, ChangedFile, PullRequest, check, linked_issue_numbers, parse_sections
4
5 GOOD_BODY = """## Summary
6
7 A sent image no longer blinks after sending.
8
9 ## Problem
10
11 <!-- template hint -->
12 After sending an image the bubble shows empty for 200 ms and then the image again.
13 Expected: the image stays visible the whole time.
14
15 ## AI model
16
17 Claude Code, Opus 5.5
18
19 ## Tests
20
21 Ran: `cargo test -p app image_cache`. Not run: Windows.
22
23 ## Review
24
25 - `/code-review medium`: 1 finding, fixed
26 - fresh agent session: no findings
27 """
28
29 BACKEND_FILE = ChangedFile("crates/chatsvc/src/window.rs", 20, 5)
30 UI_FILE = ChangedFile("crates/app/src/views/conversation.rs", 10, 2)
31
32
33 def make(title="fix(chat): a sent image no longer blinks", body=GOOD_BODY, files=None, labels=None, issue_labels=None):
34 return PullRequest(title, body, labels or [], files if files is not None else [BACKEND_FILE], issue_labels or {})
35
36
37 def missing_keys(pull_request):
38 return [item.split("**")[1] for item in check(pull_request)]
39
40
41 class SectionTests(unittest.TestCase):
42 def test_comments_do_not_count_as_content(self):
43 sections = parse_sections("## Summary\n<!-- what and why -->\n## AI model\nNone")
44 self.assertEqual(sections["summary"], "")
45 self.assertEqual(sections["ai model"], "None")
46
47 def test_test_plan_counts_as_tests(self):
48 self.assertEqual(check(make(body=GOOD_BODY.replace("## Tests", "## Test plan"))), [])
49
50 def test_issue_reference_only_with_closing_keyword(self):
51 self.assertEqual(linked_issue_numbers("Closes #12, fixes #3, see #99"), [3, 12])
52 self.assertEqual(linked_issue_numbers("<!-- Closes #123 -->"), [])
53 self.assertEqual(linked_issue_numbers("Fixes: https://github.com/danieldaeschle/rusty-teams/issues/42"), [42])
54
55
56 class GateTests(unittest.TestCase):
57 def test_good_pr_passes(self):
58 self.assertEqual(check(make()), [])
59
60 def test_bad_title(self):
61 self.assertIn("Title", missing_keys(make(title="Bound audio capture lifetime")))
62
63 def test_untouched_template_fails_every_section(self):
64 template = "## Summary\n<!-- x -->\n## AI model\n<!-- x -->\n## Review\n<!-- x -->"
65 keys = missing_keys(make(body=template))
66 for name in ("Summary", "AI model", "Tests", "Review", "Problem"):
67 self.assertIn(name, keys)
68
69 def test_issue_link_replaces_problem(self):
70 body = GOOD_BODY.replace("## Problem", "Closes #5\n\n## Notes")
71 self.assertEqual(check(make(body=body)), [])
72
73 def test_feature_needs_accepted_issue(self):
74 title = "feat(chat): pin a message"
75 self.assertIn("Issue first", missing_keys(make(title=title)))
76 body = GOOD_BODY + "\nCloses #7\n"
77 self.assertIn("Issue first", missing_keys(make(title=title, body=body, issue_labels={7: ["enhancement"]})))
78 self.assertEqual(check(make(title=title, body=body, issue_labels={7: [LABEL_ACCEPTED]})), [])
79
80 def test_large_fix_needs_accepted_issue_but_lockfile_does_not_count(self):
81 large = [ChangedFile("crates/chatsvc/src/window.rs", 350, 100)]
82 self.assertIn("Issue first", missing_keys(make(files=large)))
83 lock = [BACKEND_FILE, ChangedFile("Cargo.lock", 900, 900)]
84 self.assertEqual(check(make(files=lock)), [])
85
86 def test_ui_change_needs_screenshot(self):
87 self.assertIn("Screenshot", missing_keys(make(files=[UI_FILE])))
88 with_image = GOOD_BODY + "\n## Screenshot\n\n![chat](https://github.com/user-attachments/assets/abc)\n"
89 self.assertEqual(check(make(body=with_image, files=[UI_FILE])), [])
90
91 def test_ui_change_without_visible_change(self):
92 ticked = GOOD_BODY + "\n## Screenshot\n\n- [x] No visible change: only the cache key moved\n"
93 self.assertEqual(check(make(body=ticked, files=[UI_FILE])), [])
94 self.assertEqual(check(make(files=[UI_FILE], labels=[LABEL_NO_VISUAL])), [])
95
96 def test_windows_code_needs_windows_note(self):
97 windows_file = ChangedFile("crates/calling/src/device.rs", 5, 1, "@@\n+#[cfg(windows)]\n+fn open() {}")
98 body = GOOD_BODY.replace("Not run: Windows.", "")
99 self.assertIn("Tests", missing_keys(make(body=body, files=[windows_file])))
100 self.assertEqual(check(make(files=[windows_file])), [])
101
102 def test_gpui_window_file_is_not_windows_code(self):
103 body = GOOD_BODY.replace("Not run: Windows.", "")
104 self.assertEqual(check(make(body=body, files=[ChangedFile("crates/chatsvc/src/window.rs", 1, 1)])), [])
105
106 def test_single_review_line_is_not_enough(self):
107 body = GOOD_BODY.replace("- fresh agent session: no findings\n", "")
108 self.assertIn("Review", missing_keys(make(body=body)))
109
110 def test_planning_folder_and_vendor(self):
111 files = [BACKEND_FILE, ChangedFile("openspec/changes/x.md", 10, 0), ChangedFile("vendor/gpui/src/a.rs", 1, 1)]
112 self.assertEqual(missing_keys(make(files=files)), ["Scope", "Scope"])
113
114
115 if __name__ == "__main__":
116 unittest.main()
@@ -0,0 +1,116 @@
1import unittest
2
3from pr_gate import LABEL_ACCEPTED, LABEL_NO_VISUAL, ChangedFile, PullRequest, check, linked_issue_numbers, parse_sections
4
5GOOD_BODY = """## Summary
6
7A sent image no longer blinks after sending.
8
9## Problem
10
11<!-- template hint -->
12After sending an image the bubble shows empty for 200 ms and then the image again.
13Expected: the image stays visible the whole time.
14
15## AI model
16
17Claude Code, Opus 5.5
18
19## Tests
20
21Ran: `cargo test -p app image_cache`. Not run: Windows.
22
23## Review
24
25- `/code-review medium`: 1 finding, fixed
26- fresh agent session: no findings
27"""
28
29BACKEND_FILE = ChangedFile("crates/chatsvc/src/window.rs", 20, 5)
30UI_FILE = ChangedFile("crates/app/src/views/conversation.rs", 10, 2)
31
32
33def make(title="fix(chat): a sent image no longer blinks", body=GOOD_BODY, files=None, labels=None, issue_labels=None):
34 return PullRequest(title, body, labels or [], files if files is not None else [BACKEND_FILE], issue_labels or {})
35
36
37def missing_keys(pull_request):
38 return [item.split("**")[1] for item in check(pull_request)]
39
40
41class SectionTests(unittest.TestCase):
42 def test_comments_do_not_count_as_content(self):
43 sections = parse_sections("## Summary\n<!-- what and why -->\n## AI model\nNone")
44 self.assertEqual(sections["summary"], "")
45 self.assertEqual(sections["ai model"], "None")
46
47 def test_test_plan_counts_as_tests(self):
48 self.assertEqual(check(make(body=GOOD_BODY.replace("## Tests", "## Test plan"))), [])
49
50 def test_issue_reference_only_with_closing_keyword(self):
51 self.assertEqual(linked_issue_numbers("Closes #12, fixes #3, see #99"), [3, 12])
52 self.assertEqual(linked_issue_numbers("<!-- Closes #123 -->"), [])
53 self.assertEqual(linked_issue_numbers("Fixes: https://github.com/danieldaeschle/rusty-teams/issues/42"), [42])
54
55
56class GateTests(unittest.TestCase):
57 def test_good_pr_passes(self):
58 self.assertEqual(check(make()), [])
59
60 def test_bad_title(self):
61 self.assertIn("Title", missing_keys(make(title="Bound audio capture lifetime")))
62
63 def test_untouched_template_fails_every_section(self):
64 template = "## Summary\n<!-- x -->\n## AI model\n<!-- x -->\n## Review\n<!-- x -->"
65 keys = missing_keys(make(body=template))
66 for name in ("Summary", "AI model", "Tests", "Review", "Problem"):
67 self.assertIn(name, keys)
68
69 def test_issue_link_replaces_problem(self):
70 body = GOOD_BODY.replace("## Problem", "Closes #5\n\n## Notes")
71 self.assertEqual(check(make(body=body)), [])
72
73 def test_feature_needs_accepted_issue(self):
74 title = "feat(chat): pin a message"
75 self.assertIn("Issue first", missing_keys(make(title=title)))
76 body = GOOD_BODY + "\nCloses #7\n"
77 self.assertIn("Issue first", missing_keys(make(title=title, body=body, issue_labels={7: ["enhancement"]})))
78 self.assertEqual(check(make(title=title, body=body, issue_labels={7: [LABEL_ACCEPTED]})), [])
79
80 def test_large_fix_needs_accepted_issue_but_lockfile_does_not_count(self):
81 large = [ChangedFile("crates/chatsvc/src/window.rs", 350, 100)]
82 self.assertIn("Issue first", missing_keys(make(files=large)))
83 lock = [BACKEND_FILE, ChangedFile("Cargo.lock", 900, 900)]
84 self.assertEqual(check(make(files=lock)), [])
85
86 def test_ui_change_needs_screenshot(self):
87 self.assertIn("Screenshot", missing_keys(make(files=[UI_FILE])))
88 with_image = GOOD_BODY + "\n## Screenshot\n\n![chat](https://github.com/user-attachments/assets/abc)\n"
89 self.assertEqual(check(make(body=with_image, files=[UI_FILE])), [])
90
91 def test_ui_change_without_visible_change(self):
92 ticked = GOOD_BODY + "\n## Screenshot\n\n- [x] No visible change: only the cache key moved\n"
93 self.assertEqual(check(make(body=ticked, files=[UI_FILE])), [])
94 self.assertEqual(check(make(files=[UI_FILE], labels=[LABEL_NO_VISUAL])), [])
95
96 def test_windows_code_needs_windows_note(self):
97 windows_file = ChangedFile("crates/calling/src/device.rs", 5, 1, "@@\n+#[cfg(windows)]\n+fn open() {}")
98 body = GOOD_BODY.replace("Not run: Windows.", "")
99 self.assertIn("Tests", missing_keys(make(body=body, files=[windows_file])))
100 self.assertEqual(check(make(files=[windows_file])), [])
101
102 def test_gpui_window_file_is_not_windows_code(self):
103 body = GOOD_BODY.replace("Not run: Windows.", "")
104 self.assertEqual(check(make(body=body, files=[ChangedFile("crates/chatsvc/src/window.rs", 1, 1)])), [])
105
106 def test_single_review_line_is_not_enough(self):
107 body = GOOD_BODY.replace("- fresh agent session: no findings\n", "")
108 self.assertIn("Review", missing_keys(make(body=body)))
109
110 def test_planning_folder_and_vendor(self):
111 files = [BACKEND_FILE, ChangedFile("openspec/changes/x.md", 10, 0), ChangedFile("vendor/gpui/src/a.rs", 1, 1)]
112 self.assertEqual(missing_keys(make(files=files)), ["Scope", "Scope"])
113
114
115if __name__ == "__main__":
116 unittest.main()
.github/workflows/pr-gate.yml added +37 −0
@@ -0,0 +1,37 @@
1 # Checks that a pull request is ready for review (CONTRIBUTING.md, "When a PR is ready for review").
2 # pull_request_target so it also runs on forks of first-time contributors without approval.
3 # It checks out main only and reads the PR as data through the API: never check out or run PR code here.
4 name: PR gate
5
6 on:
7 pull_request_target:
8 types: [opened, edited, synchronize, reopened, ready_for_review, labeled, unlabeled]
9 workflow_dispatch:
10
11 permissions:
12 contents: read
13 issues: write
14 pull-requests: write
15
16 concurrency:
17 group: pr-gate-${{ github.event.pull_request.number || 'all' }}
18 cancel-in-progress: true
19
20 jobs:
21 gate:
22 name: Ready for review
23 runs-on: ubuntu-latest
24 timeout-minutes: 10
25 steps:
26 - uses: actions/checkout@v6
27 with:
28 ref: ${{ github.event.repository.default_branch }}
29 persist-credentials: false
30 sparse-checkout: .github/scripts
31
32 - name: Check
33 env:
34 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
35 PR_NUMBER: ${{ github.event.pull_request.number }}
36 run: python3 -I .github/scripts/pr_gate.py
37
@@ -0,0 +1,37 @@
1# Checks that a pull request is ready for review (CONTRIBUTING.md, "When a PR is ready for review").
2# pull_request_target so it also runs on forks of first-time contributors without approval.
3# It checks out main only and reads the PR as data through the API: never check out or run PR code here.
4name: PR gate
5
6on:
7 pull_request_target:
8 types: [opened, edited, synchronize, reopened, ready_for_review, labeled, unlabeled]
9 workflow_dispatch:
10
11permissions:
12 contents: read
13 issues: write
14 pull-requests: write
15
16concurrency:
17 group: pr-gate-${{ github.event.pull_request.number || 'all' }}
18 cancel-in-progress: true
19
20jobs:
21 gate:
22 name: Ready for review
23 runs-on: ubuntu-latest
24 timeout-minutes: 10
25 steps:
26 - uses: actions/checkout@v6
27 with:
28 ref: ${{ github.event.repository.default_branch }}
29 persist-credentials: false
30 sparse-checkout: .github/scripts
31
32 - name: Check
33 env:
34 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
35 PR_NUMBER: ${{ github.event.pull_request.number }}
36 run: python3 -I .github/scripts/pr_gate.py
37
.github/workflows/pr-title.yml deleted +0 −26
@@ -1,26 +0,0 @@
1 # A squash merge uses the PR title as the commit subject, and the release notes
2 # (cliff.toml) show it as is. CONTRIBUTING.md has the format.
3 name: PR title
4
5 on:
6 pull_request:
7 types: [opened, edited, reopened, synchronize]
8
9 permissions: {}
10
11 jobs:
12 title:
13 name: Conventional title
14 runs-on: ubuntu-latest
15 steps:
16 - name: Check
17 env:
18 TITLE: ${{ github.event.pull_request.title }}
19 run: |
20 pattern='^(feat|fix|perf|refactor|docs|test|chore|ci|build)(\([a-z0-9-]+\))?!?: [^[:space:]].*$'
21 if [[ "$TITLE" =~ $pattern ]]; then
22 echo "ok: $TITLE"
23 else
24 echo "::error::PR title must look like 'fix(chat): a sent image no longer blinks' (type(scope): message, no emoji). Got: $TITLE"
25 exit 1
26 fi
@@ -1,26 +0,0 @@
1# A squash merge uses the PR title as the commit subject, and the release notes
2# (cliff.toml) show it as is. CONTRIBUTING.md has the format.
3name: PR title
4
5on:
6 pull_request:
7 types: [opened, edited, reopened, synchronize]
8
9permissions: {}
10
11jobs:
12 title:
13 name: Conventional title
14 runs-on: ubuntu-latest
15 steps:
16 - name: Check
17 env:
18 TITLE: ${{ github.event.pull_request.title }}
19 run: |
20 pattern='^(feat|fix|perf|refactor|docs|test|chore|ci|build)(\([a-z0-9-]+\))?!?: [^[:space:]].*$'
21 if [[ "$TITLE" =~ $pattern ]]; then
22 echo "ok: $TITLE"
23 else
24 echo "::error::PR title must look like 'fix(chat): a sent image no longer blinks' (type(scope): message, no emoji). Got: $TITLE"
25 exit 1
26 fi
.github/workflows/stale-prs.yml added +26 −0
@@ -0,0 +1,26 @@
1 # Closes pull requests that stayed "status: needs info" (set by pr-gate.yml) for 14 days.
2 name: Stale PRs
3
4 on:
5 schedule:
6 - cron: "17 4 * * *"
7 workflow_dispatch:
8
9 permissions:
10 pull-requests: write
11 issues: write
12
13 jobs:
14 stale:
15 runs-on: ubuntu-latest
16 steps:
17 - uses: actions/stale@v11
18 with:
19 only-pr-labels: "status: needs info"
20 days-before-issue-stale: -1
21 days-before-issue-close: -1
22 days-before-pr-stale: 10
23 days-before-pr-close: 4
24 stale-pr-label: stale
25 stale-pr-message: "This PR is still missing what the PR gate comment lists. It closes in 4 days unless it is updated."
26 close-pr-message: "Closed because the PR gate items stayed open for 14 days. Reopen it any time once they are added."
@@ -0,0 +1,26 @@
1# Closes pull requests that stayed "status: needs info" (set by pr-gate.yml) for 14 days.
2name: Stale PRs
3
4on:
5 schedule:
6 - cron: "17 4 * * *"
7 workflow_dispatch:
8
9permissions:
10 pull-requests: write
11 issues: write
12
13jobs:
14 stale:
15 runs-on: ubuntu-latest
16 steps:
17 - uses: actions/stale@v11
18 with:
19 only-pr-labels: "status: needs info"
20 days-before-issue-stale: -1
21 days-before-issue-close: -1
22 days-before-pr-stale: 10
23 days-before-pr-close: 4
24 stale-pr-label: stale
25 stale-pr-message: "This PR is still missing what the PR gate comment lists. It closes in 4 days unless it is updated."
26 close-pr-message: "Closed because the PR gate items stayed open for 14 days. Reopen it any time once they are added."
.github/workflows/test.yml +12 −0
@@ -21,6 +21,18 @@ env:
21 21 CARGO_TERM_COLOR: always
22 22
23 23 jobs:
24 pr-gate:
25 name: PR gate rules
26 runs-on: ubuntu-latest
27 timeout-minutes: 5
28 steps:
29 - uses: actions/checkout@v6
30 with:
31 sparse-checkout: .github/scripts
32
33 - name: Tests
34 run: cd .github/scripts && python3 -m unittest -v
35
24 36 linux:
25 37 name: Linux
26 38 runs-on: ubuntu-latest
@@ -21,6 +21,18 @@ env:
21 CARGO_TERM_COLOR: always
21 CARGO_TERM_COLOR: always
22
22
23jobs:
23jobs:
24 pr-gate:
25 name: PR gate rules
26 runs-on: ubuntu-latest
27 timeout-minutes: 5
28 steps:
29 - uses: actions/checkout@v6
30 with:
31 sparse-checkout: .github/scripts
32
33 - name: Tests
34 run: cd .github/scripts && python3 -m unittest -v
35
24 linux:
36 linux:
25 name: Linux
37 name: Linux
26 runs-on: ubuntu-latest
38 runs-on: ubuntu-latest
AGENTS.md +2 −1
@@ -31,4 +31,5 @@ Code under `cfg(windows)` is not compiled by tests on Linux or macOS. CI builds
31 31 1. Commit, run `git fetch origin`, and get at least two independent reviews of `git diff origin/main...HEAD`.
32 32 2. A reviewer must not have written the change. Use a fresh agent session, a subagent, or a review command such as `/code-review` or `/review`. On Copilot, a Copilot code review on the draft PR counts as one.
33 33 3. Fix or answer every valid finding. In the PR's Review section, write one line per review (what ran it), then one line per finding: fixed, or not fixed and why.
34 4. Commit and PR title: `type(scope): message`. Type is one of `feat fix perf refactor docs test chore ci build`, the scope is lowercase, no emoji. Write it from the user's view. It becomes the release note line.
34 4. Check the PR against the table in CONTRIBUTING.md, "When a PR is ready for review". The PR gate check enforces it.
35 5. Commit and PR title: `type(scope): message`. Type is one of `feat fix perf refactor docs test chore ci build`, the scope is lowercase, no emoji. Write it from the user's view. It becomes the release note line.
@@ -31,4 +31,5 @@ Code under `cfg(windows)` is not compiled by tests on Linux or macOS. CI builds
311. Commit, run `git fetch origin`, and get at least two independent reviews of `git diff origin/main...HEAD`.
311. Commit, run `git fetch origin`, and get at least two independent reviews of `git diff origin/main...HEAD`.
322. A reviewer must not have written the change. Use a fresh agent session, a subagent, or a review command such as `/code-review` or `/review`. On Copilot, a Copilot code review on the draft PR counts as one.
322. A reviewer must not have written the change. Use a fresh agent session, a subagent, or a review command such as `/code-review` or `/review`. On Copilot, a Copilot code review on the draft PR counts as one.
333. Fix or answer every valid finding. In the PR's Review section, write one line per review (what ran it), then one line per finding: fixed, or not fixed and why.
333. Fix or answer every valid finding. In the PR's Review section, write one line per review (what ran it), then one line per finding: fixed, or not fixed and why.
344. Commit and PR title: `type(scope): message`. Type is one of `feat fix perf refactor docs test chore ci build`, the scope is lowercase, no emoji. Write it from the user's view. It becomes the release note line.
344. Check the PR against the table in CONTRIBUTING.md, "When a PR is ready for review". The PR gate check enforces it.
355. Commit and PR title: `type(scope): message`. Type is one of `feat fix perf refactor docs test chore ci build`, the scope is lowercase, no emoji. Write it from the user's view. It becomes the release note line.
CONTRIBUTING.md +21 −3
@@ -8,7 +8,7 @@ Most of this code is written with AI agents, and that is welcome here. Just say
8 8 |---|---|
9 9 | 1 | Read [GUARDRAILS.md](GUARDRAILS.md): where the app must match Teams and where it may differ. It wins over any habit. |
10 10 | 2 | Check [ROADMAP.md](ROADMAP.md), mainly "Out of scope". Features listed there are not merged. |
11 | 3 | Search open pull requests and issues for the same topic. For anything larger than a fix, open an issue first and wait for a yes. |
11 | 3 | Search open pull requests and issues for the same topic. For a feature or anything over 400 changed lines, open an issue first and wait for the `status: accepted` label. |
12 12 | 4 | Read the notes under [docs/decisions/](docs/decisions/README.md) for the area you touch. |
13 13
14 14 ## AI use
@@ -24,12 +24,30 @@ Most of this code is written with AI agents, and that is welcome here. Just say
24 24 ## Pull requests
25 25
26 26 - One topic per pull request. No unrelated refactors, no formatting of files you did not change.
27 - The template asks for four things: a summary, the AI model, the reviews that ran, and a screenshot for UI changes (taken with demo data).
27 - Fill in the template. The PR gate below checks it.
28 28 - CI runs the tests on Linux and Windows for every pull request.
29 - Commit and PR title format: `type(scope): message`, with `type` one of `feat`, `fix`, `perf`, `refactor`, `docs`, `test`, `chore`, `ci`, `build`, a lowercase scope and no emoji. CI checks the PR title.
29 - Commit and PR title format: `type(scope): message`, with `type` one of `feat`, `fix`, `perf`, `refactor`, `docs`, `test`, `chore`, `ci`, `build`, a lowercase scope and no emoji.
30 30 - The PR title becomes the squash commit and a line in the release notes (`feat` under New, `fix` under Fixes). Write it as a user would read it: `fix(chat): a sent image no longer blinks`, not `fix(chat): handle download race`.
31 31 - Rebase on `main` instead of merging it in. Answer actionable review comments or say that you will not.
32 32
33 ## When a PR is ready for review
34
35 A bot check (`PR gate`) runs on every PR that is not a draft. Until it passes, the PR gets `status: needs info`, a comment that lists what is missing, and goes back to draft. It updates on every edit and push. A PR that stays `status: needs info` for 14 days is closed and can be reopened any time.
36
37 | Gate | Rule |
38 |---|---|
39 | Title | `type(scope): message`, from the user's view |
40 | Template | Summary, AI model, Tests and Review filled in, not just the hints |
41 | Problem | No `Closes #123`: a Problem section says what is wrong or missing, when a user hits it (steps or when/then) and what should happen instead |
42 | Issue first | A `feat` PR or more than 400 changed lines (lockfiles do not count) links an issue labelled `status: accepted` |
43 | Screenshot | A change to UI code (`crates/app/src/views/`, `settings/`, locales) shows the changed area with demo data, or ticks "No visible change" with a reason |
44 | Tests | What ran and what did not. A change to Windows-only code says whether it was built on Windows |
45 | Review | At least two independent reviews, each finding fixed or answered |
46 | Scope | No planning folders (`openspec/` and the like). A change to `vendor/` says why in the description |
47 | Open PRs | At most 3 open PRs, drafts included, until 3 of yours are merged |
48
49 A PR that passes gets `status: needs review` and goes into the review queue. `gate: no visual` and `gate: skip` are for maintainers only.
50
33 51 ## Build and test
34 52
35 53 Build setup is in the [README](README.md#quick-start), the Windows cross build in [docs/build-windows.md](docs/build-windows.md). The everyday commands (demo run, format, tests, UI check) are in [AGENTS.md](AGENTS.md#commands).
@@ -8,7 +8,7 @@ Most of this code is written with AI agents, and that is welcome here. Just say
8|---|---|
8|---|---|
9| 1 | Read [GUARDRAILS.md](GUARDRAILS.md): where the app must match Teams and where it may differ. It wins over any habit. |
9| 1 | Read [GUARDRAILS.md](GUARDRAILS.md): where the app must match Teams and where it may differ. It wins over any habit. |
10| 2 | Check [ROADMAP.md](ROADMAP.md), mainly "Out of scope". Features listed there are not merged. |
10| 2 | Check [ROADMAP.md](ROADMAP.md), mainly "Out of scope". Features listed there are not merged. |
11| 3 | Search open pull requests and issues for the same topic. For anything larger than a fix, open an issue first and wait for a yes. |
11| 3 | Search open pull requests and issues for the same topic. For a feature or anything over 400 changed lines, open an issue first and wait for the `status: accepted` label. |
12| 4 | Read the notes under [docs/decisions/](docs/decisions/README.md) for the area you touch. |
12| 4 | Read the notes under [docs/decisions/](docs/decisions/README.md) for the area you touch. |
13
13
14## AI use
14## AI use
@@ -24,12 +24,30 @@ Most of this code is written with AI agents, and that is welcome here. Just say
24## Pull requests
24## Pull requests
25
25
26- One topic per pull request. No unrelated refactors, no formatting of files you did not change.
26- One topic per pull request. No unrelated refactors, no formatting of files you did not change.
27- The template asks for four things: a summary, the AI model, the reviews that ran, and a screenshot for UI changes (taken with demo data).
27- Fill in the template. The PR gate below checks it.
28- CI runs the tests on Linux and Windows for every pull request.
28- CI runs the tests on Linux and Windows for every pull request.
29- Commit and PR title format: `type(scope): message`, with `type` one of `feat`, `fix`, `perf`, `refactor`, `docs`, `test`, `chore`, `ci`, `build`, a lowercase scope and no emoji. CI checks the PR title.
29- Commit and PR title format: `type(scope): message`, with `type` one of `feat`, `fix`, `perf`, `refactor`, `docs`, `test`, `chore`, `ci`, `build`, a lowercase scope and no emoji.
30- The PR title becomes the squash commit and a line in the release notes (`feat` under New, `fix` under Fixes). Write it as a user would read it: `fix(chat): a sent image no longer blinks`, not `fix(chat): handle download race`.
30- The PR title becomes the squash commit and a line in the release notes (`feat` under New, `fix` under Fixes). Write it as a user would read it: `fix(chat): a sent image no longer blinks`, not `fix(chat): handle download race`.
31- Rebase on `main` instead of merging it in. Answer actionable review comments or say that you will not.
31- Rebase on `main` instead of merging it in. Answer actionable review comments or say that you will not.
32
32
33## When a PR is ready for review
34
35A bot check (`PR gate`) runs on every PR that is not a draft. Until it passes, the PR gets `status: needs info`, a comment that lists what is missing, and goes back to draft. It updates on every edit and push. A PR that stays `status: needs info` for 14 days is closed and can be reopened any time.
36
37| Gate | Rule |
38|---|---|
39| Title | `type(scope): message`, from the user's view |
40| Template | Summary, AI model, Tests and Review filled in, not just the hints |
41| Problem | No `Closes #123`: a Problem section says what is wrong or missing, when a user hits it (steps or when/then) and what should happen instead |
42| Issue first | A `feat` PR or more than 400 changed lines (lockfiles do not count) links an issue labelled `status: accepted` |
43| Screenshot | A change to UI code (`crates/app/src/views/`, `settings/`, locales) shows the changed area with demo data, or ticks "No visible change" with a reason |
44| Tests | What ran and what did not. A change to Windows-only code says whether it was built on Windows |
45| Review | At least two independent reviews, each finding fixed or answered |
46| Scope | No planning folders (`openspec/` and the like). A change to `vendor/` says why in the description |
47| Open PRs | At most 3 open PRs, drafts included, until 3 of yours are merged |
48
49A PR that passes gets `status: needs review` and goes into the review queue. `gate: no visual` and `gate: skip` are for maintainers only.
50
33## Build and test
51## Build and test
34
52
35Build setup is in the [README](README.md#quick-start), the Windows cross build in [docs/build-windows.md](docs/build-windows.md). The everyday commands (demo run, format, tests, UI check) are in [AGENTS.md](AGENTS.md#commands).
53Build setup is in the [README](README.md#quick-start), the Windows cross build in [docs/build-windows.md](docs/build-windows.md). The everyday commands (demo run, format, tests, UI check) are in [AGENTS.md](AGENTS.md#commands).