Skip to content

Commit 18c6c42

Browse files
authored
chore(gates): check the pull request body sections and word limit (#4841)
* chore(gates): enforce the pull request body rules `docs/agents/pull-requests.md` stated body rules nothing checked: an agent that skipped `## Before / after`, or left a body naming a commit a rebase had dropped, opened a PR that passed. This adds the missing check, so the prose can shrink to what no check can say. `scripts/pr-body/model.ts` holds the decision as one pure function: required sections, the `No observable change` escape with a stated reason, a 250-word budget outside code blocks, tables, and bot footers, and a tested SHA that is still an ancestor of the head. `scripts/pr-body/check.ts` answers only the question the model cannot: whether a SHA resolves, from the checkout. It reads the title and body from the event payload the runner writes, so a fork cannot steer the check by editing its own body. Bot authors and drafts are exempt. A SHA the checkout cannot look up is printed as a note, not as a stale body. * fix(gates): do not read a date or a count as the tested SHA A run of digits the repository has no commit for is not an object id, so it neither satisfies the Validation SHA rule nor reports a stale body. * chore(gates): cut the PR body gate down to sections and the word limit Drop the tested-SHA ancestry rule, its git plumbing and full-history checkout, the Markdown table handling, and the unit tests. One script reads the event payload and checks the required sections by title type and the word limit. * fix(gates): strip HTML comments without a regex replace CodeQL reads the regex replace as incomplete HTML sanitization. The text is only counted, never rendered, but a split-based strip avoids the pattern and also handles an unclosed comment. * fix(gates): keep a code-only section present and ignore comment markers inside fences A fenced block is replaced by a bare fence before sections and comments are read. The template no longer says table words are free. * fix(gates): strip indented fences, keep an unclosed comment marker as text, anchor the bot footer An indented fence inside a list item is a code block. A `<!--` in an inline code span opens no comment. A footer marker quoted mid-line is not a footer.
1 parent 64d7fc7 commit 18c6c42

7 files changed

Lines changed: 183 additions & 5 deletions

File tree

‎.github/pull_request_template.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<!--
2+
Delete these comments. The `pr-body` gate in CI enforces the headings below, and reads no prose from
3+
one. Keep the body under 250 words outside code blocks.
4+
-->
5+
6+
## Summary
7+
8+
<!-- State the behavior and the reason. Name the linked issue and any scope expansion. -->
9+
10+
## Before / after
11+
12+
<!--
13+
Delete this section unless the title's type is feat or fix. Show up to 3 calls at base and head, with
14+
the output that differs. When nothing a caller can observe changes, keep the heading and state
15+
`No observable change`, then say why.
16+
-->
17+
18+
## Value
19+
20+
<!--
21+
Delete this section unless the title's type is refactor. Give 2 to 4 numbers measured at base and
22+
head.
23+
-->
24+
25+
## Validation
26+
27+
<!-- Name the tested SHA and the command results, then the CI obligations and unresolved risks. -->

‎.github/workflows/pr-body.yml‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
name: Pull Request Body
2+
3+
on:
4+
pull_request:
5+
types:
6+
- opened
7+
- edited
8+
- synchronize
9+
- reopened
10+
- ready_for_review
11+
12+
permissions:
13+
contents: read
14+
15+
concurrency:
16+
group: >-
17+
ci-${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }}
18+
cancel-in-progress: true
19+
20+
jobs:
21+
# Grades the pull request title and body from the event payload against docs/agents/pull-requests.md.
22+
body:
23+
name: Body rules
24+
runs-on: blacksmith-4vcpu-ubuntu-2404
25+
timeout-minutes: 10
26+
steps:
27+
- name: Checkout
28+
uses: useblacksmith/checkout@2b9fe87d796feea153b455ec2f3125b471a7b0e7 # v1.8.2
29+
30+
- name: Setup toolchain
31+
uses: ./.github/actions/setup-node-pnpm
32+
33+
- name: Check the pull request body
34+
uses: ./.github/actions/run-gate
35+
with: { gate: pr-body }

‎docs/agents/pull-requests.md‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,13 +54,13 @@ After a rebase, validate the new head. Keep old evidence attributed to its origi
5454

