@zgeoff/chex 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -52,15 +52,16 @@ The docs checks read the repo's READMEs, its `docs/` tree and its skills:
52
52
 
53
53
  The repo checks read the branch, the pushed commits and the repo's config:
54
54
 
55
- | Check | Fails on | Arguments |
56
- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- |
57
- | `commits` | a pushed commit whose message fails `@zgeoff/commitlint-config` | `--pushed-refs` |
58
- | `local-paths` | a line a pushed commit adds that holds the home folder or the host name | `--pushed-refs` |
59
- | `test-timeouts` | a `bun test` timeout above its lane's limit, in a script or a `bunfig.toml` | none |
60
- | `test-layout` | a test folder, file name or import outside [the test layout](../../docs/guides/test-layout.md); test code includes a relative `[test] preload` file, a `.nix`-only `tests/` folder and a private workspace that only test code imports | none |
61
- | `workflows` | nothing: it prints each fault of the shared workflow lint, and fails when there is one | the paths |
62
- | `dependency-gates` | a stale age-gate exclude, an override or an audit ignore that nothing needs, a first-party package with no age-gate exclude, or a pinned release younger than the age gate ([details](../../docs/architecture/dependency-updates.md#the-dependency-gates-check)) | none |
63
- | `uncommitted` | a file the branch changes that holds a change the push does not send | none |
55
+ | Check | Fails on | Arguments |
56
+ | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
57
+ | `commits` | a pushed commit whose message fails `@zgeoff/commitlint-config` | `--pushed-refs` |
58
+ | `local-paths` | a line a pushed commit adds that holds the home folder or the host name | `--pushed-refs` |
59
+ | `test-timeouts` | a `bun test` timeout above its lane's limit, in a script or a `bunfig.toml` | none |
60
+ | `test-layout` | a test folder, file name or import outside [the test layout](../../docs/guides/test-layout.md); test code includes a relative `[test] preload` file, a `.nix`-only `tests/` folder and a private workspace that only test code imports | none |
61
+ | `workflows` | nothing: it prints each fault of the shared workflow lint, and fails when there is one | the paths |
62
+ | `dependency-gates` | a stale age-gate exclude, an override or an audit ignore that nothing needs, a first-party package with no age-gate exclude, or a pinned release younger than the age gate ([details](../../docs/architecture/dependency-updates.md#the-dependency-gates-check)) | none |
63
+ | `uncommitted` | a file the branch changes that holds a change the push does not send | none |
64
+ | `pr-body` | a PR description with a heading, a label, a code block or a prose-check commit that the [PR template](../../.github/PULL_REQUEST_TEMPLATE.md) doesn't allow ([details](../../docs/architecture/pr-body-check.md)) | `--body-file`, then `--base` and `--head` for the commit checks |
64
65
 
65
66
  With no path, `prose` and `links` read every README outside `.claude/` and `.agents/`, every file
66
67
  under `docs/`, each spike's `results.md`, and the Markdown under `.agents/skills/`,
@@ -83,8 +84,8 @@ skipped file back:
83
84
 
84
85
  `chex init` writes the `extends` line and a
85
86
  [`chex-baseline` job](../../docs/architecture/pre-push-baseline.md#a-checkout-without-the-baseline)
86
- into `lefthook.yml`, and adds a `check:docs` script of `chex prose length links readmes skill` when
87
- the repo has none, and changes nothing on a second run. `chex ci-plan` plans a run of `bun-checks`.
87
+ into `lefthook.yml`, adds a `check:docs` script of `chex prose length links readmes skill` when the
88
+ repo has none, and changes nothing on a second run. `chex ci-plan` plans a run of `bun-checks`.
88
89
 
89
90
  ## The pre-push baseline
90
91
 
@@ -95,6 +96,5 @@ extends:
95
96
  - node_modules/@zgeoff/chex/lefthook.yml
96
97
  ```
97
98
 
98
- The baseline's jobs call `chex <check>`, `bun run check:docs`, `rig related` and the repo's own
99
- `format:check` and `typecheck` scripts. Each job's name starts with `chex-`.
100
- [The pre-push baseline](../../docs/architecture/pre-push-baseline.md) describes each job.
99
+ Its jobs, [each described here](../../docs/architecture/pre-push-baseline.md), call `chex <check>`,
100
+ `bun run check:docs`, `rig related` and the repo's own `format:check` and `typecheck` scripts.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zgeoff/chex",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "Run each shared docs and repo check as one subcommand, with the lefthook pre-push baseline that calls them",
5
5
  "keywords": [
6
6
  "checks",
@@ -10,6 +10,7 @@ export const checkNames = [
10
10
  'workflows',
11
11
  'dependency-gates',
12
12
  'uncommitted',
13
+ 'pr-body',
13
14
  ] as const;
14
15
 
15
16
  export type CheckName = (typeof checkNames)[number];
@@ -19,6 +19,7 @@ const checksWithArgs: ReadonlySet<CheckName> = new Set([
19
19
  'commits',
20
20
  'local-paths',
21
21
  'workflows',
22
+ 'pr-body',
22
23
  ]);
23
24
 
24
25
  export const chexUsage = `usage: chex <check>... | chex <check> [args...] | chex init | chex ci-plan
@@ -35,7 +35,10 @@ async function runChecks(
35
35
  for (const name of names) {
36
36
  const checkExitCode = await runOneCheck(name, args, deps);
37
37
 
38
- deps.writeOutput(`${checkExitCode === 0 ? 'cleared' : 'bounced'}: ${name}\n`);
38
+ // tick-chex prints the PR body for a caller to capture, so a verdict line would corrupt it.
39
+ if (args[0] !== 'tick-chex') {
40
+ deps.writeOutput(`${checkExitCode === 0 ? 'cleared' : 'bounced'}: ${name}\n`);
41
+ }
39
42
 
40
43
  exitCode = Math.max(exitCode, checkExitCode);
41
44
  }
package/src/cli.ts CHANGED
@@ -10,6 +10,7 @@ import { runDependencyGatesCommand } from './dependency-gates/run-dependency-gat
10
10
  import { runInit } from './init/run-init.ts';
11
11
  import { runLocalPathsCommand } from './local-paths/run-local-paths-check.ts';
12
12
  import { writeTextFile } from './output/write-text-file.ts';
13
+ import { runPrBodyCheck } from './pr-body/run-pr-body-check.ts';
13
14
  import { runTestLayoutCommand } from './test-layout/run-test-layout-check.ts';
14
15
  import { runTestTimeoutsCommand } from './test-timeouts/run-test-timeouts-check.ts';
15
16
  import { runUncommittedCommand } from './uncommitted/run-uncommitted-check.ts';
@@ -27,6 +28,7 @@ process.exitCode = await runChex(process.argv.slice(2), {
27
28
  workflows: runWorkflowsCommand,
28
29
  'dependency-gates': runDependencyGatesCommand,
29
30
  uncommitted: runUncommittedCommand,
31
+ 'pr-body': runPrBodyCheck,
30
32
  },
31
33
  }),
32
34
  runInit: () =>
@@ -0,0 +1,17 @@
1
+ import { hexSha } from './hex-sha.ts';
2
+ import { parsePrBody } from './parse-pr-body.ts';
3
+ import { proseCheckLine } from './prose-check-line.ts';
4
+ import { stripPrBody } from './strip-pr-body.ts';
5
+
6
+ // The commit hashes on the ticked Deslop and Cold read lines, so a caller can read their state.
7
+ export function collectCheckedShas(body: string): string[] {
8
+ const parsed = parsePrBody(stripPrBody(body.replaceAll('\r\n', '\n')).text);
9
+
10
+ const shas = parsed.sections
11
+ .filter((section) => section.heading === 'Checks')
12
+ .flatMap((section) => section.lines)
13
+ .map((line) => proseCheckLine.exec(line)?.groups?.['sha'] ?? '')
14
+ .filter((sha) => hexSha.test(sha));
15
+
16
+ return [...new Set(shas)];
17
+ }
@@ -0,0 +1,296 @@
1
+ import { hexSha } from './hex-sha.ts';
2
+ import type { BodySection } from './parse-pr-body.ts';
3
+ import { parsePrBody, toSectionName } from './parse-pr-body.ts';
4
+ import { proseCheckLine } from './prose-check-line.ts';
5
+ import { stripPrBody } from './strip-pr-body.ts';
6
+ import type { BranchFacts } from './types.ts';
7
+
8
+ // Returns one line per error, each naming the section and the fix. An empty list is a pass. The
9
+ // facts come from git, and without them the sha checks and the missing-section check do not run.
10
+ export function collectPrBodyErrors(body: string, facts?: BranchFacts): string[] {
11
+ const stripped = stripPrBody(body.replaceAll('\r\n', '\n'));
12
+ const parsed = parsePrBody(stripped.text);
13
+ const named = parsed.sections.filter((section) => section.heading !== undefined);
14
+
15
+ return [
16
+ ...collectHeadingErrors(named, stripped.hasReport),
17
+ ...collectCodeBlockErrors(parsed.codeBlocks),
18
+ ...collectChecksFenceErrors(parsed.codeBlocks),
19
+ ...collectPlaceholderErrors(parsed.sections),
20
+ ...named.flatMap((section) =>
21
+ section.heading === 'Next steps' ? collectNextStepsErrors(section) : [],
22
+ ),
23
+ ...named.flatMap((section) =>
24
+ section.heading === 'Checks' ? collectChecksErrors(section, facts) : [],
25
+ ),
26
+ ...collectMissingChecksErrors(named, facts),
27
+ ];
28
+ }
29
+
30
+ const headingOrder: readonly string[] = ['Description', 'Next steps', 'Checks', 'Verification'];
31
+
32
+ function collectHeadingErrors(sections: readonly BodySection[], hasReport: boolean): string[] {
33
+ const errors: string[] = [];
34
+ let lastIndex = -1;
35
+
36
+ for (const section of sections) {
37
+ const index = headingOrder.indexOf(section.heading ?? '');
38
+
39
+ if (index === -1) {
40
+ errors.push(
41
+ `${toSectionName(section.heading)}: "## ${section.heading}" is not an allowed heading; use ${headingOrder.join(', ')}, in that order, or move the text into Description.`,
42
+ );
43
+ } else if (index <= lastIndex) {
44
+ errors.push(
45
+ `${section.heading}: the heading is out of order or repeated; the sections go ${headingOrder.join(', ')}, once each.`,
46
+ );
47
+ } else {
48
+ lastIndex = index;
49
+ }
50
+
51
+ if (index !== -1 && !section.isFilled && !(section.heading === 'Verification' && hasReport)) {
52
+ errors.push(`${section.heading}: the section is empty; write it or delete the heading.`);
53
+ }
54
+ }
55
+
56
+ if (!sections.some((section) => section.heading === 'Description')) {
57
+ errors.push('Description: the body has no "## Description" section; add one.');
58
+ }
59
+
60
+ return errors;
61
+ }
62
+
63
+ const maxCodeLines = 50;
64
+ const maxCodeWidth = 100;
65
+
66
+ function collectCodeBlockErrors(
67
+ blocks: readonly { section: string; lines: readonly string[]; isClosed: boolean }[],
68
+ ): string[] {
69
+ return blocks.flatMap((block) => {
70
+ const errors: string[] = [];
71
+
72
+ if (!block.isClosed) {
73
+ errors.push(`${block.section}: a code block is never closed; add the closing fence.`);
74
+ }
75
+
76
+ if (block.lines.length > maxCodeLines) {
77
+ errors.push(
78
+ `${block.section}: a code block runs ${block.lines.length} lines; cut it to ${maxCodeLines} or fewer, or link to the code.`,
79
+ );
80
+ }
81
+
82
+ const widest = Math.max(0, ...block.lines.map((line) => (line.match(/./gsu) ?? []).length));
83
+
84
+ if (widest > maxCodeWidth) {
85
+ errors.push(
86
+ `${block.section}: a code block has a line ${widest} characters wide; wrap it to ${maxCodeWidth} or fewer.`,
87
+ );
88
+ }
89
+
90
+ return errors;
91
+ });
92
+ }
93
+
94
+ function collectChecksFenceErrors(blocks: readonly { section: string }[]): string[] {
95
+ return blocks
96
+ .filter((block) => block.section === 'Checks')
97
+ .map(
98
+ () =>
99
+ 'Checks: a code block sits under Checks; the section holds only the chex, Deslop and Cold read lines, so move the block to Verification or Description.',
100
+ );
101
+ }
102
+
103
+ const htmlTags = new Set([
104
+ 'details',
105
+ 'summary',
106
+ 'br',
107
+ 'hr',
108
+ 'kbd',
109
+ 'sub',
110
+ 'sup',
111
+ 'img',
112
+ 'a',
113
+ 'p',
114
+ 'b',
115
+ 'i',
116
+ 'em',
117
+ 'strong',
118
+ 'code',
119
+ 'pre',
120
+ ]);
121
+
122
+ const placeholder = /<(?<word>[A-Za-z][A-Za-z0-9_-]*)?>/gu;
123
+
124
+ function collectPlaceholderErrors(sections: readonly BodySection[]): string[] {
125
+ return sections.flatMap((section) => {
126
+ const found = new Set<string>();
127
+
128
+ for (const line of section.lines) {
129
+ for (const match of line.matchAll(placeholder)) {
130
+ const word = match.groups?.['word'] ?? '';
131
+
132
+ if (!htmlTags.has(word.toLowerCase())) {
133
+ found.add(match[0]);
134
+ }
135
+ }
136
+ }
137
+
138
+ return [...found].map(
139
+ (item) =>
140
+ `${toSectionName(section.heading)}: the placeholder ${item} is still in the text; replace it with a real value or delete the line.`,
141
+ );
142
+ });
143
+ }
144
+
145
+ const labelOrder: readonly string[] = ['Needs the owner', 'Later'];
146
+ const labelLine = /^\*\*(?<label>[^*]+)\*\*:?\s*$/u;
147
+ const bulletLine = /^[-*+]\s+/u;
148
+ const checkboxBullet = /^[-*+]\s+\[[ xX]\]\s+\S/u;
149
+ const issueEnding = /\((?:[A-Z][A-Z0-9]*-\d+|#\d+|[\w.-]+\/[\w.-]+#\d+)\)\.?$/u;
150
+
151
+ function collectNextStepsErrors(section: BodySection): string[] {
152
+ const errors: string[] = [];
153
+ const groups: { label: string; items: string[] }[] = [];
154
+ let lastLabelIndex = -1;
155
+
156
+ for (const line of section.lines.filter((text) => text.trim() !== '')) {
157
+ const label = labelLine.exec(line)?.groups?.['label']?.trim();
158
+ const group = groups.at(-1);
159
+
160
+ if (label !== undefined) {
161
+ const index = labelOrder.indexOf(label);
162
+
163
+ if (index === -1) {
164
+ errors.push(
165
+ `Next steps: the label **${label}** is not allowed; use **Needs the owner** or **Later**.`,
166
+ );
167
+ } else if (index <= lastLabelIndex) {
168
+ errors.push(
169
+ `Next steps: **${label}** is out of order or repeated; the labels go **Needs the owner**, then **Later**, once each.`,
170
+ );
171
+ } else {
172
+ lastLabelIndex = index;
173
+ }
174
+
175
+ groups.push({ label, items: [] });
176
+ } else if (bulletLine.test(line)) {
177
+ if (group === undefined) {
178
+ errors.push(
179
+ `Next steps: the bullet "${line.trim()}" has no label above it; put it under **Needs the owner** or **Later**.`,
180
+ );
181
+ } else {
182
+ group.items.push(line);
183
+ }
184
+ } else if (/^\s/u.test(line) && group !== undefined && group.items.length > 0) {
185
+ group.items[group.items.length - 1] += ` ${line.trim()}`;
186
+ } else {
187
+ errors.push(
188
+ `Next steps: "${line.trim()}" is not a label or a bullet; write **Needs the owner** or **Later** on its own line and the items as bullets under it.`,
189
+ );
190
+ }
191
+ }
192
+
193
+ for (const group of groups) {
194
+ if (group.items.length === 0) {
195
+ errors.push(`Next steps: **${group.label}** has no bullets; add them or delete the label.`);
196
+ }
197
+
198
+ for (const item of group.items) {
199
+ if (group.label === 'Needs the owner' && !checkboxBullet.test(item)) {
200
+ errors.push(
201
+ `Next steps: "${item.trim()}" under **Needs the owner** is not a checkbox; start it with "- [ ] ".`,
202
+ );
203
+ }
204
+
205
+ if (group.label === 'Later' && !issueEnding.test(item.trim())) {
206
+ errors.push(
207
+ `Next steps: "${item.trim()}" under **Later** does not end with an issue ID in brackets such as (GEO-124) or (#45); file the issue and add it.`,
208
+ );
209
+ }
210
+ }
211
+ }
212
+
213
+ return errors;
214
+ }
215
+
216
+ const placeholderOnly = /^<[A-Za-z0-9_-]*>$/u;
217
+ const chexLine = /^- \[[ x]\] chex$/u;
218
+
219
+ function collectChecksErrors(section: BodySection, facts: BranchFacts | undefined): string[] {
220
+ return section.lines
221
+ .filter((line) => line.trim() !== '')
222
+ .flatMap((line) => {
223
+ if (chexLine.test(line)) {
224
+ return [];
225
+ }
226
+
227
+ const check = proseCheckLine.exec(line)?.groups;
228
+
229
+ if (check === undefined) {
230
+ return [
231
+ `Checks: "${line.trim()}" is not a check line; use "- [ ] chex", "- [x] Deslop (<sha>)" or "- [x] Cold read (<sha>)".`,
232
+ ];
233
+ }
234
+
235
+ const name = check['name'] ?? '';
236
+ const sha = check['sha'] ?? '';
237
+
238
+ if (check['ticked'] !== 'x') {
239
+ return [`Checks: ${name} is not ticked; run it, then tick it with the commit you checked.`];
240
+ }
241
+
242
+ // A placeholder sha is reported as a placeholder.
243
+ if (placeholderOnly.test(sha)) {
244
+ return [];
245
+ }
246
+
247
+ if (!hexSha.test(sha)) {
248
+ return [
249
+ `Checks: ${name} (${sha}) is not a commit hash; write the short hash of the commit you checked.`,
250
+ ];
251
+ }
252
+
253
+ return facts === undefined ? [] : collectShaErrors(name, sha, facts);
254
+ });
255
+ }
256
+
257
+ function collectShaErrors(name: string, sha: string, facts: BranchFacts): string[] {
258
+ const state = facts.shaStates[sha] ?? 'unknown';
259
+
260
+ if (state === 'unknown') {
261
+ return [
262
+ `Checks: ${name} (${sha}) is not a commit in this repo; write the short hash of the commit you checked.`,
263
+ ];
264
+ }
265
+
266
+ if (state === 'outside') {
267
+ return [
268
+ `Checks: ${name} (${sha}) is not in this branch's history; re-run the check on the branch and update the sha.`,
269
+ ];
270
+ }
271
+
272
+ if (state === 'old' && facts.newestDocChange !== undefined) {
273
+ return [
274
+ `Checks: ${name} (${sha}) is older than commit ${facts.newestDocChange.commit.slice(0, 7)}, which changes ${facts.newestDocChange.files.join(', ')}; re-run that check and update the sha.`,
275
+ ];
276
+ }
277
+
278
+ return [];
279
+ }
280
+
281
+ function collectMissingChecksErrors(
282
+ sections: readonly BodySection[],
283
+ facts: BranchFacts | undefined,
284
+ ): string[] {
285
+ if (facts === undefined || facts.docFiles.length === 0) {
286
+ return [];
287
+ }
288
+
289
+ if (sections.some((section) => section.heading === 'Checks')) {
290
+ return [];
291
+ }
292
+
293
+ return [
294
+ `Checks: the PR changes doc or skill files (${facts.docFiles.join(', ')}) but the body has no "## Checks" section; add one with the chex, Deslop and Cold read lines.`,
295
+ ];
296
+ }
@@ -0,0 +1 @@
1
+ export const hexSha = /^[0-9a-f]{7,40}$/u;
@@ -0,0 +1,105 @@
1
+ export interface BodySection {
2
+ // The heading text, or undefined for the lines before the first heading.
3
+ readonly heading: string | undefined;
4
+
5
+ // The lines outside code blocks.
6
+ readonly lines: readonly string[];
7
+
8
+ // Whether the section holds anything, a code block included.
9
+ readonly isFilled: boolean;
10
+ }
11
+
12
+ export interface CodeBlock {
13
+ readonly section: string;
14
+ readonly lines: readonly string[];
15
+ readonly isClosed: boolean;
16
+ }
17
+
18
+ export interface ParsedBody {
19
+ readonly sections: readonly BodySection[];
20
+ readonly codeBlocks: readonly CodeBlock[];
21
+ }
22
+
23
+ const fenceLine = /^\s{0,3}(?<fence>`{3,}|~{3,})/u;
24
+ const headingLine = /^##\s+(?<text>.*?)\s*$/u;
25
+
26
+ interface OpenBlock {
27
+ readonly marker: string;
28
+ readonly lines: string[];
29
+ }
30
+
31
+ // Reads the body line by line, so a heading or a placeholder inside a code block never counts.
32
+ export function parsePrBody(text: string): ParsedBody {
33
+ const sections: { heading: string | undefined; lines: string[]; isFilled: boolean }[] = [
34
+ { heading: undefined, lines: [], isFilled: false },
35
+ ];
36
+
37
+ const codeBlocks: CodeBlock[] = [];
38
+ let open: OpenBlock | undefined;
39
+
40
+ for (const line of text.split('\n')) {
41
+ const section = sections.at(-1);
42
+
43
+ if (section === undefined) {
44
+ continue;
45
+ }
46
+
47
+ const fence = fenceLine.exec(line)?.groups?.['fence'];
48
+
49
+ if (open !== undefined) {
50
+ if (
51
+ fence !== undefined &&
52
+ fence.startsWith(open.marker.charAt(0)) &&
53
+ fence.length >= open.marker.length &&
54
+ line.trim() === fence
55
+ ) {
56
+ codeBlocks.push({
57
+ section: toSectionName(section.heading),
58
+ lines: open.lines,
59
+ isClosed: true,
60
+ });
61
+
62
+ open = undefined;
63
+ } else {
64
+ open.lines.push(line);
65
+ }
66
+
67
+ continue;
68
+ }
69
+
70
+ if (fence !== undefined) {
71
+ open = { marker: fence, lines: [] };
72
+ section.isFilled = true;
73
+ continue;
74
+ }
75
+
76
+ const heading = headingLine.exec(line)?.groups?.['text'];
77
+
78
+ if (heading !== undefined) {
79
+ sections.push({ heading, lines: [], isFilled: false });
80
+ continue;
81
+ }
82
+
83
+ section.lines.push(line);
84
+
85
+ if (line.trim() !== '') {
86
+ section.isFilled = true;
87
+ }
88
+ }
89
+
90
+ const lastSection = sections.at(-1);
91
+
92
+ if (open !== undefined && lastSection !== undefined) {
93
+ codeBlocks.push({
94
+ section: toSectionName(lastSection.heading),
95
+ lines: open.lines,
96
+ isClosed: false,
97
+ });
98
+ }
99
+
100
+ return { sections, codeBlocks };
101
+ }
102
+
103
+ export function toSectionName(heading: string | undefined): string {
104
+ return heading ?? 'The start of the body';
105
+ }
@@ -0,0 +1,2 @@
1
+ export const proseCheckLine =
2
+ /^- \[(?<ticked>[ x])\] (?<name>Deslop|Cold read) \((?<sha>[^)]*)\)$/u;
@@ -0,0 +1,153 @@
1
+ import type { RunProgram } from '../program/run-program.ts';
2
+ import type { DocPathspecs } from './read-doc-pathspecs.ts';
3
+ import type { BranchFacts, ShaState } from './types.ts';
4
+
5
+ interface BranchFactsOptions {
6
+ readonly cwd: string;
7
+ readonly env: Readonly<Record<string, string | undefined>>;
8
+ readonly runProgram: RunProgram;
9
+ readonly pathspecs: DocPathspecs;
10
+ readonly base: string;
11
+ readonly head: string;
12
+
13
+ // The commit hashes whose state the caller wants.
14
+ readonly shas: readonly string[];
15
+ }
16
+
17
+ // The two pathspec groups run apart because the README group excludes the skill folders that the
18
+ // docs group lists.
19
+ export function readBranchFacts(options: Readonly<BranchFactsOptions>): BranchFacts {
20
+ const groups = [options.pathspecs.readmes, options.pathspecs.docs];
21
+
22
+ const docFiles = [
23
+ ...new Set(
24
+ groups.flatMap((group) =>
25
+ splitPaths(
26
+ runGit(options, [
27
+ 'diff',
28
+ '--name-only',
29
+ '-z',
30
+ '--no-renames',
31
+ `${options.base}...${options.head}`,
32
+ '--',
33
+ ...group,
34
+ ]),
35
+ ),
36
+ ),
37
+ ),
38
+ ];
39
+
40
+ const newestCommit = readNewestCommit(options, groups);
41
+
42
+ const newestDocChange =
43
+ newestCommit === undefined
44
+ ? undefined
45
+ : {
46
+ commit: newestCommit,
47
+ files: [
48
+ ...new Set(
49
+ groups.flatMap((group) =>
50
+ splitPaths(
51
+ runGit(options, [
52
+ 'diff',
53
+ '--name-only',
54
+ '-z',
55
+ '--no-renames',
56
+ `${newestCommit}^`,
57
+ newestCommit,
58
+ '--',
59
+ ...group,
60
+ ]),
61
+ ),
62
+ ),
63
+ ),
64
+ ],
65
+ };
66
+
67
+ return {
68
+ docFiles,
69
+ newestDocChange,
70
+ shaStates: Object.fromEntries(
71
+ options.shas.map((sha) => [sha, probeSha(options, newestCommit, sha)]),
72
+ ),
73
+ };
74
+ }
75
+
76
+ function splitPaths(output: string): string[] {
77
+ return output.split('\0').filter((path) => path !== '');
78
+ }
79
+
80
+ function runGit(options: Readonly<BranchFactsOptions>, args: readonly string[]): string {
81
+ const result = options.runProgram(['git', ...args], { cwd: options.cwd, env: options.env });
82
+
83
+ if (result.exitCode !== 0) {
84
+ throw new Error(`git ${args[0]} failed: ${result.stderr.trim()}`);
85
+ }
86
+
87
+ return result.stdout;
88
+ }
89
+
90
+ function readNewestCommit(
91
+ options: Readonly<BranchFactsOptions>,
92
+ groups: readonly (readonly string[])[],
93
+ ): string | undefined {
94
+ const range = `${options.base}..${options.head}`;
95
+
96
+ const touching = groups.flatMap((group) =>
97
+ runGit(options, ['rev-list', '-1', range, '--', ...group])
98
+ .split('\n')
99
+ .filter((line) => line !== ''),
100
+ );
101
+
102
+ if (touching.length === 0) {
103
+ return undefined;
104
+ }
105
+
106
+ // rev-list prints the newest commit first.
107
+ const ordered = runGit(options, ['rev-list', range]).split('\n');
108
+
109
+ return touching.toSorted((first, second) => ordered.indexOf(first) - ordered.indexOf(second))[0];
110
+ }
111
+
112
+ function probeSha(
113
+ options: Readonly<BranchFactsOptions>,
114
+ newestCommit: string | undefined,
115
+ sha: string,
116
+ ): ShaState {
117
+ const resolved = options.runProgram(
118
+ ['git', 'rev-parse', '--verify', '--quiet', `${sha}^{commit}`],
119
+ { cwd: options.cwd, env: options.env },
120
+ );
121
+
122
+ if (resolved.exitCode !== 0) {
123
+ return 'unknown';
124
+ }
125
+
126
+ const commit = resolved.stdout.trim();
127
+
128
+ if (!probeAncestor(options, commit, options.head)) {
129
+ return 'outside';
130
+ }
131
+
132
+ return newestCommit === undefined || probeAncestor(options, newestCommit, commit)
133
+ ? 'current'
134
+ : 'old';
135
+ }
136
+
137
+ // merge-base exits 1 for "not an ancestor" and with other codes when git fails.
138
+ function probeAncestor(
139
+ options: Readonly<BranchFactsOptions>,
140
+ ancestor: string,
141
+ descendant: string,
142
+ ): boolean {
143
+ const result = options.runProgram(['git', 'merge-base', '--is-ancestor', ancestor, descendant], {
144
+ cwd: options.cwd,
145
+ env: options.env,
146
+ });
147
+
148
+ if (result.exitCode > 1) {
149
+ throw new Error(`git merge-base failed: ${result.stderr.trim()}`);
150
+ }
151
+
152
+ return result.exitCode === 0;
153
+ }
@@ -0,0 +1,36 @@
1
+ import { readFileSync } from 'node:fs';
2
+
3
+ export interface DocPathspecs {
4
+ // The READMEs, which the prose check lists one by one and keeps out of the skill folders.
5
+ readonly readmes: readonly string[];
6
+
7
+ // The docs and skill Markdown.
8
+ readonly docs: readonly string[];
9
+ }
10
+
11
+ const pathspec = /'(?<spec>:\([^']*\)[^']*)'/gu;
12
+
13
+ // Reads the pathspecs that check-prose.sh uses when it gets no path, from the script itself, so the
14
+ // two lists cannot drift apart.
15
+ export function parseDocPathspecs(script: string): DocPathspecs {
16
+ const start = script.indexOf('if [ "$#" -eq 0 ]; then');
17
+ const end = script.indexOf('\nfi\n', start);
18
+ const block = start === -1 || end === -1 ? '' : script.slice(start, end);
19
+ const readmeEnd = block.indexOf('); then');
20
+ const readmeBlock = block.slice(0, readmeEnd + 1);
21
+ const docBlock = block.slice(readmeEnd + 1);
22
+ const readmes = [...readmeBlock.matchAll(pathspec)].map((match) => match.groups?.['spec'] ?? '');
23
+ const docs = [...docBlock.matchAll(pathspec)].map((match) => match.groups?.['spec'] ?? '');
24
+
25
+ if (readmes.length === 0 || docs.length === 0) {
26
+ throw new Error('check-prose.sh no longer lists the pathspecs in the form pr-body reads');
27
+ }
28
+
29
+ return { readmes, docs };
30
+ }
31
+
32
+ export function readDocPathspecs(): DocPathspecs {
33
+ return parseDocPathspecs(
34
+ readFileSync(new URL('../docs/check-prose.sh', import.meta.url), 'utf8'),
35
+ );
36
+ }
@@ -0,0 +1,117 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { parseArgs } from 'node:util';
3
+ import { runProgram } from '../program/run-program.ts';
4
+ import { collectCheckedShas } from './collect-checked-shas.ts';
5
+ import { collectPrBodyErrors } from './collect-pr-body-errors.ts';
6
+ import { readBranchFacts } from './read-branch-facts.ts';
7
+ import { readDocPathspecs } from './read-doc-pathspecs.ts';
8
+ import { tickPrBodyChex } from './tick-pr-body-chex.ts';
9
+ import type { BranchFacts } from './types.ts';
10
+
11
+ export interface PrBodyCommandDeps {
12
+ readonly readBody: (path: string) => string;
13
+ readonly readFacts: (base: string, head: string, shas: readonly string[]) => BranchFacts;
14
+ readonly writeOutput: (text: string) => void;
15
+ readonly writeError: (text: string) => void;
16
+ }
17
+
18
+ export const prBodyUsage = `usage: chex pr-body --body-file <path> [--base <sha> --head <sha>]
19
+ chex pr-body tick-chex --body-file <path> --passed|--failed`;
20
+
21
+ export function runPrBodyCheck(argv: readonly string[]): number {
22
+ return runPrBodyCommand(argv, {
23
+ readBody: (path) => readFileSync(path, 'utf8'),
24
+ readFacts: (base, head, shas) =>
25
+ readBranchFacts({
26
+ cwd: process.cwd(),
27
+ env: process.env,
28
+ runProgram,
29
+ pathspecs: readDocPathspecs(),
30
+ base,
31
+ head,
32
+ shas,
33
+ }),
34
+ writeOutput: (text) => {
35
+ process.stdout.write(text);
36
+ },
37
+ writeError: (text) => {
38
+ process.stderr.write(text);
39
+ },
40
+ });
41
+ }
42
+
43
+ // Returns the exit code: 0 when the body passes, 1 with errors, and 2 when the check cannot run.
44
+ export function runPrBodyCommand(argv: readonly string[], deps: PrBodyCommandDeps): number {
45
+ try {
46
+ return runParsedCommand(argv, deps);
47
+ } catch (error) {
48
+ deps.writeError(`pr-body: ${error instanceof Error ? error.message : String(error)}\n`);
49
+
50
+ return 2;
51
+ }
52
+ }
53
+
54
+ function runParsedCommand(argv: readonly string[], deps: PrBodyCommandDeps): number {
55
+ const parsed = parseArgs({
56
+ args: [...argv],
57
+ allowPositionals: true,
58
+ options: {
59
+ 'body-file': { type: 'string' },
60
+ base: { type: 'string' },
61
+ head: { type: 'string' },
62
+ passed: { type: 'boolean' },
63
+ failed: { type: 'boolean' },
64
+ },
65
+ });
66
+
67
+ const values = parsed.values;
68
+ const bodyFile = values['body-file'];
69
+ const [subcommand, ...extra] = parsed.positionals;
70
+
71
+ if (
72
+ bodyFile === undefined ||
73
+ extra.length > 0 ||
74
+ (subcommand !== undefined && subcommand !== 'tick-chex')
75
+ ) {
76
+ deps.writeError(
77
+ `pr-body: name --body-file, and at most the subcommand tick-chex\n${prBodyUsage}\n`,
78
+ );
79
+
80
+ return 2;
81
+ }
82
+
83
+ const body = deps.readBody(bodyFile);
84
+
85
+ if (subcommand === 'tick-chex') {
86
+ if (values.passed === values.failed) {
87
+ deps.writeError(
88
+ `pr-body: tick-chex takes --passed or --failed, not both or neither\n${prBodyUsage}\n`,
89
+ );
90
+
91
+ return 2;
92
+ }
93
+
94
+ deps.writeOutput(tickPrBodyChex(body, values.passed === true));
95
+
96
+ return 0;
97
+ }
98
+
99
+ if ((values.base === undefined) !== (values.head === undefined)) {
100
+ deps.writeError(`pr-body: --base and --head go together\n${prBodyUsage}\n`);
101
+
102
+ return 2;
103
+ }
104
+
105
+ const facts =
106
+ values.base === undefined || values.head === undefined
107
+ ? undefined
108
+ : deps.readFacts(values.base, values.head, collectCheckedShas(body));
109
+
110
+ const errors = collectPrBodyErrors(body, facts);
111
+
112
+ if (errors.length > 0) {
113
+ deps.writeOutput(`${errors.map((error) => `pr-body: ${error}`).join('\n')}\n`);
114
+ }
115
+
116
+ return errors.length === 0 ? 0 : 1;
117
+ }
@@ -0,0 +1,20 @@
1
+ export interface StrippedBody {
2
+ readonly text: string;
3
+
4
+ // Whether the body holds a closed wringer:report span, which the Verification section fills.
5
+ readonly hasReport: boolean;
6
+ }
7
+
8
+ const reportSpan = /<!--\s*wringer:report\s*-->[\s\S]*?<!--\s*\/wringer:report\s*-->/gu;
9
+ const htmlComment = /<!--[\s\S]*?-->/gu;
10
+
11
+ // The template's comments hold headings and code fences, and the verify report holds a table, so
12
+ // none of them may count as the author's text.
13
+ export function stripPrBody(body: string): StrippedBody {
14
+ const withoutReport = body.replaceAll(reportSpan, '');
15
+
16
+ return {
17
+ text: withoutReport.replaceAll(htmlComment, ''),
18
+ hasReport: withoutReport !== body,
19
+ };
20
+ }
@@ -0,0 +1,22 @@
1
+ const chexLine = /^- \[[ xX]\] chex(?=[ \t]*\r?$)/gmu;
2
+ const htmlComment = /<!--[\s\S]*?-->/gu;
3
+
4
+ // Changes only the first chex checkbox line outside an HTML comment, and returns the rest of the
5
+ // body byte for byte. A body with no such line comes back unchanged.
6
+ export function tickPrBodyChex(body: string, passed: boolean): string {
7
+ const comments = [...body.matchAll(htmlComment)].map((match) => ({
8
+ start: match.index,
9
+ end: match.index + match[0].length,
10
+ }));
11
+
12
+ const line = [...body.matchAll(chexLine)].find(
13
+ (match) =>
14
+ !comments.some((comment) => match.index >= comment.start && match.index < comment.end),
15
+ );
16
+
17
+ if (line === undefined) {
18
+ return body;
19
+ }
20
+
21
+ return `${body.slice(0, line.index)}- [${passed ? 'x' : ' '}] chex${body.slice(line.index + line[0].length)}`;
22
+ }
@@ -0,0 +1,16 @@
1
+ // How a prose check's commit sits against the branch: not in the repo, not an ancestor of head, an
2
+ // ancestor that a later doc or skill change outdates, or current.
3
+ export type ShaState = 'unknown' | 'outside' | 'old' | 'current';
4
+
5
+ export interface BranchFacts {
6
+ // The doc and skill files that the commits in base..head change.
7
+ readonly docFiles: readonly string[];
8
+
9
+ // The newest commit in base..head that changes a doc or skill file, with the files it changes.
10
+ readonly newestDocChange:
11
+ | { readonly commit: string; readonly files: readonly string[] }
12
+ | undefined;
13
+
14
+ // The state of each commit hash the body names on a Deslop or Cold read line.
15
+ readonly shaStates: Readonly<Record<string, ShaState>>;
16
+ }