wachiman 1.15.0 → 1.16.0

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.
Files changed (54) hide show
  1. package/README.md +1 -0
  2. package/package.json +1 -1
  3. package/src/accounts/commands.ts +3 -2
  4. package/src/accounts/confirm.ts +1 -1
  5. package/src/accounts/profile-list.ts +24 -0
  6. package/src/cli.ts +54 -20
  7. package/src/config.ts +19 -6
  8. package/src/connectors/local-git.ts +47 -0
  9. package/src/doctor/checks.ts +106 -1
  10. package/src/doctor/run.ts +9 -1
  11. package/src/engine.ts +280 -97
  12. package/src/help.ts +85 -3
  13. package/src/init/args.ts +5 -2
  14. package/src/init/github-login.ts +13 -0
  15. package/src/init/options.ts +31 -3
  16. package/src/init/prompt.ts +46 -15
  17. package/src/init/run.ts +204 -24
  18. package/src/init/settings.ts +127 -0
  19. package/src/init/write.ts +16 -102
  20. package/src/local-ask.ts +5 -4
  21. package/src/local.ts +55 -10
  22. package/src/loop/command.ts +5 -5
  23. package/src/pr-template/adopt.ts +434 -0
  24. package/src/pr-template/catalog.ts +429 -0
  25. package/src/pr-template/check-run.ts +328 -0
  26. package/src/pr-template/check.ts +338 -0
  27. package/src/pr-template/describe.ts +368 -0
  28. package/src/pr-template/format.ts +399 -0
  29. package/src/pr-template/gh.ts +159 -0
  30. package/src/pr-template/install.ts +288 -0
  31. package/src/pr-template/legacy-guides.ts +50 -0
  32. package/src/pr-template/pr-risk.ts +426 -0
  33. package/src/pr-template/render.ts +302 -0
  34. package/src/pr-template/resolve.ts +65 -0
  35. package/src/pr-template/run.ts +88 -0
  36. package/src/pr-template/strip.ts +171 -0
  37. package/src/pr-template/write.ts +139 -0
  38. package/src/providers/claude-code.ts +7 -8
  39. package/src/providers/codex.ts +4 -4
  40. package/src/providers/spawn.ts +95 -0
  41. package/src/providers/types.ts +5 -2
  42. package/src/repo-settings.ts +159 -0
  43. package/src/setup/prompt.ts +49 -33
  44. package/src/setup/run.ts +31 -6
  45. package/src/sinks/common.ts +10 -3
  46. package/src/sinks/markdown.ts +3 -2
  47. package/src/sinks/terminal.ts +3 -2
  48. package/src/upgrade/command.ts +286 -0
  49. package/src/upgrade/pin.ts +112 -0
  50. package/src/wizard/mascot.ts +56 -51
  51. package/src/wizard/prompt-fancy.ts +10 -2
  52. package/src/wizard/prompt.ts +17 -4
  53. package/src/wizard/ui.ts +2 -0
  54. package/templates/pr/sections.json +163 -0