5555
## PR body
5656

57-
Open as draft only when requested or incomplete.
58-
Keep the body below 250 words outside code blocks. Update it after each push.
57+
The `pr-body` gate enforces the sections and the 250-word limit.
58+
Update the body after each push. Open as draft only when requested or incomplete.
5959

6060
- `## Summary`: the invariant and behavior, the reason, the linked issue, and scope expansion.
61-
- `## Before / after`: required when a caller can observe the change, output and errors included.
62-
Show up to 3 calls at base and head, with the output that differs.
63-
- `## Value`: required for a refactor. Give 2–4 numbers measured at base and head.
61+
- `## Before / after`: for `feat` and `fix`, up to 3 calls at base and head, with the
62+
output that differs. Or state `No observable change` with a reason.
63+
- `## Value`: for a refactor, 2–4 numbers measured at base and head.
6464
- `## Validation`: the tested SHA and receipt, command results, CI obligations, and unresolved risks.
6565
Use evidence accessible remotely.
6666
For docs-only changes, explain why runtime tests do not apply.

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,7 @@
180180
"check:doc-links": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test scripts/__tests__/check-doc-links.test.ts && pnpm --dir website build && node --experimental-strip-types scripts/check-doc-links.ts",
181181
"check:doc-prose": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test scripts/__tests__/check-doc-prose.test.ts && node --experimental-strip-types scripts/check-doc-prose.ts",
182182
"check:agent-guidance": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test scripts/__tests__/agent-guidance-contract.test.ts",
183+
"check:pr-body": "node --experimental-strip-types scripts/check-pr-body.ts",
183184
"check:replay-compat": "node --experimental-strip-types scripts/check-replay-compat-provenance.ts",
184185
"check:daemon-wire-compat": "node --experimental-strip-types scripts/wire-compat/run.ts",
185186
"check:daemon-wire-compat:test": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test scripts/wire-compat/model.test.ts",

