@ultimat3/cli 31.27.0 → 31.29.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 (134) hide show
  1. package/CLAUDE.md +4 -1
  2. package/README.md +14 -4
  3. package/package.json +29 -29
  4. package/src/app-manifest.ts +6 -1
  5. package/src/app-migrations-verdict.ts +84 -0
  6. package/src/cmd-doctor.ts +11 -3
  7. package/src/cmd-drill.ts +23 -9
  8. package/src/cmd-repro-spec.ts +13 -1
  9. package/src/cmd-repro.ts +37 -5
  10. package/src/cmd-upgrade-codemods.ts +71 -0
  11. package/src/cmd-upgrade-spec.ts +19 -5
  12. package/src/cmd-upgrade.ts +91 -34
  13. package/src/codemods/agents-dev-mcp.ts +50 -0
  14. package/src/codemods/authenticator-session-refusal.ts +214 -0
  15. package/src/codemods/biome-no-default-export.ts +58 -0
  16. package/src/codemods/bunfig-island-coverage.ts +33 -0
  17. package/src/codemods/chart-dashboard.ts +73 -0
  18. package/src/codemods/ci-e2e-browser-stock.ts +75 -0
  19. package/src/codemods/ci-e2e-browser.ts +63 -0
  20. package/src/codemods/codemod.ts +58 -0
  21. package/src/codemods/define-error-leaf.ts +73 -0
  22. package/src/codemods/docs-ci-parts.ts +65 -0
  23. package/src/codemods/docs-gate-prose.ts +53 -0
  24. package/src/codemods/docs-island-rows.ts +31 -0
  25. package/src/codemods/docs-shipped-guards.ts +100 -0
  26. package/src/codemods/docs-test-services.ts +62 -0
  27. package/src/codemods/engine-diff.ts +104 -0
  28. package/src/codemods/engine-edits.ts +111 -0
  29. package/src/codemods/engine-fs.ts +95 -0
  30. package/src/codemods/engine.ts +191 -0
  31. package/src/codemods/format-edited-hook-3122.ts +28 -0
  32. package/src/codemods/format-edited-hook.ts +152 -0
  33. package/src/codemods/helm-alerts-deploy.ts +85 -0
  34. package/src/codemods/helm-alerts-objective.ts +105 -0
  35. package/src/codemods/helm-alerts-stock.ts +108 -0
  36. package/src/codemods/index.ts +60 -0
  37. package/src/codemods/metrics-probe-healthz.ts +47 -0
  38. package/src/codemods/migrate-job-ordered.ts +81 -0
  39. package/src/codemods/migrate-job-stock.ts +41 -0
  40. package/src/codemods/pending.ts +36 -0
  41. package/src/codemods/repro-gitignore.ts +40 -0
  42. package/src/codemods/runtime-pin-lines.ts +109 -0
  43. package/src/codemods/runtime-pin.ts +116 -0
  44. package/src/codemods/solid-floor.ts +63 -0
  45. package/src/codemods/test-ports.ts +86 -0
  46. package/src/codemods/test-suites.ts +37 -0
  47. package/src/codemods/theme-toggle-mount-over.ts +70 -0
  48. package/src/codemods/vendored-guards.ts +186 -0
  49. package/src/codemods/verify-floor-skips.ts +88 -0
  50. package/src/codemods/verify-floor-steps.ts +90 -0
  51. package/src/doctor-advisory-floors.ts +113 -0
  52. package/src/doctor-guards.ts +39 -86
  53. package/src/doctor-superseded.ts +67 -0
  54. package/src/drill-schema-behind.ts +26 -0
  55. package/src/error-codes-doctor.ts +12 -4
  56. package/src/error-codes.ts +9 -0
  57. package/src/exercise-database.ts +7 -2
  58. package/src/framework-schema-apply.ts +7 -19
  59. package/src/framework-schema-stamp.ts +38 -3
  60. package/src/framework-schema-verify.ts +120 -0
  61. package/src/framework-schema-wait.ts +125 -0
  62. package/src/generate-files.ts +6 -5
  63. package/src/guards-built-in-codes.ts +36 -0
  64. package/src/guards-built-in-refusal.ts +25 -0
  65. package/src/guards-built-in.ts +134 -0
  66. package/src/guards-materialize.ts +42 -0
  67. package/src/guards-paths.ts +37 -0
  68. package/src/guards-shipped-names.ts +38 -0
  69. package/src/guards-vendored.ts +73 -0
  70. package/src/guards.ts +90 -34
  71. package/src/index.ts +10 -0
  72. package/src/lint-findings.ts +3 -3
  73. package/src/mcp-errors.ts +12 -1
  74. package/src/measure-scope.ts +23 -3
  75. package/src/messages-repro.ts +16 -2
  76. package/src/messages-upgrade.ts +15 -0
  77. package/src/messages.ts +1 -1
  78. package/src/repro-archive-collect.ts +161 -0
  79. package/src/repro-archive-write.ts +96 -0
  80. package/src/repro-archive.ts +161 -0
  81. package/src/repro-bundle.ts +8 -16
  82. package/src/repro-errors.ts +14 -2
  83. package/src/repro-framework.ts +53 -0
  84. package/src/repro-parse.ts +87 -0
  85. package/src/repro-redact.ts +218 -0
  86. package/src/repro-scrub.ts +257 -0
  87. package/src/role-pg-stats.ts +21 -0
  88. package/src/role-start.ts +4 -0
  89. package/src/runtime-queue.ts +27 -6
  90. package/src/serve-boot-probe.ts +97 -0
  91. package/src/serve-boot.ts +26 -1
  92. package/src/serve-retire.ts +16 -3
  93. package/src/superseded-match.ts +87 -0
  94. package/src/superseded.ts +84 -0
  95. package/src/templates/bun-image.ts +48 -0
  96. package/src/templates/chart-dashboard-panels.ts +178 -0
  97. package/src/templates/chart-dashboard.ts +9 -135
  98. package/src/templates/github/ci.yml.ts +1 -1
  99. package/src/templates/guard-released-forms.ts +112 -0
  100. package/src/templates/guard-runtime-pin-test.ts +54 -0
  101. package/src/templates/guard-runtime-pin.ts +189 -0
  102. package/src/templates/scaffold-claude-agents.ts +6 -6
  103. package/src/templates/scaffold-claude-commands.ts +1 -1
  104. package/src/templates/scaffold-claude-hook.ts +18 -8
  105. package/src/templates/scaffold-claude.ts +2 -2
  106. package/src/templates/scaffold-container.ts +2 -2
  107. package/src/templates/scaffold-docs.ts +26 -24
  108. package/src/templates/scaffold-guards.ts +73 -39
  109. package/src/templates/scaffold-helm-alert-deploy.ts +105 -0
  110. package/src/templates/scaffold-helm-alert-rules.ts +7 -1
  111. package/src/templates/scaffold-helm-alerts.ts +3 -0
  112. package/src/templates/scaffold-helm-migrate.ts +85 -0
  113. package/src/templates/scaffold-helm-templates.ts +2 -36
  114. package/src/templates/scaffold-helm.ts +1 -0
  115. package/src/templates/scaffold-repo.ts +2 -1
  116. package/src/unthrown-codes.ts +2 -0
  117. package/src/upgrade-bun-floor.ts +4 -0
  118. package/src/upgrade-clean-tree.ts +54 -0
  119. package/src/upgrade-gate-codemods-install.ts +40 -0
  120. package/src/upgrade-gate-codemods.ts +151 -0
  121. package/src/upgrade-gate.ts +38 -6
  122. package/src/upgrade-lock.ts +118 -0
  123. package/src/upgrade-plan.ts +2 -1
  124. package/src/upgrade-report-codemods.ts +54 -0
  125. package/src/upgrade-report.ts +52 -27
  126. package/src/upgrade-signals.ts +91 -0
  127. package/src/upgrade-unfinished.ts +61 -0
  128. package/wiki/CLI-Reference.md +70 -5
  129. package/wiki/Deployment.md +2 -1
  130. package/wiki/Interface-Rules.md +17 -8
  131. package/wiki/Known-Gaps.md +1 -1
  132. package/wiki/Observability.md +1 -0
  133. package/wiki/Project-Layout.md +4 -4
  134. package/wiki/Upgrading.md +6 -0