@@ -0,0 +1,328 @@
1
+ /**
2
+ * The command layer of `wachiman pr-template check`, `strip` and `risk`: argument parsing and the
3
+ * runners that read files and call git and gh. The rules live in check.ts, strip.ts and pr-risk.ts.
4
+ *
5
+ * Exit codes: 0 passes, 1 findings, 2 a configuration, usage or tool problem. `check` reads
6
+ * `.github/pr-template.json` (from the working tree for a file, from the PR's head commit for
7
+ * `--pr`); `strip` and `risk` never read it (ADR 0051).
8
+ */
9
+ import { readFileSync } from "node:fs";
10
+ import { join, resolve } from "node:path";
11
+ import { UsageError } from "../config";
12
+ import { parseFlags } from "../flags";
13
+ import { CHOICE_FILE, loadCatalog, loadRepoChoice, type Catalog } from "./catalog";
14
+ import { checkDescription, type CheckResult, type Finding } from "./check";
15
+ import {
16
+ changesFromGit, commitMessagesFromGit, defaultRunner, ghFileAt, ghPrDiff, ghPrView, gitFileAt, gitHead, ToolError, type CommandRunner,
17
+ } from "./gh";
18
+ import { computeRisk, formatRisk, parseRiskExtension, RISK_EXTENSION_FILE, type ChangedFile, type RiskExtension } from "./pr-risk";
19
+ import { resolveTemplate, type ResolvedTemplate } from "./resolve";
20
+ import { stripDescription } from "./strip";
21
+
22
+ export const DEFAULT_BASE = "origin/main";
23
+
24
+ export const checkUsage =
25
+ "wachiman pr-template check [<file>] [--pr <n>] [--repo <owner/name>] [--title <t>] [--head <sha>] [--base <ref>] [--allow-breaking]";
26
+ export const stripUsage = "wachiman pr-template strip <file>";
27
+ export const riskUsage = "wachiman pr-template risk [--base <ref>]";
28
+
29
+ export interface CheckOptions {
30
+ /** A description on disk (the title is then required). */
31
+ file?: string;
32
+ /** A pull request number (title, body, head, commits and files then come from gh). */
33
+ pr?: number;
34
+ repo?: string;
35
+ title?: string;
36
+ head?: string;
37
+ base: string;
38
+ allowBreaking: boolean;
39
+ }
40
+ export interface StripOptions { file: string }
41
+ export interface RiskOptions { base: string }
42
+
43
+ export interface PrTemplateIo {
44
+ stdout: (text: string) => void;
45
+ stderr: (line: string) => void;
46
+ }
47
+
48
+ export interface PrTemplateDeps {
49
+ /** Runs git and gh. Default: the real tools. */
50
+ run?: CommandRunner;
51
+ /** The catalog. Default: the shipped one. */
52
+ catalog?: Catalog;
53
+ /** Where a relative `<file>` argument resolves: the directory the command was given. Default: the repository directory. */
54
+ fileBase?: string;
55
+ }
56
+
57
+ const helpRequested = (argv: string[]) => argv.includes("--help") || argv.includes("-h");
58
+
59
+ /** `argv` is what follows `check`. */
60
+ export function parseCheckArgs(argv: string[]): CheckOptions | { help: true } {
61
+ if (helpRequested(argv)) return { help: true };
62
+ const { positionals, values, booleans } = parseFlags(
63
+ argv,
64
+ { values: ["--pr", "--repo", "--title", "--head", "--base"], booleans: ["--allow-breaking"] },
65
+ "pr-template check",
66
+ );
67
+ if (positionals.length > 1) throw new UsageError(`check takes one file, got "${positionals.join('", "')}".`);
68
+ const file = positionals[0];
69
+ const prText = values["--pr"];
70
+ if ((file === undefined) === (prText === undefined)) throw new UsageError("check needs either a file or --pr <number>.");
71
+ let pr: number | undefined;
72
+ if (prText !== undefined) {
73
+ if (!/^[1-9][0-9]*$/.test(prText)) throw new UsageError(`--pr must be a pull request number, got "${prText}".`);
74
+ pr = Number(prText);
75
+ for (const flag of ["--title", "--head", "--base"]) {
76
+ if (values[flag] !== undefined) throw new UsageError(`${flag} goes with a file; with --pr the title, head and base come from the pull request.`);
77
+ }
78
+ } else {
79
+ if (values["--repo"] !== undefined) throw new UsageError("--repo goes with --pr.");
80
+ if (values["--title"] === undefined) throw new UsageError("check <file> needs --title.");
81
+ }
82
+ return {
83
+ ...(file !== undefined ? { file } : {}),
84
+ ...(pr !== undefined ? { pr } : {}),
85
+ ...(values["--repo"] !== undefined ? { repo: values["--repo"] } : {}),
86
+ ...(values["--title"] !== undefined ? { title: values["--title"] } : {}),
87
+ ...(values["--head"] !== undefined ? { head: values["--head"] } : {}),
88
+ base: values["--base"] ?? DEFAULT_BASE,
89
+ allowBreaking: booleans["--allow-breaking"] === true,
90
+ };
91
+ }
92
+
93
+ /** `argv` is what follows `strip`. */
94
+ export function parseStripArgs(argv: string[]): StripOptions | { help: true } {
95
+ if (helpRequested(argv)) return { help: true };
96
+ const { positionals } = parseFlags(argv, { values: [], booleans: [] }, "pr-template strip");
97
+ if (positionals.length !== 1) throw new UsageError("strip needs one file.");
98
+ return { file: positionals[0]! };
99
+ }
100
+
101
+ /** `argv` is what follows `risk`. */
102
+ export function parseRiskArgs(argv: string[]): RiskOptions | { help: true } {
103
+ if (helpRequested(argv)) return { help: true };
104
+ const { positionals, values } = parseFlags(argv, { values: ["--base"], booleans: [] }, "pr-template risk");
105
+ if (positionals.length > 0) throw new UsageError(`risk takes no argument "${positionals[0]}".`);
106
+ return { base: values["--base"] ?? DEFAULT_BASE };
107
+ }
108
+
109
+ // --------------------------------------------------------------------------- helpers
110
+
111
+ const PREFIX = "wachiman pr-template";
112
+
113
+ function templateFor(catalog: Catalog, choiceText: string | null): ResolvedTemplate {
114
+ return resolveTemplate(catalog, choiceText === null ? null : loadRepoChoice(choiceText, catalog));
115
+ }
116
+
117
+ /** A file in the working tree, or null when it is not there. */
118
+ function readIfPresent(path: string): string | null {
119
+ try {
120
+ return readFileSync(path, "utf8");
121
+ } catch (err) {
122
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
123
+ throw new ToolError(`cannot read ${path}: ${(err as Error).message}`);
124
+ }
125
+ }
126
+
127
+ function report(result: CheckResult, io: PrTemplateIo): number {
128
+ for (const f of result.findings) io.stderr(`${PREFIX}: ${f.code}: ${f.message}`);
129
+ if (!result.ok) return 1;
130
+ io.stdout("ok\n");
131
+ return 0;
132
+ }
133
+
134
+ const keyOf = (f: Finding) => `${f.code}: ${f.message}`;
135
+
136
+ /** What the other template would say differently, as lines for the output. */
137
+ function compareLines(source: string, here: Finding[], base: Finding[]): string[] {
138
+ const hereKeys = new Set(here.map(keyOf));
139
+ const baseKeys = new Set(base.map(keyOf));
140
+ const onlyBase = base.filter((f) => !hereKeys.has(keyOf(f)));
141
+ const onlyHere = here.filter((f) => !baseKeys.has(keyOf(f)));
142
+ if (onlyBase.length === 0 && onlyHere.length === 0) return [`the template on the base branch (${source}) would report the same.`];
143
+ return [
144
+ `the template on the base branch (${source}) would report differently:`,
145
+ ...onlyBase.map((f) => ` only the base template reports: ${keyOf(f)}`),
146
+ ...onlyHere.map((f) => ` only this pull request's template reports: ${keyOf(f)}`),
147
+ ];
148
+ }
149
+
150
+ function extensionFrom(text: string | null, warn: (line: string) => void): RiskExtension | null {
151
+ return text === null ? null : parseRiskExtension(text, warn);
152
+ }
153
+
154
+ // --------------------------------------------------------------------------- check
155
+
156
+ export function runCheck(opts: CheckOptions, repoDir: string, io: PrTemplateIo, deps: PrTemplateDeps = {}): number {
157
+ try {
158
+ return opts.pr !== undefined ? checkPr(opts.pr, opts, io, deps) : checkFile(opts, repoDir, io, deps);
159
+ } catch (err) {
160
+ if (err instanceof UsageError || err instanceof ToolError) {
161
+ io.stderr(`${PREFIX}: error: ${err.message}`);
162
+ return 2;
163
+ }
164
+ throw err;
165
+ }
166
+ }
167
+
168
+ function checkFile(opts: CheckOptions, repoDir: string, io: PrTemplateIo, deps: PrTemplateDeps): number {
169
+ const run = deps.run ?? defaultRunner;
170
+ const catalog = deps.catalog ?? loadCatalog();
171
+ const warn = (line: string) => io.stderr(`${PREFIX}: warning: ${line}`);
172
+
173
+ const file = resolve(deps.fileBase ?? repoDir, opts.file!);
174
+ let body: string;
175
+ try {
176
+ body = readFileSync(file, "utf8");
177
+ } catch (err) {
178
+ throw new ToolError(`cannot read ${opts.file}: ${(err as Error).message}`);
179
+ }
180
+ const template = templateFor(catalog, readIfPresent(join(repoDir, CHOICE_FILE)));
181
+
182
+ let head = opts.head;
183
+ if (!head) {
184
+ try {
185
+ head = gitHead(run, repoDir);
186
+ } catch (err) {
187
+ warn(`footer head comparison skipped: ${(err as Error).message}`);
188
+ }
189
+ }
190
+ let files: ChangedFile[] | undefined;
191
+ let riskExtension: RiskExtension | null = null;
192
+ let riskError: string | undefined;
193
+ let commitMessages: string[] = [];
194
+ // two independent reads: a failure in one is reported as its own step and never discards the other
195
+ try {
196
+ const found = changesFromGit(run, repoDir, opts.base);
197
+ files = found.changes;
198
+ riskExtension = extensionFrom(gitFileAt(run, repoDir, found.mergeBase, RISK_EXTENSION_FILE), warn);
199
+ } catch (err) {
200
+ riskError = (err as Error).message;
201
+ files = undefined;
202
+ warn(`the risk floor could not be computed: ${riskError}`);
203
+ }
204
+ try {
205
+ commitMessages = commitMessagesFromGit(run, repoDir, opts.base);
206
+ } catch (err) {
207
+ warn(`commit message check skipped: ${(err as Error).message}`);
208
+ }
209
+
210
+ return report(
211
+ checkDescription({
212
+ body,
213
+ title: opts.title,
214
+ head,
215
+ template,
216
+ catalog,
217
+ ...(files !== undefined ? { files, riskExtension } : {}),
218
+ ...(riskError !== undefined ? { riskError } : {}),
219
+ commitMessages,
220
+ allowBreaking: opts.allowBreaking,
221
+ warn,
222
+ }),
223
+ io,
224
+ );
225
+ }
226
+
227
+ function checkPr(number: number, opts: CheckOptions, io: PrTemplateIo, deps: PrTemplateDeps): number {
228
+ const run = deps.run ?? defaultRunner;
229
+ const catalog = deps.catalog ?? loadCatalog();
230
+ const warn = (line: string) => io.stderr(`${PREFIX}: warning: ${line}`);
231
+
232
+ const pr = ghPrView(run, number, opts.repo);
233
+ // the PR's own template, read at its head commit and never from the working tree
234
+ const template = templateFor(catalog, ghFileAt(run, pr.headRepo, CHOICE_FILE, pr.headSha));
235
+
236
+ let files: ChangedFile[] | undefined;
237
+ let riskError: string | undefined;
238
+ try {
239
+ files = ghPrDiff(run, number, opts.repo);
240
+ } catch (err) {
241
+ riskError = (err as Error).message;
242
+ }
243
+ // the risk extension comes from the base branch, so a PR cannot lower its own floor; a file that
244
+ // cannot be fetched is an error (exit 2), never a lower floor
245
+ let riskExtension: RiskExtension | null = null;
246
+ try {
247
+ riskExtension = extensionFrom(ghFileAt(run, pr.baseRepo, RISK_EXTENSION_FILE, pr.baseRef), warn);
248
+ } catch (err) {
249
+ if (!(err instanceof ToolError)) throw err;
250
+ throw new ToolError(`cannot read ${RISK_EXTENSION_FILE} from ${pr.baseRepo}@${pr.baseRef}: ${err.message}`);
251
+ }
252
+
253
+ const common = {
254
+ body: pr.body,
255
+ title: pr.title,
256
+ head: pr.headSha,
257
+ catalog,
258
+ ...(files !== undefined ? { files, riskExtension } : {}),
259
+ ...(riskError !== undefined ? { riskError } : {}),
260
+ commitMessages: pr.commitMessages,
261
+ allowBreaking: opts.allowBreaking,
262
+ };
263
+ const result = checkDescription({ ...common, template, warn });
264
+
265
+ const changesTemplate = pr.paths.includes(CHOICE_FILE) || (files ?? []).some((f) => f.path === CHOICE_FILE);
266
+ if (changesTemplate) {
267
+ io.stdout("checked against the template in this pull request\n");
268
+ // the comparison is advisory: when the base's template cannot be fetched, the result below still stands
269
+ let baseText: string | null | undefined;
270
+ try {
271
+ baseText = ghFileAt(run, pr.baseRepo, CHOICE_FILE, pr.baseRef);
272
+ } catch (err) {
273
+ if (!(err instanceof ToolError)) throw err;
274
+ io.stdout(`the comparison with the template on the base branch is unavailable: ${err.message}\n`);
275
+ }
276
+ if (baseText !== undefined) {
277
+ const source = baseText === null ? "the default, the base has no .github/pr-template.json" : CHOICE_FILE;
278
+ try {
279
+ const baseResult = checkDescription({ ...common, template: templateFor(catalog, baseText) });
280
+ for (const line of compareLines(source, result.findings, baseResult.findings)) io.stdout(`${line}\n`);
281
+ } catch (err) {
282
+ if (!(err instanceof UsageError)) throw err;
283
+ io.stdout(`the template on the base branch is not valid, so there is nothing to compare with: ${err.message}\n`);
284
+ }
285
+ }
286
+ }
287
+ return report(result, io);
288
+ }
289
+
290
+ // --------------------------------------------------------------------------- strip and risk
291
+
292
+ export function runStrip(opts: StripOptions, repoDir: string, io: PrTemplateIo, deps: PrTemplateDeps = {}): number {
293
+ try {
294
+ let text: string;
295
+ try {
296
+ text = readFileSync(resolve(repoDir, opts.file), "utf8");
297
+ } catch (err) {
298
+ throw new ToolError(`cannot read ${opts.file}: ${(err as Error).message}`);
299
+ }
300
+ io.stdout(stripDescription(text, deps.catalog ? { catalog: deps.catalog } : {}));
301
+ return 0;
302
+ } catch (err) {
303
+ if (err instanceof UsageError || err instanceof ToolError) {
304
+ io.stderr(`${PREFIX}: error: ${err.message}`);
305
+ return 2;
306
+ }
307
+ throw err;
308
+ }
309
+ }
310
+
311
+ export function runRisk(opts: RiskOptions, repoDir: string, io: PrTemplateIo, deps: PrTemplateDeps = {}): number {
312
+ const run = deps.run ?? defaultRunner;
313
+ const warn = (line: string) => io.stderr(`${PREFIX}: warning: ${line}`);
314
+ try {
315
+ const { mergeBase, changes } = changesFromGit(run, repoDir, opts.base);
316
+ const extension = extensionFrom(gitFileAt(run, repoDir, mergeBase, RISK_EXTENSION_FILE), warn);
317
+ io.stdout(`${formatRisk(computeRisk(changes, extension, warn))}\n`);
318
+ return 0;
319
+ } catch (err) {
320
+ if (err instanceof ToolError) {
321
+ // Only a failure to find the merge base says the base ref is the problem; any other git or gh failure is not about it.
322
+ const aboutBase = /^git merge-base failed/.test(err.message);
323
+ io.stderr(`${PREFIX}: error: ${err.message}${aboutBase ? ` (pass --base <ref> if ${opts.base} does not exist)` : ""}`);
324
+ return 2;
325
+ }
326
+ throw err;
327
+ }
328
+ }
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Checks a PR description against a resolved template (ADR 0050, 0051). The rules are those of the
3
+ * earlier Python checker, and its finding codes are kept. What changed is where the lists come
4
+ * from: headings, status rows, collapsed blocks and their order come from the template, and the
5
+ * locked entries (the Risk row, `## Needs you`, the Wachiman block and the footer) come from the
6
+ * catalog, so a repository's `.github/pr-template.json` can never remove them.
7
+ *
8
+ * `breaking-change` and `adr-bare-number` are not template rules: they run on every description.
9
+ * This checks structure, not truth.
10
+ *
11
+ * The inside of the Wachiman block is Wachiman's own text (a grade, a table, `<details>` with
12
+ * plain summaries), so the structural rules do not read it; `breaking-change` does, because a
13
+ * squash merge copies the whole body.
14
+ */
15
+ import { loadCatalog, type Catalog, type CatalogEntry, type DetailsEntry, type FooterEntry, type SectionEntry, type StatusRowEntry } from "./catalog";
16
+ import { parseDescription, type ParsedDescription } from "./describe";
17
+ import { computeRisk, LEVELS, type ChangedFile, type Risk, type RiskExtension, type RiskLevel } from "./pr-risk";
18
+ import type { ResolvedTemplate } from "./resolve";
19
+
20
+ export const FINDING_CODES = [
21
+ "heading-missing",
22
+ "heading-order",
23
+ "heading-unknown",
24
+ "section-missing",
25
+ "status-row-missing",
26
+ "needs-you-empty",
27
+ "adr-bare-number",
28
+ "breaking-change",
29
+ "risk-unstated",
30
+ "risk-unverified",
31
+ "risk-below-floor",
32
+ "footer-missing",
33
+ "footer-head-mismatch",
34
+ "block-missing",
35
+ "details-unknown",
36
+ "details-order",
37
+ "changes-too-many-rows",
38
+ ] as const;
39
+ export type FindingCode = (typeof FINDING_CODES)[number];
40
+
41
+ export interface Finding {
42
+ code: FindingCode;
43
+ message: string;
44
+ /** 1-based line in the description, when the finding points at one. */
45
+ line?: number;
46
+ }
47
+
48
+ export interface CheckResult {
49
+ ok: boolean;
50
+ findings: Finding[];
51
+ }
52
+
53
+ export interface CheckInput {
54
+ /** The description. Null or empty is a description with nothing in it. */
55
+ body: string | null | undefined;
56
+ /** The PR title; used only for the `!` breaking marker. */
57
+ title?: string | null;
58
+ /** The head commit. Missing skips the footer comparison (the footer must still exist). */
59
+ head?: string | null;
60
+ /** The effective template of the repository. */
61
+ template: ResolvedTemplate;
62
+ /** Where the locked entries come from. Default: the shipped catalog. */
63
+ catalog?: Catalog;
64
+ /** The changed files. With them the risk floor is computed here. */
65
+ files?: readonly ChangedFile[];
66
+ /** Parsed `.github/pr-risk.toml`, used with `files`. */
67
+ riskExtension?: RiskExtension | null;
68
+ /** A floor computed elsewhere (a level or a Risk); wins over `files`. Null skips the comparison. */
69
+ risk?: Risk | RiskLevel | null;
70
+ /** Why the floor could not be computed. It fails the check unless Risk is stated High. */
71
+ riskError?: string | null;
72
+ /** Commit messages of the PR, scanned for the breaking-change marker. */
73
+ commitMessages?: readonly string[];
74
+ /** Pass only when the owner asked for a breaking change. */
75
+ allowBreaking?: boolean;
76
+ /** Told about a problem in `riskExtension` while the floor is computed from `files`: an invalid regex that is ignored. */
77
+ warn?: (line: string) => void;
78
+ }
79
+
80
+ // --------------------------------------------------------------------------- patterns
81
+
82
+ const ADR_REF = /\bADRs?[ -]?#?\d+\b/i;
83
+ const LINK = /\[([^\]]*)\]\(([^)\s]*)(?:\s+"[^"]*")?\)/g;
84
+ const FENCE_BLOCK = /^[ \t]*(```|~~~)[^\n]*\n[\s\S]*?^[ \t]*\1[^\n]*$/gm;
85
+ const BREAKING = /BREAKING[ -]CHANGE/;
86
+ const BANG_TITLE = /^[a-z]+(\([^)]*\))?!:/i;
87
+
88
+ /** The letters left once ADR numbers and everything that is not a letter are gone. */
89
+ const letters = (text: string) => text.replace(new RegExp(ADR_REF.source, "gi"), "").replace(/[^\p{L}]+/gu, "");
90
+
91
+ /** Mentions of an ADR by number alone: a link whose only text is the number still counts. */
92
+ export function bareAdrMentions(input: string): string[] {
93
+ let text = input.replace(FENCE_BLOCK, "");
94
+ text = text.replace(LINK, (_whole, label: string) => (ADR_REF.test(label) && letters(label) === "" ? label : " "));
95
+ text = text.replace(/https?:\/\/\S+/g, " ");
96
+ return [...text.matchAll(new RegExp(ADR_REF.source, "gi"))].map((m) => m[0]);
97
+ }
98
+
99
+ /**
100
+ * Data rows of the first Markdown table in `text`: the contiguous lines with an unescaped `|` right
101
+ * after its separator line (which has a header line with a `|` above it). A table may be written
102
+ * without its outer pipes. Without a separator, the lines that start with `|` stand in, minus the header.
103
+ */
104
+ export function tableRows(text: string): string[] {
105
+ const hasPipe = (l: string) => /(?<!\\)\|/.test(l);
106
+ const lines = text.split("\n").map((l) => l.trim());
107
+ const sep = lines.findIndex((l, i) => i > 0 && /^\|?[\s:|-]+\|?$/.test(l) && l.includes("-") && hasPipe(lines[i - 1]!));
108
+ if (sep === -1) return lines.filter((l) => l.startsWith("|")).slice(1);
109
+ const rows: string[] = [];
110
+ for (const l of lines.slice(sep + 1)) {
111
+ if (l === "" || !hasPipe(l)) break;
112
+ rows.push(l);
113
+ }
114
+ return rows;
115
+ }
116
+
117
+ function splitCells(row: string): string[] {
118
+ let cells = row.trim().split(/(?<!\\)\|/);
119
+ if (cells.length > 0 && cells[0]!.trim() === "") cells = cells.slice(1);
120
+ if (cells.length > 0 && cells[cells.length - 1]!.trim() === "") cells = cells.slice(0, -1);
121
+ return cells.map((c) => c.trim());
122
+ }
123
+
124
+ const quote = (text: string) => JSON.stringify(text.slice(0, 40));
125
+
126
+ function decisionRecordProblems(decisions: string): string[] {
127
+ const lines = decisions.split("<details")[0]!.split("\n").filter((l) => l.trim().startsWith("|"));
128
+ if (lines.length === 0) return [];
129
+ const header = splitCells(lines[0]!).map((c) => c.toLowerCase());
130
+ const col = header.includes("record") ? header.indexOf("record") : 2;
131
+ const problems: string[] = [];
132
+ for (const row of tableRows(lines.join("\n"))) {
133
+ const cells = splitCells(row);
134
+ const cell = cells[col] ?? "";
135
+ if (/^(none|n\/a|-|—|)$/i.test(cell.trim())) continue;
136
+ const links = [...cell.matchAll(LINK)];
137
+ if (links.length === 0) problems.push(`the Record cell ${quote(cell)} has no link`);
138
+ else if (!links.some((l) => letters(l[1]!) !== "")) problems.push(`the Record cell ${quote(cell)} links with only a number as text`);
139
+ }
140
+ return problems;
141
+ }
142
+
143
+ function statedLevel(text: string): number | null {
144
+ const m = /🟢|🟡|🔴|\b(low|medium|high)\b/i.exec(text);
145
+ if (!m) return null;
146
+ const token = m[0];
147
+ const i = LEVELS.findIndex(([emoji, name]) => token === emoji || token.toLowerCase() === name.toLowerCase());
148
+ return i === -1 ? null : i;
149
+ }
150
+
151
+ const levelOf = (risk: Risk | RiskLevel): number => (typeof risk === "number" ? risk : risk.level);
152
+
153
+ const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
154
+
155
+ /** The words before `{sha}` in the footer text, then a 7 to 40 character hex sha, backticks optional. */
156
+ function footerPattern(entry: FooterEntry): RegExp {
157
+ const prefix = entry.text.slice(0, entry.text.indexOf("{sha}")).trim() || "Describes commit";
158
+ const words = prefix.split(/\s+/).map(escapeRegex).join("\\s+");
159
+ return new RegExp(`${words}\\s+\`?([0-9a-fA-F]{7,40})\`?`);
160
+ }
161
+
162
+ // --------------------------------------------------------------------------- the template
163
+
164
+ /**
165
+ * The template with its locked entries taken from the catalog: one the template lacks is put back
166
+ * where the catalog has it, and one it carries is replaced by the catalog's version.
167
+ */
168
+ export function withLockedFromCatalog(template: ResolvedTemplate, catalog: Catalog): ResolvedTemplate {
169
+ const locked = new Map(catalog.sections.filter((e) => e.locked).map((e) => [e.id, e]));
170
+ const sections: CatalogEntry[] = template.sections.map((e) => locked.get(e.id) ?? e);
171
+ const have = new Set(sections.map((e) => e.id));
172
+ for (const entry of locked.values()) {
173
+ if (have.has(entry.id)) continue;
174
+ const later = new Set(catalog.sections.slice(catalog.sections.indexOf(entry) + 1).map((e) => e.id));
175
+ const at = sections.findIndex((e) => later.has(e.id));
176
+ sections.splice(at === -1 ? sections.length : at, 0, entry);
177
+ }
178
+ return { ...template, sections };
179
+ }
180
+
181
+ const isRequired = (e: CatalogEntry) => e.required || e.locked;
182
+
183
+ // --------------------------------------------------------------------------- the check
184
+
185
+ export function checkDescription(input: CheckInput): CheckResult {
186
+ const catalog = input.catalog ?? loadCatalog();
187
+ const template = withLockedFromCatalog(input.template, catalog);
188
+ const findings: Finding[] = [];
189
+ const add = (code: FindingCode, message: string, line?: number) => findings.push(line === undefined ? { code, message } : { code, message, line: line + 1 });
190
+
191
+ const raw = input.body ?? "";
192
+ const parsed: ParsedDescription = parseDescription(raw);
193
+
194
+ const statusEntries = template.sections.filter((e): e is StatusRowEntry => e.kind === "status-row");
195
+ const sectionEntries = template.sections.filter((e): e is SectionEntry => e.kind === "section");
196
+ const detailsEntries = template.sections.filter((e): e is DetailsEntry => e.kind === "details");
197
+ const footerEntry = template.sections.find((e): e is FooterEntry => e.kind === "footer")!;
198
+ const hasNotes = detailsEntries.some((e) => e.id === "notes");
199
+ const moveHint = hasNotes ? "move its content into Notes or one of the template's sections" : "move its content into one of the template's sections";
200
+
201
+ // headings
202
+ const allowedHeadings = sectionEntries.map((e) => e.heading);
203
+ const names = parsed.headings.map((h) => h.name);
204
+ for (const e of sectionEntries) {
205
+ if (!isRequired(e) || names.includes(e.heading)) continue;
206
+ if (e.custom) add("section-missing", `the description has no \`## ${e.heading}\` section; the repository's template requires it`);
207
+ else add("heading-missing", `the description has no \`## ${e.heading}\` heading; it is required in every description`);
208
+ }
209
+ const known = names.filter((n) => allowedHeadings.includes(n));
210
+ const idx = known.map((n) => allowedHeadings.indexOf(n));
211
+ if (idx.some((b, i) => i > 0 && b <= idx[i - 1]!)) {
212
+ add("heading-order", `the \`##\` headings are ${known.join(", ")}; each must appear once, in the order ${allowedHeadings.join(", ")}`);
213
+ }
214
+ for (const h of parsed.headings) {
215
+ if (!allowedHeadings.includes(h.name)) add("heading-unknown", `\`## ${h.name}\` is not a heading of this template; ${moveHint}`, h.line);
216
+ }
217
+
218
+ // status table
219
+ const rows = new Map<string, string>();
220
+ for (const r of parsed.statusRows) if (!rows.has(r.label)) rows.set(r.label, r.value);
221
+ for (const e of statusEntries) {
222
+ if (isRequired(e) && !rows.has(e.label)) {
223
+ add("status-row-missing", `the status table has no ${e.label} row; add \`| **${e.label}** | ... |\` (None if empty)`);
224
+ }
225
+ }
226
+
227
+ // sections that must not be empty (Needs you)
228
+ for (const e of sectionEntries) {
229
+ if (e.rule !== "not-empty") continue;
230
+ const section = parsed.sections.find((s) => s.name === e.heading);
231
+ if (!section) continue;
232
+ // Only the section's own text: not its collapsed blocks, and not the footer that follows it.
233
+ let text = parsed.structural.split("\n").slice(section.startLine + 1, section.bodyEndLine).join("\n");
234
+ text = text.replace(/^\s*[-*]\s*\[[ xX]?\]\s*$/gm, "");
235
+ text = text.replace(/\*\*(Before|After) merge:?\*\*:?/g, "");
236
+ if (text.trim() === "") {
237
+ add("needs-you-empty", `\`## ${e.heading}\` is empty; list the owner's actions as checkboxes, or write "Nothing. Merge when checks are green."`);
238
+ }
239
+ }
240
+
241
+ // an ADR cited by number
242
+ for (const mention of bareAdrMentions(parsed.structural)) {
243
+ add("adr-bare-number", `"${mention}" cites an ADR by number; say what it decides and link it, for example [One PR description template](../adr/0033-....md)`);
244
+ }
245
+ const decisions = sectionEntries.find((e) => e.id === "decisions");
246
+ const decisionsSection = decisions && parsed.sections.find((s) => s.name === decisions.heading);
247
+ if (decisionsSection) {
248
+ for (const problem of decisionRecordProblems(decisionsSection.clean)) {
249
+ add("adr-bare-number", `in \`## ${decisions!.heading}\`, ${problem}; write the ADR title as the link text`);
250
+ }
251
+ }
252
+
253
+ // the breaking-change marker, comments included
254
+ if (!input.allowBreaking) {
255
+ const fix = "remove it, or pass --allow-breaking only if the owner asked for a breaking change";
256
+ const title = input.title ?? "";
257
+ if (BANG_TITLE.test(title)) add("breaking-change", `the title ${JSON.stringify(title)} has a \`!\` (the conventional-commit breaking marker); ${fix}`);
258
+ if (BREAKING.test(raw)) {
259
+ add("breaking-change", `the body contains the breaking-change footer text (comments count: a squash merge copies them into the commit); ${fix}`);
260
+ }
261
+ (input.commitMessages ?? []).forEach((msg, i) => {
262
+ if (BREAKING.test(msg ?? "")) {
263
+ add("breaking-change", `commit message ${i + 1} contains the breaking-change footer text; reword the commit, or pass --allow-breaking only if the owner asked`);
264
+ }
265
+ });
266
+ }
267
+
268
+ // the risk row against the computed floor
269
+ const riskEntry = statusEntries.find((e) => e.rule === "risk-floor");
270
+ let computed: Risk | RiskLevel | null = input.risk === undefined ? null : input.risk;
271
+ if (input.risk === undefined && input.files !== undefined) computed = computeRisk(input.files, input.riskExtension, input.warn);
272
+ if (riskEntry && rows.has(riskEntry.label)) {
273
+ const stated = statedLevel(rows.get(riskEntry.label)!);
274
+ if (stated === null) {
275
+ add("risk-unstated", `the ${riskEntry.label} row has no level; start it with 🟢 Low, 🟡 Medium or 🔴 High`);
276
+ } else if (computed === null && input.riskError && stated < LEVELS.length - 1) {
277
+ add("risk-unverified", `the risk floor could not be computed (${input.riskError}); fix the cause (a reachable --base for a file, a working gh for --pr)`);
278
+ } else if (computed !== null && stated < levelOf(computed)) {
279
+ const why = typeof computed !== "number" && computed.rule ? ` (${computed.rule})` : "";
280
+ add("risk-below-floor", `the ${riskEntry.label} row says ${LEVELS[stated]![1]} but \`wachiman pr-template risk\` computes ${LEVELS[levelOf(computed)]![1]}${why}; raise it, an author may only raise the level`);
281
+ }
282
+ }
283
+
284
+ // footer
285
+ let sha: string | null = null;
286
+ const footerRe = footerPattern(footerEntry);
287
+ for (const sub of parsed.subs) {
288
+ const m = footerRe.exec(sub.text);
289
+ if (m) {
290
+ sha = m[1]!;
291
+ break;
292
+ }
293
+ }
294
+ if (sha === null) {
295
+ add("footer-missing", `the footer has no commit sha; keep the footer line of the template and replace the {sha} placeholder with the real commit (7 or more hex characters)`);
296
+ } else if (input.head) {
297
+ const head = input.head.toLowerCase();
298
+ const found = sha.toLowerCase();
299
+ const matches = head.startsWith(found) || (head.length < 40 && found.startsWith(head));
300
+ if (!matches) add("footer-head-mismatch", `the footer describes commit ${sha.slice(0, 12)} but the head is ${input.head.slice(0, 12)}; rewrite the description against the head and update the sha`);
301
+ }
302
+
303
+ // the Wachiman block
304
+ if (template.sections.some((e) => e.kind === "block") && parsed.blocks.length === 0) {
305
+ const block = template.sections.find((e) => e.kind === "block") as Extract<CatalogEntry, { kind: "block" }>;
306
+ add("block-missing", `the description has no Wachiman block; keep both markers, ${block.start} and ${block.end}, from the template`);
307
+ }
308
+
309
+ // collapsed blocks
310
+ const allowedDetails = detailsEntries.map((e) => e.summary);
311
+ const present: string[] = [];
312
+ for (const d of parsed.details) {
313
+ if (d.name === null) {
314
+ add("details-unknown", `a collapsed block has no bold title in its summary; use one of ${allowedDetails.join(", ")}, or put the text in ${hasNotes ? "Notes" : "a section"}`, d.startLine);
315
+ } else if (!allowedDetails.includes(d.name)) {
316
+ add("details-unknown", `the collapsed block "${d.name}" is not allowed; use one of ${allowedDetails.join(", ")}, or put the text in ${hasNotes ? "Notes" : "a section"}`, d.startLine);
317
+ } else {
318
+ present.push(d.name);
319
+ }
320
+ }
321
+ const didx = present.map((n) => allowedDetails.indexOf(n));
322
+ if (didx.some((b, i) => i > 0 && b <= didx[i - 1]!)) {
323
+ add("details-order", `the collapsed blocks are ${present.join(", ")}; each must appear once, in the order ${allowedDetails.join(", ")}`);
324
+ }
325
+ for (const e of detailsEntries) {
326
+ if (isRequired(e) && !parsed.details.some((d) => d.name === e.summary)) {
327
+ add("section-missing", `the description has no "${e.summary}" collapsed block; the template requires it`);
328
+ }
329
+ const max = /^max-rows:(\d+)$/.exec(e.rule ?? "");
330
+ if (!max) continue;
331
+ const block = parsed.details.find((d) => d.name === e.summary);
332
+ if (!block) continue;
333
+ const n = tableRows(block.clean).length;
334
+ if (n > Number(max[1])) add("changes-too-many-rows", `the ${e.summary} table has ${n} rows; group them down to at most ${max[1]}`);
335
+ }
336
+
337
+ return { ok: findings.length === 0, findings };
338
+ }