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
package/src/local.ts CHANGED
@@ -13,13 +13,16 @@
13
13
  */
14
14
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
15
15
  import { resolve } from "node:path";
16
- import { loadConfig, UsageError } from "./config";
16
+ import { loadConfig, UsageError, type EngineConfig } from "./config";
17
17
  import {
18
18
  buildLocalInput,
19
19
  DEFAULT_MAX_DEPTH,
20
20
  EMPTY_TREE_LABEL,
21
+ localRepoSettings,
22
+ localSettingsCommit,
21
23
  type LocalRefs,
22
24
  removeSnapshot,
25
+ type SettingsScope,
23
26
  snapshotHead,
24
27
  warnSnapshotDifferences,
25
28
  } from "./connectors/local-git";
@@ -27,6 +30,7 @@ import { DEFAULT_EXCLUDE, estimateFor, filterFiles, planBatches, reviewChange, r
27
30
  import { sizeGate, type ReviewEstimate } from "./estimate";
28
31
  import { spawnGit } from "./evidence";
29
32
  import { assertReviewInputFormat, REVIEW_INPUT_V2 } from "./formats";
33
+ import { applyRepoSettings, fileSettingsNote, ignoredSettingsNote, wantsRepoSettings, type RepoSettings } from "./repo-settings";
30
34
  import { workingTreeInput, snapshotWorkingTree } from "./connectors/working-tree";
31
35
  import { historyRoot, historySettings, saveRun } from "./history";
32
36
  import { readConfig, wachimanHome } from "./accounts/config";
@@ -248,10 +252,10 @@ export function interruptible(provider: ProviderAdapter, state: { interrupted: b
248
252
  preflight: () => provider.preflight(),
249
253
  modelLabel: () => provider.modelLabel(),
250
254
  leaksSecret: (texts) => provider.leaksSecret(texts),
251
- run: (request) => {
255
+ run: async (request) => {
252
256
  if (state.interrupted) throw new InterruptedError("the review was interrupted");
253
257
  try {
254
- return provider.run(request);
258
+ return await provider.run(request);
255
259
  } catch (error) {
256
260
  if (error instanceof InterruptedError) state.interrupted = true;
257
261
  throw error;
@@ -281,6 +285,34 @@ export interface LocalSession {
281
285
  state: { interrupted: boolean };
282
286
  }
283
287
 
288
+ /**
289
+ * `config` with the model and the effort the repository's `.wachiman.yml` sets where nothing explicit
290
+ * did. The file is read at the commit the instruction files are read at (`localSettingsCommit`),
291
+ * never from the working tree or the head, for the same reason as in Actions: the change under
292
+ * review cannot choose what it is reviewed under. One stderr line says when the file decided. A
293
+ * broken file at that commit is ignored with a warning and the run continues on the environment and
294
+ * the defaults, so the change that fixes it can be reviewed.
295
+ */
296
+ export function withLocalSettings(config: EngineConfig, repoDir: string, scope: SettingsScope, stderr: (line: string) => void): EngineConfig {
297
+ if (!wantsRepoSettings(config)) return config;
298
+ const sha = localSettingsCommit(repoDir, scope);
299
+ if (sha === undefined) return config;
300
+ const where = `${scope.inputBase !== undefined ? "the input's base" : scope.workingTree ? "HEAD" : "the merge-base"} ${short(sha)}`;
301
+ let settings: RepoSettings | undefined;
302
+ try {
303
+ settings = localRepoSettings(repoDir, sha);
304
+ } catch (error) {
305
+ if (!(error instanceof UsageError)) throw error;
306
+ stderr(ignoredSettingsNote(error.message, where));
307
+ return config;
308
+ }
309
+ if (!settings) return config;
310
+ const next = applyRepoSettings(config, settings, { where, warn: stderr });
311
+ const note = fileSettingsNote(next, where);
312
+ if (note) stderr(`settings: ${note}`);
313
+ return next;
314
+ }
315
+
284
316
  /**
285
317
  * The settings, the account (ADR 0029), the subscription-mode provider and, with `--verify`, the
286
318
  * verifier, all checked before any call. Nothing in the reviewed repository takes part: a corrupt
@@ -293,12 +325,15 @@ export function openLocalSession(p: {
293
325
  env: Record<string, string | undefined>;
294
326
  stderr: (line: string) => void;
295
327
  deps: LocalDeps;
328
+ /** The scope flags: they decide the commit whose `.wachiman.yml` is read (the one the instruction files are read at). */
329
+ scope?: SettingsScope;
296
330
  }): LocalSession {
297
331
  const { env, repoDir, deps } = p;
298
- const loaded = loadConfig(env, p.stderr);
299
- if (loaded.provider !== "claude-code") {
300
- throw new UsageError(`WACHIMAN_PROVIDER=${loaded.provider}: the local review runs only on Claude Code, your signed-in \`claude\`.`);
332
+ const loadedEnv = loadConfig(env, p.stderr);
333
+ if (loadedEnv.provider !== "claude-code") {
334
+ throw new UsageError(`WACHIMAN_PROVIDER=${loadedEnv.provider}: the local review runs only on Claude Code, your signed-in \`claude\`.`);
301
335
  }
336
+ const loaded = withLocalSettings(loadedEnv, repoDir, p.scope ?? {}, p.stderr);
302
337
  // A person ran it: no automatic ceiling (decision 14).
303
338
  const config = {
304
339
  ...loaded,
@@ -444,7 +479,7 @@ export function sizeWarning(estimate: ReviewEstimate, gate: number, budgetUsd: n
444
479
  return `warning: reviewing all of this would cost about $${estimate.usd.toFixed(2)} at API prices (${estimate.batches} batches × $${estimate.perBatchUsd.toFixed(2)} for ${model}), above the $${gate.toFixed(2)} size gate. Local runs are never refused; this one continues and stops at its budget, $${budgetUsd.toFixed(2)} (WACHIMAN_BUDGET_USD).`;
445
480
  }
446
481
 
447
- export function runLocal(
482
+ export async function runLocal(
448
483
  args: LocalArgs,
449
484
  repoDir: string,
450
485
  env: Record<string, string | undefined>,
@@ -454,7 +489,7 @@ export function runLocal(
454
489
  engineVersion: string;
455
490
  },
456
491
  deps: LocalDeps = {},
457
- ): number {
492
+ ): Promise<number> {
458
493
  const fileInput = args.input === undefined ? undefined : readInputFile(args.input);
459
494
  if ((args.workingTree || fileInput?.change.kind === "working-tree") && args.resultVersion === 1) {
460
495
  throw new UsageError("Working-tree reviews require --result-version 2; a tree is not a commit.");
@@ -470,6 +505,14 @@ export function runLocal(
470
505
  env,
471
506
  stderr: io.stderr,
472
507
  deps,
508
+ scope: {
509
+ workingTree: args.workingTree,
510
+ base: args.base,
511
+ commit: args.commit,
512
+ from: args.from,
513
+ maxDepth: args.maxDepth,
514
+ inputBase: fileInput?.change.base.sha,
515
+ },
473
516
  });
474
517
 
475
518
  let release: (() => void) | undefined;
@@ -529,7 +572,7 @@ export function runLocal(
529
572
  : "verify: off",
530
573
  );
531
574
 
532
- const result = reviewChange(input, reviewOptionsOf(config, config.budgetUsd, profile.kind === "managed" ? "isolated" : "default"), {
575
+ const result = await reviewChange(input, reviewOptionsOf(config, config.budgetUsd, profile.kind === "managed" ? "isolated" : "default"), {
533
576
  provider,
534
577
  ...(verifier ? { verifier } : {}),
535
578
  // The verifier reads the code before the change too; made once, only when there is something to check.
@@ -575,6 +618,7 @@ export function runLocal(
575
618
  io.stderr(thisRunText(result, annotation));
576
619
  io.stderr(sinceLastRunText(annotation));
577
620
  }
621
+ const settingsFrom = { model: config.modelSource === "file", effort: config.effortSource === "file" };
578
622
  const text =
579
623
  args.format === "json"
580
624
  ? renderJson(
@@ -584,9 +628,10 @@ export function runLocal(
584
628
  annotation ? result.findings.map((_, i) => annotation!.byIndex.get(i)?.id) : undefined,
585
629
  )
586
630
  : args.format === "markdown"
587
- ? renderMarkdown(result, { profileNote, history: annotation })
631
+ ? renderMarkdown(result, { profileNote, history: annotation, settingsFrom })
588
632
  : renderTerminal(result, {
589
633
  profileNote,
634
+ settingsFrom,
590
635
  agentPrompt: args.agentPrompt,
591
636
  history: annotation,
592
637
  });
@@ -155,11 +155,11 @@ type IdentifiedResult = ReviewResult & { findings: { id: string }[] };
155
155
  type Attempt = { ok: true; result: IdentifiedResult } | { ok: false; why: string } | { interrupted: true };
156
156
 
157
157
  /** One review call: succeeds only with a complete `/2` result in which every finding has a history id. */
158
- function attempt(args: LocalArgs, repoDir: string, env: Record<string, string | undefined>, io: LoopIo, deps: LoopDeps): Attempt {
158
+ async function attempt(args: LocalArgs, repoDir: string, env: Record<string, string | undefined>, io: LoopIo, deps: LoopDeps): Promise<Attempt> {
159
159
  let out = "";
160
160
  let code: number;
161
161
  try {
162
- code = (deps.review ?? runLocal)(args, repoDir, env, { stdout: (t) => (out += t), stderr: io.stderr, engineVersion: io.engineVersion }, deps);
162
+ code = await (deps.review ?? runLocal)(args, repoDir, env, { stdout: (t) => (out += t), stderr: io.stderr, engineVersion: io.engineVersion }, deps);
163
163
  } catch (error) {
164
164
  if (error instanceof UsageError) throw error;
165
165
  return { ok: false, why: error instanceof Error ? error.message : String(error) };
@@ -188,7 +188,7 @@ interface LoopIo {
188
188
  const withVerdicts = (ledger: LedgerEntry[], verdicts: ReturnType<typeof readVerdicts>): LoopFinding[] =>
189
189
  ledger.map((e) => ({ ...e, ...(verdicts.get(e.id) ? { verdict: { verdict: verdicts.get(e.id)!.verdict, reason: verdicts.get(e.id)!.reason } } : {}) }));
190
190
 
191
- export function runLoop(args: LoopArgs, repoDir: string, env: Record<string, string | undefined>, io: LoopIo, deps: LoopDeps = {}): number {
191
+ export async function runLoop(args: LoopArgs, repoDir: string, env: Record<string, string | undefined>, io: LoopIo, deps: LoopDeps = {}): Promise<number> {
192
192
  const root = historyRoot(wachimanHome(env));
193
193
  const key = repositoryKey(repoDir).key;
194
194
  const branch = currentBranch(repoDir);
@@ -258,10 +258,10 @@ export function runLoop(args: LoopArgs, repoDir: string, env: Record<string, str
258
258
  ...(args.profile !== undefined ? { profile: args.profile } : {}),
259
259
  ...(args.maxDepth !== undefined ? { maxDepth: args.maxDepth } : {}),
260
260
  };
261
- let made = attempt(localArgs, repoDir, env, io, deps);
261
+ let made = await attempt(localArgs, repoDir, env, io, deps);
262
262
  if ("ok" in made && !made.ok) {
263
263
  io.stderr(`loop: the review failed (${made.why}); trying once more.`);
264
- made = attempt(localArgs, repoDir, env, io, deps);
264
+ made = await attempt(localArgs, repoDir, env, io, deps);
265
265
  }
266
266
  if ("interrupted" in made) return 130;
267
267
  if (!made.ok) {
@@ -0,0 +1,434 @@
1
+ /**
2
+ * Adopting an unmanaged `.github/pull_request_template.md` (ADR 0052). The file is read in blocks
3
+ * (a table row, a heading, a `<details>` element, an HTML comment, or a run of lines up to a blank
4
+ * line) and split into the template's own structure, which the catalog replaces, and everything
5
+ * else, which moves into `.github/pr-template.json`:
6
+ *
7
+ * - what the catalog knows (guide comments, the status table, its `##` sections, its `<details>`
8
+ * blocks, the Wachiman block, the footer) is dropped, because the catalog generates it again;
9
+ * - an unknown status row, `##` section or `<details>` block becomes a `custom` entry;
10
+ * - any other block goes to `preamble`, in order.
11
+ *
12
+ * What the loader (`loadRepoChoice`) would reject never reaches the output: a name it refuses stays
13
+ * in the preamble as ordinary lines, a Wachiman marker (any `<!-- wachiman:` comment) is dropped
14
+ * (the catalog writes its own), and a comment that is opened and never closed (or closed and never
15
+ * opened) or a fenced code block that is never closed refuses the adoption with a `UsageError`,
16
+ * before anything is written.
17
+ *
18
+ * The report lists every block that moved and every comment taken for a guide, so a repository
19
+ * comment misread as guidance is visible (and still in the backup).
20
+ */
21
+ import { UsageError } from "../config";
22
+ import { checkCustomName, commentProblem, CUSTOM_NAME_KEY, entryName, fenceProblem, type Catalog, type CatalogEntry, type CustomEntry, type CustomKind } from "./catalog";
23
+ import { LEGACY_HEADER_PREFIX, collapseSpace, isLegacyGuide } from "./legacy-guides";
24
+ import { STATUS_GUIDE_LEAD, normalizeForStamp } from "./render";
25
+
26
+ export interface Adoption {
27
+ custom: CustomEntry[];
28
+ /** Blocks and lines for `preamble`; an empty string is the blank line between two blocks that were apart. */
29
+ preamble: string[];
30
+ /** Catalog entries that are not in the default template but were in the old file. */
31
+ add: string[];
32
+ report: string[];
33
+ }
34
+
35
+ const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase();
36
+ const clip = (text: string, n = 90) => (text.length > n ? `${text.slice(0, n - 1)}…` : text);
37
+ const LIST_ITEM = /^\s{0,3}([-*+]|\d+[.)])\s/;
38
+ const HEADING = /^(#{1,6})\s+(.*?)\s*$/;
39
+ const DETAILS_OPEN = /^\s*<details\b[^>]*>\s*<summary>(.*?)<\/summary>\s*$/i;
40
+ const STATUS_ROW = /^\|\s*\*\*(.+?)\*\*\s*\|(.*)\|\s*$/;
41
+ const TABLE_HEADER = /^\|\s*\|\s*\|\s*$/;
42
+ const TABLE_SEPARATOR = /^\|(\s*:?-+:?\s*\|)+\s*$/;
43
+ const WACHIMAN_MARKER = /<!--\s*wachiman:|wachiman:confidence:|wachiman:pr-template/i;
44
+ const FOOTER = /^<sub>(.*)<\/sub>\s*$/;
45
+
46
+ /** Whether `line` starts a block of its own, so a text run ends before it. */
47
+ const startsBlock = (line: string) => /^\s*<!--/.test(line) || /^#{1,6}\s/.test(line) || /^\s*<\/?details\b/i.test(line) || /^\s*\|/.test(line) || /^<sub>/.test(line);
48
+
49
+ const slug = (name: string) =>
50
+ name
51
+ .toLowerCase()
52
+ .replace(/[^a-z0-9]+/g, "-")
53
+ .replace(/^-+|-+$/g, "") || "custom";
54
+
55
+ export interface AdoptContext {
56
+ catalog: Catalog;
57
+ /** Custom ids and names the repository's JSON already has (to avoid a duplicate when merging). */
58
+ existingCustom?: CustomEntry[];
59
+ /** The `drop` list of the repository's JSON: a section it dropped is not added back. */
60
+ existingDrop?: string[];
61
+ }
62
+
63
+ export function analyzeUnmanaged(fileText: string, { catalog, existingCustom = [], existingDrop = [] }: AdoptContext): Adoption {
64
+ const lines = fileText.replace(/\r\n?/g, "\n").split("\n");
65
+ const result: Adoption = { custom: [], preamble: [], add: [], report: [] };
66
+ const report = (line: string) => result.report.push(line);
67
+
68
+ const lockedNames = catalog.sections.filter((e) => e.locked).map((e) => entryName(e)).filter((n): n is string => n !== undefined);
69
+ const catalogGuides = new Set(catalog.sections.flatMap((e) => (e.guide === undefined ? [] : [collapseSpace(e.guide)])).concat(collapseSpace(catalog.intro)));
70
+ const usedIds = new Set([...catalog.sections.map((e) => e.id), ...existingCustom.map((c) => c.id)]);
71
+ const knownCount = { rows: 0, sections: 0, details: 0 };
72
+
73
+ const findKnown = (kind: CatalogEntry["kind"], name: string) => catalog.sections.find((e) => e.kind === kind && entryName(e) !== undefined && same(entryName(e)!, name));
74
+ // A table line is compared as a formatter leaves it equal: the padding of a cell and the width of a separator do not count.
75
+ const canon = (line: string) => normalizeForStamp(line).trim();
76
+ const bodyOf = (e: CatalogEntry): Set<string> => new Set(("body" in e ? e.body : []).map(canon).filter((l) => l !== ""));
77
+
78
+ type Ctx = { known: CatalogEntry } | { custom: CustomEntry } | null;
79
+ let ctx: Ctx = null;
80
+ let afterKnown = false;
81
+ let prevRowId: string | undefined;
82
+ let prevOtherId: string | undefined;
83
+ let sawHeader = false;
84
+ let lastPreambleEnd = -1;
85
+ // One entry per `<details>` that is open: "moved" when its lines go to the preamble (so its closing tag goes too), "structure" when the catalog regenerates it.
86
+ const openDetails: ("moved" | "structure")[] = [];
87
+
88
+ const noteKnown = (e: CatalogEntry) => {
89
+ if (e.kind === "status-row") prevRowId = e.id;
90
+ else if (e.kind !== "block" && e.kind !== "footer") prevOtherId = e.id;
91
+ if (!e.default && !result.add.includes(e.id)) {
92
+ if (existingDrop.includes(e.id)) report(`"${entryName(e)}" is in the old file, but .github/pr-template.json drops it; it stays dropped.`);
93
+ else result.add.push(e.id);
94
+ }
95
+ };
96
+
97
+ const toPreamble = (blockLines: string[], start: number, end: number) => {
98
+ const items: string[] = [];
99
+ for (const raw of blockLines) {
100
+ let line = raw.replace(/<(model|sha)>/gi, (_m, tag: string) => `{${tag.toLowerCase()}}`);
101
+ if (line !== raw) report("rewrote a <model> or <sha> tag as a {model} or {sha} placeholder; GitHub hides HTML tags.");
102
+ // The catalog writes the Wachiman markers itself, and the loader refuses them in the preamble.
103
+ if (WACHIMAN_MARKER.test(line)) {
104
+ const cleaned = line.replace(/<!--\s*wachiman:[^]*?-->/gi, "");
105
+ report(`dropped a Wachiman marker from a line that was kept: ${clip(line.trim())}`);
106
+ if (WACHIMAN_MARKER.test(cleaned) || cleaned.trim() === "") continue;
107
+ line = cleaned.trimEnd();
108
+ }
109
+ if (items.length === 0 || LIST_ITEM.test(line)) items.push(line);
110
+ else items[items.length - 1] += `\n${line}`;
111
+ }
112
+ for (const item of items) {
113
+ const problem = commentProblem(item);
114
+ if (problem !== undefined) {
115
+ throw new UsageError(
116
+ `The old template ${problem} near "${clip(item.trim(), 60)}", which would hide or break the generated template. Close the comment with "-->" (or remove it) in the old file and run install again; nothing was written.`,
117
+ );
118
+ }
119
+ }
120
+ if (items.length === 0) return;
121
+ if (result.preamble.length > 0 && lastPreambleEnd !== start) result.preamble.push("");
122
+ result.preamble.push(...items);
123
+ lastPreambleEnd = end;
124
+ report(`moved to preamble: ${blockLines.map((l, i) => (i === 0 ? l.trim() : `\n ${l.trim()}`)).join("")}`);
125
+ };
126
+
127
+ const newCustom = (kind: CustomKind, name: string): CustomEntry | null => {
128
+ if (lockedNames.some((n) => same(n, name))) return null;
129
+ // The loader checks the name as it is stored; an entry it would refuse stays as ordinary lines in the preamble.
130
+ try {
131
+ checkCustomName(name.trim(), CUSTOM_NAME_KEY[kind], kind, "");
132
+ } catch (err) {
133
+ const kindName = kind === "status-row" ? "status row" : kind === "section" ? "section" : "collapsed block";
134
+ report(`"${clip(name.trim(), 40)}" cannot be a custom ${kindName} (${(err as Error).message.replace(/^:\s*/, "")}); its lines stay in the preamble as they are.`);
135
+ return null;
136
+ }
137
+ if (result.custom.some((c) => c.kind === kind && same(c.name, name))) return null;
138
+ const existing = existingCustom.find((c) => c.kind === kind && same(c.name, name));
139
+ if (existing) {
140
+ // Already a custom entry of the repository: it stays as it is; its place in the old file only moves the anchor.
141
+ if (kind === "status-row") prevRowId = existing.id;
142
+ else prevOtherId = existing.id;
143
+ report(`"${existing.name}" is already a custom entry in .github/pr-template.json; kept as it is.`);
144
+ return { ...existing };
145
+ }
146
+ let id = slug(name);
147
+ for (let n = 2; usedIds.has(id); n++) id = `${slug(name)}-${n}`;
148
+ usedIds.add(id);
149
+ const after = kind === "status-row" ? prevRowId : prevOtherId;
150
+ const entry: CustomEntry = { id, kind, name: name.trim(), required: false, ...(after !== undefined ? { after } : {}) };
151
+ result.custom.push(entry);
152
+ if (kind === "status-row") prevRowId = id;
153
+ else prevOtherId = id;
154
+ report(`kept the ${kind === "status-row" ? "status row" : kind === "section" ? "section" : "collapsed block"} "${entry.name}" as a custom entry${after ? ` after "${after}"` : ""} in .github/pr-template.json.`);
155
+ return entry;
156
+ };
157
+
158
+ const bodyCovered = (run: string[]) => {
159
+ if (ctx === null || !("known" in ctx)) return false;
160
+ const body = bodyOf(ctx.known);
161
+ return run.every((l) => l.trim() === "" || body.has(canon(l)));
162
+ };
163
+
164
+ let i = 0;
165
+ while (i < lines.length) {
166
+ const line = lines[i]!;
167
+ if (line.trim() === "") {
168
+ i++;
169
+ continue;
170
+ }
171
+
172
+ // An HTML comment of its own.
173
+ if (/^\s*<!--/.test(line)) {
174
+ let j = i;
175
+ while (j < lines.length && !lines[j]!.includes("-->", j === i ? line.indexOf("<!--") + 4 : 0)) j++;
176
+ const last = lines[Math.min(j, lines.length - 1)]!;
177
+ if (j < lines.length && last.trim().endsWith("-->")) {
178
+ const raw = lines.slice(i, j + 1);
179
+ const inner = collapseSpace(raw.join("\n").trim().replace(/^<!--/, "").replace(/-->$/, ""));
180
+ if (inner === "wachiman:confidence:start") {
181
+ let k = j + 1;
182
+ while (k < lines.length && collapseSpace(lines[k]!.replace(/^\s*<!--/, "").replace(/-->\s*$/, "")) !== "wachiman:confidence:end") k++;
183
+ if (k < lines.length) {
184
+ report("replaced the Wachiman block by the catalog's.");
185
+ ctx = null;
186
+ afterKnown = false;
187
+ i = k + 1;
188
+ continue;
189
+ }
190
+ // No end marker: nothing says where the block stops, so only the marker line goes (the catalog writes its own) and everything after it is kept.
191
+ report("a Wachiman start marker has no end marker; the marker line was dropped (the catalog writes its own) and everything after it was kept.");
192
+ ctx = null;
193
+ afterKnown = false;
194
+ i = j + 1;
195
+ continue;
196
+ }
197
+ if (inner === "wachiman:confidence:end" || inner.startsWith("wachiman:pr-template")) {
198
+ ctx = null;
199
+ afterKnown = false;
200
+ i = j + 1;
201
+ continue;
202
+ }
203
+ const isHeader = raw[0]!.trimStart().startsWith(LEGACY_HEADER_PREFIX);
204
+ const matches = isHeader || isLegacyGuide(inner) || catalogGuides.has(inner) || inner.startsWith(collapseSpace(STATUS_GUIDE_LEAD));
205
+ if (isHeader || matches || afterKnown) {
206
+ if (!isHeader && ctx !== null && "custom" in ctx && !matches && ctx.custom.guide === undefined && !/<!--|-->/.test(inner)) {
207
+ if (result.custom.includes(ctx.custom)) {
208
+ ctx.custom.guide = inner;
209
+ report(`kept the comment under "${ctx.custom.name}" as its guide: ${clip(inner)}`);
210
+ } else {
211
+ report(`the comment under "${ctx.custom.name}" was not kept as a guide: the entry is already in .github/pr-template.json and stays as it is (the comment is in the backup): ${clip(inner)}`);
212
+ }
213
+ } else {
214
+ report(`treated as a guide comment and replaced: ${clip(inner)}`);
215
+ }
216
+ afterKnown = false;
217
+ i = j + 1;
218
+ continue;
219
+ }
220
+ toPreamble(raw, i, j + 1);
221
+ afterKnown = false;
222
+ i = j + 1;
223
+ continue;
224
+ }
225
+ // An opening `<!--` with no clean end: it is ordinary text; fall through.
226
+ }
227
+
228
+ const heading = HEADING.exec(line);
229
+ if (heading) {
230
+ const level = heading[1]!.length;
231
+ const name = heading[2]!.replace(/(?:^|\s+)#+\s*$/, "");
232
+ if (level === 2) {
233
+ const known = findKnown("section", name);
234
+ if (known) {
235
+ ctx = { known };
236
+ knownCount.sections++;
237
+ noteKnown(known);
238
+ afterKnown = true;
239
+ i++;
240
+ continue;
241
+ }
242
+ const entry = newCustom("section", name);
243
+ if (entry) {
244
+ ctx = { custom: entry };
245
+ afterKnown = true;
246
+ i++;
247
+ continue;
248
+ }
249
+ }
250
+ toPreamble([line], i, i + 1);
251
+ ctx = null;
252
+ afterKnown = false;
253
+ i++;
254
+ continue;
255
+ }
256
+
257
+ const details = DETAILS_OPEN.exec(line);
258
+ if (details) {
259
+ const summary = details[1]!;
260
+ const bold = /^\s*<b>(.*?)<\/b>/i.exec(summary);
261
+ const name = (bold ? bold[1]! : summary.replace(/<[^>]+>/g, "")).trim();
262
+ const known = findKnown("details", name);
263
+ if (known) {
264
+ openDetails.push("structure");
265
+ ctx = { known };
266
+ knownCount.details++;
267
+ noteKnown(known);
268
+ afterKnown = true;
269
+ i++;
270
+ continue;
271
+ }
272
+ const entry = newCustom("details", name);
273
+ if (entry) {
274
+ ctx = { custom: entry };
275
+ openDetails.push("structure");
276
+ afterKnown = true;
277
+ i++;
278
+ continue;
279
+ }
280
+ // A locked or duplicate name: the block is the repository's, so it moves whole, with its closing tag.
281
+ openDetails.push("moved");
282
+ toPreamble([line], i, i + 1);
283
+ ctx = null;
284
+ afterKnown = false;
285
+ i++;
286
+ continue;
287
+ }
288
+ if (/^\s*<details\b/i.test(line)) {
289
+ // Any other opening tag is ordinary text, but its closing tag has to travel with it.
290
+ openDetails.push("moved");
291
+ toPreamble([line], i, i + 1);
292
+ ctx = null;
293
+ afterKnown = false;
294
+ i++;
295
+ continue;
296
+ }
297
+ if (/^\s*<\/details>\s*$/i.test(line)) {
298
+ const closed = openDetails.pop();
299
+ if (closed === "moved") {
300
+ toPreamble([line], i, i + 1);
301
+ afterKnown = false;
302
+ i++;
303
+ continue;
304
+ }
305
+ ctx = null;
306
+ afterKnown = false;
307
+ i++;
308
+ continue;
309
+ }
310
+
311
+ if (/^\s*\|/.test(line)) {
312
+ const trimmed = line.trim();
313
+ if (TABLE_HEADER.test(trimmed)) {
314
+ sawHeader = true;
315
+ i++;
316
+ continue;
317
+ }
318
+ if (TABLE_SEPARATOR.test(trimmed) && sawHeader) {
319
+ sawHeader = false;
320
+ i++;
321
+ continue;
322
+ }
323
+ sawHeader = false;
324
+ const row = STATUS_ROW.exec(trimmed);
325
+ if (row) {
326
+ const label = row[1]!;
327
+ const known = findKnown("status-row", label);
328
+ if (known) {
329
+ knownCount.rows++;
330
+ noteKnown(known);
331
+ ctx = null;
332
+ afterKnown = true;
333
+ i++;
334
+ continue;
335
+ }
336
+ const entry = newCustom("status-row", label);
337
+ if (entry) {
338
+ const cell = row[2]!.trim();
339
+ const text = collapseSpace(/^<!--(.*)-->$/.exec(cell)?.[1] ?? cell);
340
+ if (/<!--|-->|\|/.test(text) && result.custom.includes(entry)) {
341
+ // More than one value, or markup a guide cannot carry: dropping it would lose the repository's text.
342
+ throw new UsageError(
343
+ `The old template has a row of "${entry.name}" on line ${i + 1} with more than one value or markup in its cell: "${clip(trimmed, 60)}". A row keeps one plain value as its guide. Reduce the row to one value (or move the rest out of the table) in the old file and run install again; nothing was written.`,
344
+ );
345
+ } else if (text !== "" && !result.custom.includes(entry)) {
346
+ report(`the cell of "${entry.name}" was not kept as a guide: the entry is already in .github/pr-template.json and stays as it is (the cell is in the backup).`);
347
+ } else if (text !== "") {
348
+ entry.guide = text;
349
+ report(`kept the cell of "${entry.name}" as its guide: ${clip(text)}`);
350
+ }
351
+ ctx = null;
352
+ afterKnown = false;
353
+ i++;
354
+ continue;
355
+ }
356
+ }
357
+ if (bodyCovered([trimmed])) {
358
+ i++;
359
+ continue;
360
+ }
361
+ toPreamble([line], i, i + 1);
362
+ afterKnown = false;
363
+ i++;
364
+ continue;
365
+ }
366
+
367
+ const footer = FOOTER.exec(line.trim());
368
+ if (footer && /Describes commit|<sha>|\{sha\}/i.test(footer[1]!)) {
369
+ report("replaced the footer by the catalog's.");
370
+ ctx = null;
371
+ afterKnown = false;
372
+ i++;
373
+ continue;
374
+ }
375
+
376
+ // A run of lines up to a blank line or the start of another kind of block.
377
+ let j = i + 1;
378
+ while (j < lines.length && lines[j]!.trim() !== "" && !startsBlock(lines[j]!)) j++;
379
+ const run = lines.slice(i, j);
380
+ // Inside a known section the lines the catalog itself generates are structure; the others are the repository's.
381
+ const rest = run.filter((l) => !bodyCovered([l]));
382
+ if (rest.length > 0) toPreamble(rest, i, j);
383
+ afterKnown = false;
384
+ i = j;
385
+ }
386
+
387
+ // The loader reads the whole preamble, so a fence is judged across blocks (one may hold a blank line).
388
+ const openFence = fenceProblem(result.preamble);
389
+ if (openFence !== undefined) {
390
+ const at = result.preamble.findLastIndex((entry) => /^ {0,3}(`{3,}|~{3,})/m.test(entry));
391
+ const where = result.preamble.slice(Math.max(at, 0)).join("\n").trim();
392
+ throw new UsageError(
393
+ `The old template ${openFence} near "${clip(where, 60)}", which would render the rest of the generated template as code. Close the fence in the old file and run install again; nothing was written.`,
394
+ );
395
+ }
396
+
397
+ const parts = [
398
+ knownCount.rows > 0 ? `${knownCount.rows} status rows` : "",
399
+ knownCount.sections > 0 ? `${knownCount.sections} sections` : "",
400
+ knownCount.details > 0 ? `${knownCount.details} collapsed blocks` : "",
401
+ ].filter((p) => p !== "");
402
+ if (parts.length > 0) report(`replaced by the catalog's version: ${parts.join(", ")}.`);
403
+ return result;
404
+ }
405
+
406
+ /** What `.github/pr-template.json` becomes: the existing definition (or an empty one) plus what the old file contributed. */
407
+ export function mergeAdoption(base: Record<string, unknown> | null, adoption: Adoption): Record<string, unknown> {
408
+ const out: Record<string, unknown> = { base: "default", ...(base ?? {}) };
409
+ const list = (key: string) => ((out[key] as unknown[] | undefined) ?? []) as string[];
410
+
411
+ const add = [...list("add")];
412
+ for (const id of adoption.add) if (!add.includes(id)) add.push(id);
413
+ if (add.length > 0) out.add = add;
414
+
415
+ const custom = [...((out.custom as CustomEntry[] | undefined) ?? [])];
416
+ const nameKey = { "status-row": "label", section: "heading", details: "summary" } as const;
417
+ const serial = (c: CustomEntry) => {
418
+ const { name, kind, ...rest } = c;
419
+ return { id: rest.id, kind, [nameKey[kind]]: name, required: rest.required, ...(rest.guide !== undefined ? { guide: rest.guide } : {}), ...(rest.after !== undefined ? { after: rest.after } : {}) };
420
+ };
421
+ for (const c of adoption.custom) custom.push(serial(c) as unknown as CustomEntry);
422
+ if (custom.length > 0) out.custom = custom;
423
+
424
+ const preamble = [...list("preamble")];
425
+ const fresh = adoption.preamble.filter((p, i, all) => (p === "" ? all[i - 1] !== "" : !preamble.includes(p)));
426
+ while (fresh.length > 0 && fresh[0] === "") fresh.shift();
427
+ while (fresh.length > 0 && fresh[fresh.length - 1] === "") fresh.pop();
428
+ if (fresh.length > 0) {
429
+ if (preamble.length > 0 && preamble[preamble.length - 1] !== "") preamble.push("");
430
+ preamble.push(...fresh);
431
+ }
432
+ if (preamble.length > 0) out.preamble = preamble;
433
+ return out;
434
+ }