@@ -0,0 +1,104 @@
1
+ // The unified diff a codemod reports a file it would not overwrite with: what the template change
2
+ // wanted, for the author to apply by hand. LCS over the lines between the common ends, bounded:
3
+ // past `MAX_CELLS` the middle is a plain replace, still a correct diff, just not a minimal one.
4
+
5
+ const CONTEXT = 3;
6
+ const MAX_CELLS = 4_000_000;
7
+
8
+ type Op = { readonly kind: ' ' | '-' | '+'; readonly text: string };
9
+
10
+ const linesOf = (text: string): readonly string[] => {
11
+ if (text === '') return [];
12
+ const lines = text.split('\n');
13
+ return lines.at(-1) === '' ? lines.slice(0, -1) : lines;
14
+ };
15
+
16
+ function middleOps(a: readonly string[], b: readonly string[]): Op[] {
17
+ if (a.length * b.length > MAX_CELLS) {
18
+ return [
19
+ ...a.map((text): Op => ({ kind: '-', text })),
20
+ ...b.map((text): Op => ({ kind: '+', text })),
21
+ ];
22
+ }
23
+ const width = b.length + 1;
24
+ const table = new Uint32Array((a.length + 1) * width);
25
+ for (let i = a.length - 1; i >= 0; i -= 1) {
26
+ for (let j = b.length - 1; j >= 0; j -= 1) {
27
+ table[i * width + j] =
28
+ a[i] === b[j]
29
+ ? (table[(i + 1) * width + j + 1] ?? 0) + 1
30
+ : Math.max(table[(i + 1) * width + j] ?? 0, table[i * width + j + 1] ?? 0);
31
+ }
32
+ }
33
+ const ops: Op[] = [];
34
+ let i = 0;
35
+ let j = 0;
36
+ while (i < a.length || j < b.length) {
37
+ if (i < a.length && j < b.length && a[i] === b[j]) {
38
+ ops.push({ kind: ' ', text: a[i] ?? '' });
39
+ i += 1;
40
+ j += 1;
41
+ } else if (
42
+ i < a.length &&
43
+ (j === b.length || (table[(i + 1) * width + j] ?? 0) >= (table[i * width + j + 1] ?? 0))
44
+ ) {
45
+ // Removal first on a tie: a replaced line reads `-old` then `+new`, as git prints it.
46
+ ops.push({ kind: '-', text: a[i] ?? '' });
47
+ i += 1;
48
+ } else {
49
+ ops.push({ kind: '+', text: b[j] ?? '' });
50
+ j += 1;
51
+ }
52
+ }
53
+ return ops;
54
+ }
55
+
56
+ function editScript(a: readonly string[], b: readonly string[]): readonly Op[] {
57
+ let head = 0;
58
+ while (head < a.length && head < b.length && a[head] === b[head]) head += 1;
59
+ let tail = 0;
60
+ while (
61
+ tail < a.length - head &&
62
+ tail < b.length - head &&
63
+ a[a.length - 1 - tail] === b[b.length - 1 - tail]
64
+ ) {
65
+ tail += 1;
66
+ }
67
+ const same = (text: string): Op => ({ kind: ' ', text });
68
+ return [
69
+ ...a.slice(0, head).map(same),
70
+ ...middleOps(a.slice(head, a.length - tail), b.slice(head, b.length - tail)),
71
+ ...a.slice(a.length - tail).map(same),
72
+ ];
73
+ }
74
+
75
+ /** `path`'s change from `before` (undefined: the file is new) to `after`; '' when they are equal. */
76
+ export function unifiedDiff(path: string, before: string | undefined, after: string): string {
77
+ if (before === after) return '';
78
+ const ops = editScript(linesOf(before ?? ''), linesOf(after));
79
+ const out = [before === undefined ? '--- /dev/null' : `--- a/${path}`, `+++ b/${path}`];
80
+ let index = 0;
81
+ while (index < ops.length) {
82
+ const first = ops.findIndex((op, at) => at >= index && op.kind !== ' ');
83
+ if (first === -1) break;
84
+ // A hunk runs while the gap between two changes is at most twice the context.
85
+ let last = first;
86
+ for (let at = first + 1; at < ops.length && at - last <= 2 * CONTEXT; at += 1) {
87
+ if (ops[at]?.kind !== ' ') last = at;
88
+ }
89
+ const start = Math.max(index, first - CONTEXT);
90
+ const end = Math.min(ops.length, last + CONTEXT + 1);
91
+ const prior = ops.slice(0, start);
92
+ const oldStart = prior.filter((op) => op.kind !== '+').length;
93
+ const newStart = prior.filter((op) => op.kind !== '-').length;
94
+ const hunk = ops.slice(start, end);
95
+ const oldCount = hunk.filter((op) => op.kind !== '+').length;
96
+ const newCount = hunk.filter((op) => op.kind !== '-').length;
97
+ const at = (from: number, count: number): string =>
98
+ `${String(count === 0 ? from : from + 1)},${String(count)}`;
99
+ out.push(`@@ -${at(oldStart, oldCount)} +${at(newStart, newCount)} @@`);
100
+ for (const op of hunk) out.push(`${op.kind}${op.text}`);
101
+ index = end;
102
+ }
103
+ return `${out.join('\n')}\n`;
104
+ }
@@ -0,0 +1,111 @@
1
+ // The two edits a template codemod is made of: swap exact snippets of the old template for the new
2
+ // ones, or add a file the template added. Mechanical or nothing: a snippet the app rewrote leaves
3
+ // the file as it is, reported with the template's own change as a diff to apply by hand.
4
+
5
+ import type { CodemodApp, CodemodResult } from './codemod';
6
+ import { unifiedDiff } from './engine-diff';
7
+
8
+ export interface SnippetEdit {
9
+ /** The old template's exact text. */
10
+ readonly from: string;
11
+ /** What the new template says in its place. */
12
+ readonly to: string;
13
+ /** Prose (a comment) the app may have reworded: swapped when found, never a reason to skip. */
14
+ readonly optional?: boolean;
15
+ }
16
+
17
+ const NOTHING: CodemodResult = { changed: [], skipped: [] };
18
+
19
+ /** A file's text as LF without a BOM, and how to put both back: a Windows checkout is supported. */
20
+ export interface FileText {
21
+ readonly text: string;
22
+ readonly restore: (text: string) => string;
23
+ }
24
+
25
+ export function fileText(source: string): FileText {
26
+ const bom = source.startsWith('\uFEFF') ? '\uFEFF' : '';
27
+ const body = source.slice(bom.length);
28
+ const crlf = body.includes('\r\n');
29
+ return {
30
+ text: crlf ? body.replaceAll('\r\n', '\n') : body,
31
+ restore: (text) => `${bom}${crlf ? text.replaceAll('\n', '\r\n') : text}`,
32
+ };
33
+ }
34
+
35
+ /** `path` read as LF text; undefined when the app has no such file. */
36
+ export async function readText(app: CodemodApp, path: string): Promise<FileText | undefined> {
37
+ const source = await app.read(path);
38
+ return source === undefined ? undefined : fileText(source);
39
+ }
40
+
41
+ /**
42
+ * Carried across. A removal (`to` inside `from`): `from` is gone. An insert (`from` inside `to`):
43
+ * `to` is there. A swap: `to` is there and `from` is not.
44
+ */
45
+ const done = (source: string, edit: SnippetEdit): boolean => {
46
+ if (edit.from.includes(edit.to)) return !source.includes(edit.from);
47
+ if (edit.to.includes(edit.from)) return source.includes(edit.to);
48
+ return source.includes(edit.to) && !source.includes(edit.from);
49
+ };
50
+
51
+ const count = (source: string, part: string): number => source.split(part).length - 1;
52
+
53
+ /**
54
+ * Every pending `from` swapped for its `to`, or nothing: an edit already carried across is done;
55
+ * one whose `from` is gone too means the app wrote its own, and one whose `from` stands in more than
56
+ * one place is a guess — which the template meant is not in the text — so the file is the author's.
57
+ * Matched on LF text without a BOM, written back with the file's own line ending and BOM.
58
+ */
59
+ export async function editSnippets(
60
+ app: CodemodApp,
61
+ path: string,
62
+ edits: readonly SnippetEdit[],
63
+ ): Promise<CodemodResult> {
64
+ const file = await readText(app, path);
65
+ if (file === undefined) return NOTHING;
66
+ const source = file.text;
67
+ const pending = edits.filter((edit) => !done(source, edit));
68
+ if (pending.every((edit) => edit.optional === true && !source.includes(edit.from))) {
69
+ return NOTHING;
70
+ }
71
+ const wanted = (side: 'from' | 'to'): string =>
72
+ `${edits.map((edit) => edit[side]).join('\n\n')}\n`;
73
+ const skip = (reason: string): CodemodResult => ({
74
+ changed: [],
75
+ skipped: [{ path, reason, diff: unifiedDiff(path, wanted('from'), wanted('to')) }],
76
+ });
77
+ const missing = pending.filter((edit) => edit.optional !== true && !source.includes(edit.from));
78
+ if (missing.length > 0) {
79
+ return skip(
80
+ `the app's copy no longer holds the template text this change replaces (${missing.map((edit) => JSON.stringify(edit.from.split('\n')[0] ?? '')).join(', ')}), so the diff below is the template's change, to make by hand`,
81
+ );
82
+ }
83
+ const twice = pending.find((edit) => count(source, edit.from) > 1);
84
+ if (twice !== undefined) {
85
+ return skip(
86
+ `the template text this change replaces stands in ${String(count(source, twice.from))} places (${JSON.stringify(twice.from.split('\n')[0] ?? '')}), and which one it meant is not decidable: the diff below is the change, to make by hand`,
87
+ );
88
+ }
89
+ let next = source;
90
+ for (const edit of pending) next = next.replace(edit.from, () => edit.to);
91
+ if (next === source) return NOTHING;
92
+ await app.write(path, file.restore(next));
93
+ return { changed: [path], skipped: [] };
94
+ }
95
+
96
+ /** A file the template added since: written when the app has none, never over one it has. */
97
+ export async function writeIfAbsent(
98
+ app: CodemodApp,
99
+ path: string,
100
+ source: string,
101
+ ): Promise<CodemodResult> {
102
+ if (await app.exists(path)) return NOTHING;
103
+ await app.write(path, source);
104
+ return { changed: [path], skipped: [] };
105
+ }
106
+
107
+ /** Several results as one, in order. */
108
+ export const mergeResults = (results: readonly CodemodResult[]): CodemodResult => ({
109
+ changed: results.flatMap((result) => result.changed),
110
+ skipped: results.flatMap((result) => result.skipped),
111
+ });
@@ -0,0 +1,95 @@
1
+ // The `CodemodApp` over a real app root: posix paths relative to it in and out, refused when they
2
+ // resolve outside it — lexically or through a symlink. A glob skips `node_modules/` and `.git/`,
3
+ // which no scaffold-owned file is in.
4
+
5
+ // why: Bun has no file-removal, rename, lstat or realpath primitive; `rm` with `force` makes a
6
+ // removal of nothing no error, `rename` lands a write whole, and only `realpath` answers where a
7
+ // symlinked component really points.
8
+ import { lstat, realpath, rename, rm } from 'node:fs/promises';
9
+ // why: Bun exposes no path-resolve primitive; containment is decided on the resolved path.
10
+ import { dirname, resolve, sep } from 'node:path';
11
+ import { ScaffoldPathEscapeError } from '../errors';
12
+ import type { CodemodApp } from './codemod';
13
+
14
+ const SKIPPED = /^(?:node_modules|\.git)\//;
15
+
16
+ const FIX =
17
+ 'x upgrade codemods --from 0.0.0 --dry-run --json # names the codemod that asked for the path; report it with that output';
18
+
19
+ const inside = (base: string, target: string): boolean => target.startsWith(`${base}${sep}`);
20
+
21
+ /** Nothing at this path (or a file where a directory was named): keep walking up. */
22
+ const absent = (error: unknown): boolean => {
23
+ const code = typeof error === 'object' && error !== null ? Reflect.get(error, 'code') : undefined;
24
+ return code === 'ENOENT' || code === 'ENOTDIR';
25
+ };
26
+
27
+ /**
28
+ * The absolute path, once it is inside the root twice over: lexically, and after following every
29
+ * symlink on the way — the deepest component that exists is resolved, and must land under the
30
+ * root's own real path. A dangling link resolves nowhere, so it is refused rather than followed.
31
+ */
32
+ async function contained(root: string, path: string): Promise<string> {
33
+ const base = resolve(root);
34
+ const target = resolve(base, path);
35
+ const refuse = (): never => {
36
+ throw new ScaffoldPathEscapeError({ path, dir: base, fix: FIX });
37
+ };
38
+ if (target === base || !inside(base, target)) refuse();
39
+ const realBase = await realpath(base);
40
+ for (let probe = target; probe !== base; probe = dirname(probe)) {
41
+ const exists = await lstat(probe).then(
42
+ () => true,
43
+ (error: unknown) => (absent(error) ? false : Promise.reject(error)),
44
+ );
45
+ if (!exists) continue;
46
+ const real = await realpath(probe).catch(refuse);
47
+ if (real !== realBase && !inside(realBase, real)) refuse();
48
+ break;
49
+ }
50
+ return target;
51
+ }
52
+
53
+ /**
54
+ * `source` at `target`, whole or not at all: written beside it under a unique name, then renamed
55
+ * over it — a crash leaves the old file or the new one, never half of one, and no stray temp.
56
+ */
57
+ export async function landFile(
58
+ target: string,
59
+ source: string,
60
+ move: (from: string, to: string) => Promise<void> = rename,
61
+ ): Promise<void> {
62
+ const temp = `${target}.x-codemod-${String(process.pid)}-${crypto.randomUUID()}.tmp`;
63
+ await Bun.write(temp, source);
64
+ try {
65
+ await move(temp, target);
66
+ } catch (error) {
67
+ await rm(temp, { force: true });
68
+ throw error;
69
+ }
70
+ }
71
+
72
+ export function fsCodemodApp(root: string): CodemodApp {
73
+ return {
74
+ root,
75
+ async read(path) {
76
+ const file = Bun.file(await contained(root, path));
77
+ return (await file.exists()) ? await file.text() : undefined;
78
+ },
79
+ async write(path, source) {
80
+ await landFile(await contained(root, path), source);
81
+ },
82
+ async remove(path) {
83
+ await rm(await contained(root, path), { force: true });
84
+ },
85
+ exists: async (path) => Bun.file(await contained(root, path)).exists(),
86
+ async glob(pattern) {
87
+ const paths: string[] = [];
88
+ for await (const path of new Bun.Glob(pattern).scan({ cwd: root, dot: true })) {
89
+ const posix = path.replaceAll('\\', '/');
90
+ if (!SKIPPED.test(posix)) paths.push(posix);
91
+ }
92
+ return paths.sort();
93
+ },
94
+ };
95
+ }
@@ -0,0 +1,191 @@
1
+ // The codemod engine: the codemods a hop owes (`since` in (from, to], version then id), each run
2
+ // over a staged view of the app so the next one sees its output, a throw costs only its own
3
+ // writes, and `--dry-run` is the same run minus the final flush. Pure over `CodemodApp`.
4
+
5
+ import { renderThrowable } from '@ultimat3/core';
6
+ import { compareVersions } from '../upgrade-plan';
7
+ import type { Codemod, CodemodApp, CodemodSkip } from './codemod';
8
+
9
+ export interface CodemodOutcome {
10
+ readonly id: string;
11
+ readonly since: string;
12
+ readonly summary: string;
13
+ /** The files this codemod left different from how it found them, written or removed. */
14
+ readonly changed: readonly string[];
15
+ readonly skipped: readonly CodemodSkip[];
16
+ }
17
+
18
+ export interface CodemodsReport {
19
+ readonly from: string;
20
+ readonly to: string;
21
+ readonly dryRun: boolean;
22
+ /** Every codemod that ran, in the order it ran, whether or not it changed anything. */
23
+ readonly applied: readonly CodemodOutcome[];
24
+ }
25
+
26
+ /**
27
+ * Release order on the `major.minor.patch` triple: a prerelease (`32.0.0-next.1`) is its release,
28
+ * which carries every codemod `since` it — `compareVersions` alone reads it as 0.0.0.
29
+ */
30
+ const compareRelease = (a: string, b: string): number =>
31
+ compareVersions(a.split('-')[0] ?? a, b.split('-')[0] ?? b);
32
+
33
+ /** The codemods a hop from `from` to `to` owes, in the order they run. */
34
+ export function pendingCodemods(
35
+ codemods: readonly Codemod[],
36
+ from: string,
37
+ to: string,
38
+ ): readonly Codemod[] {
39
+ return codemods
40
+ .filter(
41
+ (codemod) =>
42
+ compareRelease(codemod.since, from) > 0 && compareRelease(codemod.since, to) <= 0,
43
+ )
44
+ .sort((a, b) => compareRelease(a.since, b.since) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
45
+ }
46
+
47
+ /** A path's staged state: its new text, or null for removed. */
48
+ type Staged = Map<string, string | null>;
49
+
50
+ /** The bytes the run first saw at each path it touched (undefined: no file): what a flush checks. */
51
+ type Seen = Map<string, string | undefined>;
52
+
53
+ /** `base` as `layers` leave it: the newest layer that names a path answers for it. */
54
+ function stagedView(
55
+ base: CodemodApp,
56
+ layers: readonly Staged[],
57
+ top: Staged,
58
+ seen: Seen,
59
+ ): CodemodApp {
60
+ const baseRead = async (path: string): Promise<string | undefined> => {
61
+ if (seen.has(path)) return seen.get(path);
62
+ const text = await base.read(path);
63
+ seen.set(path, text);
64
+ return text;
65
+ };
66
+ const lookup = (path: string): string | null | undefined => {
67
+ for (const layer of [top, ...[...layers].reverse()]) {
68
+ if (layer.has(path)) return layer.get(path);
69
+ }
70
+ return undefined;
71
+ };
72
+ const read = async (path: string): Promise<string | undefined> => {
73
+ const staged = lookup(path);
74
+ if (staged === null) return undefined;
75
+ return staged ?? (await baseRead(path));
76
+ };
77
+ return {
78
+ root: base.root,
79
+ read,
80
+ exists: async (path) => (await read(path)) !== undefined,
81
+ write: async (path, source) => {
82
+ await baseRead(path);
83
+ top.set(path, source);
84
+ },
85
+ remove: async (path) => {
86
+ await baseRead(path);
87
+ top.set(path, null);
88
+ },
89
+ glob: async (pattern) => {
90
+ const glob = new Bun.Glob(pattern);
91
+ const paths = new Set(await base.glob(pattern));
92
+ for (const layer of [...layers, top]) {
93
+ for (const [path, text] of layer) {
94
+ if (!glob.match(path)) continue;
95
+ if (text === null) paths.delete(path);
96
+ else paths.add(path);
97
+ }
98
+ }
99
+ const held: string[] = [];
100
+ for (const path of paths) if ((await read(path)) !== undefined) held.push(path);
101
+ return held.sort();
102
+ },
103
+ };
104
+ }
105
+
106
+ /** The paths a layer really changed: a write of the bytes already there is none. */
107
+ async function changedBy(layer: Staged, before: CodemodApp): Promise<readonly string[]> {
108
+ const changed: string[] = [];
109
+ for (const [path, text] of layer) {
110
+ if ((text ?? undefined) !== (await before.read(path))) changed.push(path);
111
+ }
112
+ return changed.sort();
113
+ }
114
+
115
+ export async function runCodemods(input: {
116
+ readonly app: CodemodApp;
117
+ readonly codemods: readonly Codemod[];
118
+ readonly from: string;
119
+ readonly to: string;
120
+ readonly dryRun: boolean;
121
+ }): Promise<CodemodsReport> {
122
+ const { app, from, to, dryRun } = input;
123
+ const layers: Staged[] = [];
124
+ const seen: Seen = new Map();
125
+ const applied: CodemodOutcome[] = [];
126
+ for (const codemod of pendingCodemods(input.codemods, from, to)) {
127
+ const top: Staged = new Map();
128
+ const before = stagedView(app, layers, new Map(), seen);
129
+ const head = { id: codemod.id, since: codemod.since, summary: codemod.summary };
130
+ try {
131
+ const result = await codemod.run(stagedView(app, layers, top, seen));
132
+ const changed = await changedBy(top, before);
133
+ layers.push(top);
134
+ applied.push({ ...head, changed, skipped: result.skipped });
135
+ } catch (error) {
136
+ // A framework bug, never the app's: its half-done writes go, and the next codemod still runs.
137
+ const reason = `the codemod threw, so it changed nothing: ${renderThrowable(error)}`;
138
+ applied.push({ ...head, changed: [], skipped: [{ path: '.', reason }] });
139
+ }
140
+ }
141
+ if (dryRun) return { from, to, dryRun, applied };
142
+ const final = new Map<string, string | null>();
143
+ for (const layer of layers) for (const [path, text] of layer) final.set(path, text);
144
+ const moved = await movedSince(app, final, seen);
145
+ if (moved.length > 0) return { from, to, dryRun, applied: refused(applied, moved) };
146
+ await flush(app, final);
147
+ return { from, to, dryRun, applied };
148
+ }
149
+
150
+ /** The staged paths whose bytes on disk are no longer the ones the run read. */
151
+ async function movedSince(
152
+ app: CodemodApp,
153
+ final: ReadonlyMap<string, string | null>,
154
+ seen: Seen,
155
+ ): Promise<readonly string[]> {
156
+ const moved: string[] = [];
157
+ for (const path of final.keys()) {
158
+ if (seen.has(path) && (await app.read(path)) !== seen.get(path)) moved.push(path);
159
+ }
160
+ return moved;
161
+ }
162
+
163
+ /** Nothing lands: each moved file is said, on the codemod that would have written it. */
164
+ function refused(
165
+ applied: readonly CodemodOutcome[],
166
+ moved: readonly string[],
167
+ ): readonly CodemodOutcome[] {
168
+ const reason =
169
+ 'changed on disk while the codemods ran, so no file was written: rerun x upgrade codemods on the tree as it is now';
170
+ return applied.map((one) => ({
171
+ ...one,
172
+ changed: [],
173
+ skipped: [
174
+ ...one.skipped,
175
+ ...one.changed.filter((path) => moved.includes(path)).map((path) => ({ path, reason })),
176
+ ],
177
+ }));
178
+ }
179
+
180
+ /**
181
+ * Writes first, removals after: interrupted between them, the tree holds both the old evidence and
182
+ * the new file — never neither, which a rerun would read as a different app.
183
+ */
184
+ async function flush(app: CodemodApp, final: ReadonlyMap<string, string | null>): Promise<void> {
185
+ for (const [path, text] of final) {
186
+ if (text !== null && text !== (await app.read(path))) await app.write(path, text);
187
+ }
188
+ for (const [path, text] of final) {
189
+ if (text === null && (await app.read(path)) !== undefined) await app.remove(path);
190
+ }
191
+ }
@@ -0,0 +1,28 @@
1
+ // The format hook as `x new` wrote it from 31.22.0 to 31.27.0, byte for byte: the text the
2
+ // format-edited-hook codemod recognises as the stock script. It ran `bunx biome`, which on a checkout
3
+ // with no install fetches an unrelated npm package named `biome`; today's script never does.
4
+
5
+ export const HOOK_SCRIPT_3122 = `#!/usr/bin/env bun
6
+ // PostToolUse(Edit|Write): \`biome check --write\` on the one file just edited — it formats in place
7
+ // and reports what it cannot fix. The path arrives on stdin as \`tool_input.file_path\`. Exit 2
8
+ // shows the agent the finding (the edit already landed); a file biome does not handle is a no-op.
9
+
10
+ const input: unknown = JSON.parse((await Bun.stdin.text()) || '{}');
11
+ const record = (typeof input === 'object' && input !== null ? input : {}) as {
12
+ tool_input?: { file_path?: unknown };
13
+ };
14
+ const file = record.tool_input?.file_path;
15
+ if (typeof file === 'string' && file !== '') {
16
+ const proc = Bun.spawnSync(
17
+ ['bunx', 'biome', 'check', '--write', '--no-errors-on-unmatched', file],
18
+ { stdout: 'pipe', stderr: 'pipe', timeout: 15_000 },
19
+ );
20
+ if (proc.exitCode !== 0) {
21
+ const out = \`\${proc.stdout.toString()}\${proc.stderr.toString()}\`.trim();
22
+ process.stderr.write(
23
+ \`\${out.split('\\n').slice(-30).join('\\n')}\\nfix what it names, then: bunx biome check --write \${file}\\n\`,
24
+ );
25
+ process.exit(2);
26
+ }
27
+ }
28
+ `;
@@ -0,0 +1,152 @@
1
+ // The PostToolUse format hook, carried twice. 31.22.0: it read `$CLAUDE_FILE_PATHS`, which the
2
+ // harness never sets; now `.claude/hooks/format-edited.ts` reads the path from stdin. 31.28.0: that
3
+ // script ran `bunx biome`, which with no install fetches an unrelated npm package; now it runs the
4
+ // app's own `node_modules/.bin/biome` or nothing, and the docs name `@biomejs/biome`.
5
+
6
+ import { claudeHookFile, HOOK_PATH } from '../templates/scaffold-claude-hook';
7
+ import type { Codemod } from './codemod';
8
+ import type { SnippetEdit } from './engine-edits';
9
+ import { editSnippets, mergeResults, writeIfAbsent } from './engine-edits';
10
+ import { HOOK_SCRIPT_3122 } from './format-edited-hook-3122';
11
+
12
+ const SETTINGS = '.claude/settings.json';
13
+ const README = '.claude/README.md';
14
+
15
+ const lines = (...text: readonly string[]): string => text.join('\n');
16
+
17
+ /** The hook as `settings.json` held it before: the dead command, matched as the template wrote it. */
18
+ const HOOK: SnippetEdit = {
19
+ from: lines(
20
+ ' "matcher": "Edit|Write",',
21
+ ' "hooks": [',
22
+ ' {',
23
+ ' "type": "command",',
24
+ ' "command": "bunx biome check --no-errors-on-unmatched --write \\"$CLAUDE_FILE_PATHS\\" 2>/dev/null || true"',
25
+ ' }',
26
+ ),
27
+ to: lines(
28
+ ' "matcher": "Edit|Write|MultiEdit",',
29
+ ' "hooks": [',
30
+ ' {',
31
+ ' "type": "command",',
32
+ ` "command": "bun \\"$CLAUDE_PROJECT_DIR\\"/${HOOK_PATH}",`,
33
+ ' "timeout": 20',
34
+ ' }',
35
+ ),
36
+ };
37
+
38
+ /** The read-only commands added to the allowlist alongside: the app's own list wins if edited. */
39
+ const ALLOWED: SnippetEdit = {
40
+ from: lines(' "Bash(bunx x docs:*)",', ' "Bash(bunx x env check:*)",'),
41
+ to: lines(
42
+ ' "Bash(bunx x docs:*)",',
43
+ ...[
44
+ 'impact',
45
+ 'graph',
46
+ 'affected',
47
+ 'exercise',
48
+ 'i18n sync',
49
+ 'fix boundary',
50
+ 'mcp tools',
51
+ 'env check',
52
+ ].map((command) => ` "Bash(bunx x ${command}:*)",`),
53
+ ),
54
+ optional: true,
55
+ };
56
+
57
+ const README_EDITS: readonly SnippetEdit[] = [
58
+ {
59
+ from: lines(
60
+ '| `settings.json` | nothing in context | read once per session; the hook runs per edit |',
61
+ '| `commands/*.md` |',
62
+ ),
63
+ to: lines(
64
+ '| `settings.json` | nothing in context | read once per session; the hook runs per edit |',
65
+ `| \`${HOOK_PATH.slice('.claude/'.length)}\` | nothing in context | runs after each edit, on that one file |`,
66
+ '| `commands/*.md` |',
67
+ ),
68
+ optional: true,
69
+ },
70
+ {
71
+ from: lines(
72
+ 'One `PostToolUse` hook: `bunx biome check --write` on the file that was just edited. **`--write`',
73
+ 'means it rewrites that file in place** — the same safe fixes `biome check --write .` would make',
74
+ 'repo-wide, but your working tree does change after every agent edit. Scoped to one file, so it costs',
75
+ 'milliseconds, and it settles formatting arguments before they reach a diff.',
76
+ ),
77
+ to: lines(
78
+ `One \`PostToolUse\` hook, \`${HOOK_PATH}\`: \`bunx biome check --write\` on the file that was just`,
79
+ 'edited, named by the JSON the harness sends on stdin. **`--write` means it rewrites that file in',
80
+ 'place** — the same safe fixes `biome check --write .` would make repo-wide, but your working tree',
81
+ 'does change after every agent edit. Scoped to one file, so it costs milliseconds, and it settles',
82
+ 'formatting arguments before they reach a diff. What biome cannot fix is shown to the agent at once,',
83
+ 'with the command that re-checks the file, instead of surfacing later as a red `lint` step.',
84
+ ),
85
+ optional: true,
86
+ },
87
+ ];
88
+
89
+ /** The stock script `x new` wrote from 31.22.0, whole: an app that edited it keeps its own. */
90
+ const script = claudeHookFile().contents;
91
+ const HOOK_SCRIPT: SnippetEdit = {
92
+ from: HOOK_SCRIPT_3122,
93
+ to: typeof script === 'string' ? script : HOOK_SCRIPT_3122,
94
+ };
95
+
96
+ /** `bunx biome` names whatever npm calls `biome`; `@biomejs/biome` is the formatter. */
97
+ const BIOME_ALLOW: SnippetEdit = {
98
+ from: ' "Bash(bunx biome check:*)",',
99
+ to: ' "Bash(bunx @biomejs/biome check:*)",',
100
+ optional: true,
101
+ };
102
+ const README_BIOME: SnippetEdit = {
103
+ from: `One \`PostToolUse\` hook, \`${HOOK_PATH}\`: \`bunx biome check --write\` on the file that was just`,
104
+ to: `One \`PostToolUse\` hook, \`${HOOK_PATH}\`: the installed \`biome check --write\` on the file that was just`,
105
+ optional: true,
106
+ };
107
+ const LINT_LINE: SnippetEdit = {
108
+ from: '`bunx biome check --write <paths>`',
109
+ to: '`bunx @biomejs/biome check --write <paths>`',
110
+ optional: true,
111
+ };
112
+ const DOCS = [
113
+ '.claude/agents/data.md',
114
+ '.claude/agents/server.md',
115
+ '.claude/agents/web.md',
116
+ '.claude/commands/feature.md',
117
+ ] as const;
118
+
119
+ /** The 31.28.0 edits alone, per file, in run order: what a 31.22-to-31.27 app is carried by. */
120
+ export const BIOME_EDITS: Readonly<Record<string, readonly SnippetEdit[]>> = {
121
+ [SETTINGS]: [BIOME_ALLOW],
122
+ [HOOK_PATH]: [HOOK_SCRIPT],
123
+ [README]: [README_BIOME],
124
+ ...Object.fromEntries(DOCS.map((path) => [path, [LINT_LINE]])),
125
+ };
126
+
127
+ /** Each file's edits: what the codemod runs, and what its test runs backwards. */
128
+ export const FORMAT_HOOK_EDITS = {
129
+ [SETTINGS]: [ALLOWED, HOOK, BIOME_ALLOW],
130
+ [README]: [...README_EDITS, README_BIOME],
131
+ } as const;
132
+
133
+ export const codemod: Codemod = {
134
+ id: 'format-edited-hook',
135
+ since: '31.28.0',
136
+ summary: `.claude/settings.json runs ${HOOK_PATH}, which reads the edited file from stdin and runs the app's own biome, never bunx biome`,
137
+ async run(app) {
138
+ const settings = await editSnippets(app, SETTINGS, FORMAT_HOOK_EDITS[SETTINGS]);
139
+ // The script only where settings.json runs it: an app that dropped the hook keeps none.
140
+ const runsIt = ((await app.read(SETTINGS)) ?? '').includes(HOOK_PATH);
141
+ const results = [
142
+ settings,
143
+ runsIt && typeof script === 'string'
144
+ ? await writeIfAbsent(app, HOOK_PATH, script)
145
+ : { changed: [], skipped: [] },
146
+ await editSnippets(app, HOOK_PATH, [HOOK_SCRIPT]),
147
+ await editSnippets(app, README, FORMAT_HOOK_EDITS[README]),
148
+ ];
149
+ for (const path of DOCS) results.push(await editSnippets(app, path, [LINT_LINE]));
150
+ return mergeResults(results);
151
+ },
152
+ };