‎scripts/check-affected/checks.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,9 @@ export const CHECK_CATALOG: readonly CheckSpec[] = [
151151
),
152152
gate('docs-links', 'Docs internal links and heading anchors', 'check:doc-links'),
153153
gate('docs-prose', 'Docs filler, marketing, and time-relative words', 'check:doc-prose'),
154+
// Reads the pull request from the event payload the runner writes, so it has nothing to grade
155+
// outside CI.
156+
gate('pr-body', 'Pull request body sections and word limit', 'check:pr-body', false),
154157
gate('agent-guidance', 'Agent guidance ownership and context budgets', 'check:agent-guidance'),
155158
// Parses ios.yml and the Swift sources; no Xcode, no simulator, so it runs anywhere.
156159
gate(

‎scripts/check-affected/model.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ export const ALL_CHECKS = [
8686
'docs-links',
8787
'docs-prose',
8888
'agent-guidance',
89+
'pr-body',
8990
'xctest-selection',
9091
'runner-error-codes',
9192
'packaged-runner-swift',

‎scripts/check-pr-body.ts‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
// The pull request body gate: `pnpm check:pr-body`.
2+
//
3+
// Enforces the `## PR body` rule in docs/agents/pull-requests.md. It reads the title and the body from
4+
// the event payload at `GITHUB_EVENT_PATH`, never from the checked-out tree, so it has nothing to
5+
// grade outside CI.
6+
7+
import fs from 'node:fs';
8+
9+
const WORD_LIMIT = 250;
10+
/** Review bots append a footer to the body. The author did not write it, so it is not counted. */
11+
const BOT_FOOTER = /^<!--\s*(?:codesmith:footer|This is an auto-generated description)/m;
12+
13+
const SECTION_HINTS: Readonly<Record<string, string>> = {
14+
Summary: 'the invariant and behavior, the reason, the linked issue, and scope expansion',
15+
'Before / after':
16+
'up to 3 calls at base and head with the output that differs, or `No observable change` with a reason',
17+
Value: '2-4 numbers measured at base and head',
18+
Validation: 'the tested SHA, command results, CI obligations, and unresolved risks',
19+
};
20+
21+
type PullRequest = {
22+
title?: string;
23+
body?: string | null;
24+
draft?: boolean;
25+
user?: { login?: string; type?: string };
26+
};
27+
28+
function requiredSections(title: string): string[] {
29+
const type = /^([a-z]+)(?:\([^)]*\))?!?:/.exec(title.trim())?.[1];
30+
if (type === 'feat' || type === 'fix') return ['Summary', 'Before / after', 'Validation'];
31+
if (type === 'refactor') return ['Summary', 'Value', 'Validation'];
32+
return ['Summary', 'Validation'];
33+
}
34+
35+
/** The text under a `## <heading>` line, up to the next heading. Undefined without that heading. */
36+
function sectionText(prose: string, heading: string): string | undefined {
37+
const lines = prose.split('\n');
38+
const wanted = `## ${heading}`.toLowerCase();
39+
const start = lines.findIndex(
40+
(line) =>
41+
line
42+
.trim()
43+
.toLowerCase()
44+
.replace(/\s*\/\s*/, ' / ') === wanted,
45+
);
46+
if (start === -1) return undefined;
47+
const rest = lines.slice(start + 1);
48+
const end = rest.findIndex((line) => /^#{1,2} /.test(line));
49+
return (end === -1 ? rest : rest.slice(0, end)).join('\n').trim();
50+
}
51+
52+
/** Drops HTML comments, such as the template's prompts. An unclosed `<!--` is kept as text. */
53+
function withoutComments(text: string): string {
54+
return text
55+
.split('<!--')
56+
.map((part, index) => {
57+
if (index === 0) return part;
58+
const end = part.indexOf('-->');
59+
return end === -1 ? part : part.slice(end + 3);
60+
})
61+
.join('');
62+
}
63+
64+
function bodyViolations(title: string, body: string): string[] {
65+
// A fenced block becomes a bare fence: it keeps its section non-empty, hides a `<!--` inside it
66+
// from the comment strip, and adds no word to the count.
67+
const fenceless = body
68+
.replaceAll('\r', '')
69+
.replaceAll(/^[ \t]*(`{3,}|~{3,})[\s\S]*?^[ \t]*\1[^\n]*$/gm, '```');
70+
const prose = withoutComments(fenceless.split(BOT_FOOTER)[0] ?? '');
71+
const violations = requiredSections(title)
72+
.filter((heading) => !sectionText(prose, heading))
73+
.map((heading) => `Add a "## ${heading}" section: ${SECTION_HINTS[heading]}.`);
74+
const words = prose.split(/\s+/).filter((word) => /[\p{L}\p{N}]/u.test(word)).length;
75+
if (words >= WORD_LIMIT) {
76+
violations.push(
77+
`Shorten the body: it has ${words} words outside code blocks, and the limit is below ${WORD_LIMIT}.`,
78+
);
79+
}
80+
return violations;
81+
}
82+
83+
function main(): number {
84+
const eventPath = process.env.GITHUB_EVENT_PATH;
85+
if (!eventPath) {
86+
console.error('check:pr-body grades a pull request event. It runs in CI only.');
87+
return 1;
88+
}
89+
const pullRequest: PullRequest | undefined = JSON.parse(
90+
fs.readFileSync(eventPath, 'utf8'),
91+
).pull_request;
92+
if (!pullRequest) {
93+
console.error(`${eventPath} holds no pull_request event.`);
94+
return 1;
95+
}
96+
const { title = '', body, draft, user } = pullRequest;
97+
if (draft || user?.type === 'Bot' || user?.login?.endsWith('[bot]')) {
98+
console.log('PR body: not checked for a draft or a bot author.');
99+
return 0;
100+
}
101+
const violations = bodyViolations(title, body ?? '');
102+
if (violations.length === 0) {
103+
console.log('PR body: ok.');
104+
return 0;
105+
}
106+
console.error(`PR body: ${violations.length} rule(s) failed. See docs/agents/pull-requests.md.`);
107+
for (const violation of violations) console.error(`- ${violation}`);
108+
return 1;
109+
}
110+
111+
process.exitCode = main();

0 commit comments

Comments
 (0)