@ultimat3/cli 31.27.0 → 31.28.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 (107) hide show
  1. package/CLAUDE.md +3 -1
  2. package/README.md +14 -4
  3. package/package.json +29 -29
  4. package/src/app-manifest.ts +6 -1
  5. package/src/cmd-doctor.ts +11 -3
  6. package/src/cmd-repro-spec.ts +13 -1
  7. package/src/cmd-repro.ts +37 -5
  8. package/src/cmd-upgrade-codemods.ts +71 -0
  9. package/src/cmd-upgrade-spec.ts +19 -5
  10. package/src/cmd-upgrade.ts +91 -34
  11. package/src/codemods/agents-dev-mcp.ts +50 -0
  12. package/src/codemods/authenticator-session-refusal.ts +214 -0
  13. package/src/codemods/biome-no-default-export.ts +58 -0
  14. package/src/codemods/bunfig-island-coverage.ts +33 -0
  15. package/src/codemods/chart-dashboard.ts +73 -0
  16. package/src/codemods/ci-e2e-browser-stock.ts +75 -0
  17. package/src/codemods/ci-e2e-browser.ts +63 -0
  18. package/src/codemods/codemod.ts +58 -0
  19. package/src/codemods/define-error-leaf.ts +73 -0
  20. package/src/codemods/docs-ci-parts.ts +65 -0
  21. package/src/codemods/docs-gate-prose.ts +53 -0
  22. package/src/codemods/docs-island-rows.ts +31 -0
  23. package/src/codemods/docs-shipped-guards.ts +100 -0
  24. package/src/codemods/docs-test-services.ts +62 -0
  25. package/src/codemods/engine-diff.ts +104 -0
  26. package/src/codemods/engine-edits.ts +111 -0
  27. package/src/codemods/engine-fs.ts +95 -0
  28. package/src/codemods/engine.ts +191 -0
  29. package/src/codemods/format-edited-hook-3122.ts +28 -0
  30. package/src/codemods/format-edited-hook.ts +152 -0
  31. package/src/codemods/helm-alerts-objective.ts +105 -0
  32. package/src/codemods/helm-alerts-stock.ts +108 -0
  33. package/src/codemods/index.ts +56 -0
  34. package/src/codemods/metrics-probe-healthz.ts +47 -0
  35. package/src/codemods/pending.ts +36 -0
  36. package/src/codemods/repro-gitignore.ts +40 -0
  37. package/src/codemods/runtime-pin-lines.ts +109 -0
  38. package/src/codemods/runtime-pin.ts +116 -0
  39. package/src/codemods/solid-floor.ts +63 -0
  40. package/src/codemods/test-ports.ts +86 -0
  41. package/src/codemods/test-suites.ts +37 -0
  42. package/src/codemods/theme-toggle-mount-over.ts +70 -0
  43. package/src/codemods/vendored-guards.ts +186 -0
  44. package/src/codemods/verify-floor-skips.ts +88 -0
  45. package/src/codemods/verify-floor-steps.ts +90 -0
  46. package/src/doctor-advisory-floors.ts +113 -0
  47. package/src/doctor-guards.ts +39 -86
  48. package/src/doctor-superseded.ts +67 -0
  49. package/src/error-codes-doctor.ts +12 -4
  50. package/src/error-codes.ts +6 -0
  51. package/src/exercise-database.ts +7 -2
  52. package/src/generate-files.ts +6 -5
  53. package/src/guards-built-in-codes.ts +36 -0
  54. package/src/guards-built-in-refusal.ts +25 -0
  55. package/src/guards-built-in.ts +134 -0
  56. package/src/guards-materialize.ts +42 -0
  57. package/src/guards-paths.ts +37 -0
  58. package/src/guards-shipped-names.ts +38 -0
  59. package/src/guards-vendored.ts +73 -0
  60. package/src/guards.ts +90 -34
  61. package/src/index.ts +10 -0
  62. package/src/lint-findings.ts +3 -3
  63. package/src/mcp-errors.ts +11 -1
  64. package/src/measure-scope.ts +23 -3
  65. package/src/messages-repro.ts +16 -2
  66. package/src/messages-upgrade.ts +15 -0
  67. package/src/messages.ts +1 -1
  68. package/src/repro-archive-collect.ts +161 -0
  69. package/src/repro-archive-write.ts +96 -0
  70. package/src/repro-archive.ts +161 -0
  71. package/src/repro-bundle.ts +8 -16
  72. package/src/repro-errors.ts +14 -2
  73. package/src/repro-framework.ts +53 -0
  74. package/src/repro-parse.ts +87 -0
  75. package/src/repro-redact.ts +218 -0
  76. package/src/repro-scrub.ts +257 -0
  77. package/src/superseded-match.ts +87 -0
  78. package/src/superseded.ts +84 -0
  79. package/src/templates/bun-image.ts +48 -0
  80. package/src/templates/github/ci.yml.ts +1 -1
  81. package/src/templates/guard-released-forms.ts +112 -0
  82. package/src/templates/guard-runtime-pin-test.ts +54 -0
  83. package/src/templates/guard-runtime-pin.ts +189 -0
  84. package/src/templates/scaffold-claude-agents.ts +6 -6
  85. package/src/templates/scaffold-claude-commands.ts +1 -1
  86. package/src/templates/scaffold-claude-hook.ts +18 -8
  87. package/src/templates/scaffold-claude.ts +2 -2
  88. package/src/templates/scaffold-docs.ts +26 -24
  89. package/src/templates/scaffold-guards.ts +73 -39
  90. package/src/templates/scaffold-repo.ts +2 -1
  91. package/src/unthrown-codes.ts +2 -0
  92. package/src/upgrade-bun-floor.ts +4 -0
  93. package/src/upgrade-clean-tree.ts +54 -0
  94. package/src/upgrade-gate-codemods-install.ts +40 -0
  95. package/src/upgrade-gate-codemods.ts +151 -0
  96. package/src/upgrade-gate.ts +38 -6
  97. package/src/upgrade-lock.ts +118 -0
  98. package/src/upgrade-plan.ts +2 -1
  99. package/src/upgrade-report-codemods.ts +54 -0
  100. package/src/upgrade-report.ts +52 -27
  101. package/src/upgrade-signals.ts +91 -0
  102. package/src/upgrade-unfinished.ts +61 -0
  103. package/wiki/CLI-Reference.md +58 -4
  104. package/wiki/Interface-Rules.md +17 -8
  105. package/wiki/Observability.md +1 -0
  106. package/wiki/Project-Layout.md +4 -4
  107. package/wiki/Upgrading.md +5 -0
@@ -7,6 +7,7 @@
7
7
  import { join } from 'node:path';
8
8
  import { UltimateError } from '@ultimat3/core';
9
9
  import { versionAtLeast } from './app-root';
10
+ import { runUpgradeCodemods } from './cmd-upgrade-codemods';
10
11
  import { upgradeSpec } from './cmd-upgrade-spec';
11
12
  import type { CliCommand, CommandContext } from './command';
12
13
  import { failed, ok } from './command';
@@ -21,13 +22,21 @@ import { typescriptLags } from './typescript-floor';
21
22
  import { applyAgentsLink, planAgentsLink } from './upgrade-agents-link';
22
23
  import type { BunEdit, BunManual } from './upgrade-bun-floor';
23
24
  import { editBunSites, floorOf, isBunSite } from './upgrade-bun-floor';
25
+ import { requireCleanTree } from './upgrade-clean-tree';
24
26
  import { repoScripts, runHopGate, runRepoScripts } from './upgrade-gate';
27
+ import { atTargetCodemods, EVERY_RELEASE, previewCodemods } from './upgrade-gate-codemods';
28
+ import { acquireUpgradeLock } from './upgrade-lock';
25
29
  import { readManifests, readPins, rewritePins } from './upgrade-pins';
30
+ import type { UpgradeHop } from './upgrade-plan';
26
31
  import { planHop, releaseOf } from './upgrade-plan';
27
32
  import { publishedVersions, releaseBunRange } from './upgrade-registry';
28
33
  import type { PlannedWrites } from './upgrade-report';
29
34
  import { humanLines, NO_WRITES, report, thenLine } from './upgrade-report';
35
+ import { codemodLines } from './upgrade-report-codemods';
30
36
  import { findUpgradeRoot } from './upgrade-root';
37
+ import { stopChildrenOnSignal, tagRunner, upgradeTag } from './upgrade-signals';
38
+ import type { UnfinishedHop } from './upgrade-unfinished';
39
+ import { clearUnfinished, readUnfinished, writeUnfinished } from './upgrade-unfinished';
31
40
  import { elapsedLabel, HEARTBEAT_MS } from './verify-progress';
32
41
  import { writeErrorLine } from './write-line';
33
42
 
@@ -42,28 +51,6 @@ const readTarget = (ctx: CommandContext): string | undefined => {
42
51
  });
43
52
  };
44
53
 
45
- /** The repository's root, or the refusal: git is the only record of where the walk stands. */
46
- async function requireCleanTree(runner: Runner, root: string): Promise<string> {
47
- const top = await runner(['git', 'rev-parse', '--show-toplevel'], { cwd: root });
48
- if (!top.ok) {
49
- throw new UltimateError({
50
- code: 'X_UPGRADE_DIRTY_TREE',
51
- cause: `${root} is not a git repository, and a hop has to be one commit you can review or undo`,
52
- fix: 'git init && git add -A && git commit -m "before x upgrade" # then: x upgrade --json',
53
- });
54
- }
55
- const status = await runner(['git', 'status', '--porcelain'], { cwd: root });
56
- const changes = status.stdout.split('\n').filter((line) => line.trim().length > 0);
57
- if (!status.ok || changes.length > 0) {
58
- throw new UltimateError({
59
- code: 'X_UPGRADE_DIRTY_TREE',
60
- cause: `${String(changes.length)} uncommitted change(s), and a hop has to be one reviewable commit: ${changes.slice(0, 5).join('; ')}`,
61
- fix: 'git status --short # then commit or stash, and re-run: x upgrade --json',
62
- });
63
- }
64
- return top.stdout.trim();
65
- }
66
-
67
54
  /** Everything the hop would write, decided before any of it is. `--dry-run` stops here. */
68
55
  async function planWrites(input: {
69
56
  readonly runner: Runner;
@@ -146,6 +133,16 @@ async function withHeartbeat<T>(
146
133
  }
147
134
  }
148
135
 
136
+ /** The recorded hop this run finishes: its pins are at target and it is the hop that wrote them. */
137
+ const resumable = (
138
+ unfinished: UnfinishedHop | undefined,
139
+ planned: UpgradeHop,
140
+ dryRun: boolean,
141
+ ): UnfinishedHop | undefined =>
142
+ unfinished !== undefined && planned.atTarget && !dryRun && unfinished.to === planned.to
143
+ ? unfinished
144
+ : undefined;
145
+
149
146
  /** `YYYY-MM-DD` in UTC: the day a rebaselined floor's `why` names. */
150
147
  const utcDay = (at: Date): string => at.toISOString().slice(0, 10);
151
148
 
@@ -153,22 +150,36 @@ export const createUpgradeCommand = (
153
150
  write: (line: string) => void,
154
151
  /** The clock a rebaselined coverage floor is dated by; a test pins it. */
155
152
  now: () => Date = () => new Date(),
156
- ): CliCommand => ({
157
- spec: upgradeSpec,
158
- async run(ctx: CommandContext): Promise<CommandResult> {
159
- const { dir: root, app } = await findUpgradeRoot(ctx.cwd);
160
- const to = readTarget(ctx);
153
+ ): CliCommand => {
154
+ /** One hop, under the lock and the signal handlers `run` holds around it. */
155
+ async function runHop(
156
+ ctx: CommandContext,
157
+ root: string,
158
+ app: boolean,
159
+ to: string | undefined,
160
+ ): Promise<CommandResult> {
161
161
  const dryRun = flagBool(ctx.args, 'dry-run');
162
- const top = await requireCleanTree(ctx.runner, root);
162
+ const unfinished = await readUnfinished(root);
163
+ const top = await requireCleanTree(ctx.runner, root, unfinished);
163
164
  const manifests = await readManifests(root);
164
165
  const pins = readPins(manifests);
165
166
  // Reported, never written: a compiler is the app's to move, and the line names the command.
166
167
  const typescript = typescriptLags(manifests);
167
168
  const versions = await publishedVersions(ctx.runner, root);
168
- const hop = planHop({ pins, versions, ...(to === undefined ? {} : { to }) });
169
+ const planned = planHop({ pins, versions, ...(to === undefined ? {} : { to }) });
170
+ // Pins at target with a hop recorded as unfinished: that hop wrote them and never reached its
171
+ // gate. It is finished now — install, then the whole gate, every codemod (each skips a file it
172
+ // already carried) — rather than answered done.
173
+ const resume = resumable(unfinished, planned, dryRun);
174
+ const hop = resume === undefined ? planned : { ...planned, from: resume.from, atTarget: false };
169
175
 
170
176
  if (hop.atTarget) {
177
+ // A record for some other target is a hop since undone (`git stash`): nothing left to finish.
178
+ if (unfinished !== undefined && !dryRun) await clearUnfinished(root);
171
179
  const then = thenLine({ hop, dryRun, app, gate: undefined, scripts: [] });
180
+ const carried = app
181
+ ? await atTargetCodemods({ runner: ctx.runner, root, to: hop.to, dryRun })
182
+ : undefined;
172
183
  const summary =
173
184
  hop.next === null
174
185
  ? msg('cli.upgrade.atLatest', { version: hop.to })
@@ -187,15 +198,20 @@ export const createUpgradeCommand = (
187
198
  scripts: [],
188
199
  then,
189
200
  typescript,
201
+ ...carried,
190
202
  }),
191
203
  lines: [
192
204
  ...typescript.map((lag) => msg('cli.upgrade.typescript', { ...lag })),
205
+ ...codemodLines(carried?.codemods ?? null),
193
206
  msg('cli.upgrade.then', { then }),
194
207
  ],
195
208
  });
196
209
  }
197
210
 
198
- const bunRange = await releaseBunRange(ctx.runner, root, hop.to);
211
+ const bunRange =
212
+ resume === undefined
213
+ ? await releaseBunRange(ctx.runner, root, hop.to)
214
+ : (resume.bunTo ?? undefined);
199
215
  const floor = floorOf(bunRange);
200
216
  // Before any write: the CLI this hop installs refuses this Bun on its first line, so the pins
201
217
  // would land and every later step would report the same `X_BUN_VERSION` as a hop gone red.
@@ -211,7 +227,10 @@ export const createUpgradeCommand = (
211
227
  manifests,
212
228
  });
213
229
  const held = manifests.find((manifest) => manifest.file === 'package.json')?.text ?? '';
214
- const bunFrom = /"engines"\s*:\s*\{[^}]*?"bun"\s*:\s*"([^"]*)"/.exec(held)?.[1] ?? null;
230
+ const bunFrom =
231
+ resume === undefined
232
+ ? (/"engines"\s*:\s*\{[^}]*?"bun"\s*:\s*"([^"]*)"/.exec(held)?.[1] ?? null)
233
+ : resume.bunFrom;
215
234
  const agentsMd = await planAgentsLink(root);
216
235
  const shared = {
217
236
  hop,
@@ -228,6 +247,8 @@ export const createUpgradeCommand = (
228
247
  if (dryRun) {
229
248
  const named = scriptNames.map((name) => ({ name, ok: null }));
230
249
  const then = thenLine({ hop, dryRun: true, app, gate: undefined, scripts: named });
250
+ // This CLI's list, written nowhere: the hop itself applies the installed release's.
251
+ const preview = app ? await previewCodemods(root, hop.from, hop.to) : undefined;
231
252
  return ok('upgrade', msg('cli.upgrade.dryRun', { from: hop.from, to: hop.to }), {
232
253
  data: report({
233
254
  ...shared,
@@ -236,6 +257,7 @@ export const createUpgradeCommand = (
236
257
  gate: undefined,
237
258
  scripts: named,
238
259
  then,
260
+ ...preview,
239
261
  }),
240
262
  lines: humanLines({
241
263
  hop,
@@ -245,10 +267,19 @@ export const createUpgradeCommand = (
245
267
  then,
246
268
  agentsMd,
247
269
  typescript,
270
+ ...preview,
248
271
  }),
249
272
  });
250
273
  }
251
274
 
275
+ // From the first pin written until the gate returns: a stopped hop is told apart from a done one.
276
+ await writeUnfinished(root, {
277
+ from: hop.from,
278
+ to: hop.to,
279
+ bunFrom,
280
+ bunTo: bunRange ?? null,
281
+ startedAt: resume?.startedAt ?? now().toISOString(),
282
+ });
252
283
  await Promise.all(
253
284
  [...writes.files].map(async ([path, text]) => {
254
285
  await Bun.write(path, text);
@@ -277,15 +308,19 @@ export const createUpgradeCommand = (
277
308
  runner: ctx.runner,
278
309
  root,
279
310
  onStage: stageReached,
311
+ codemods: { from: resume === undefined ? hop.from : EVERY_RELEASE, to: hop.to },
280
312
  ...(bunMoved === undefined ? {} : { bunMoved }),
281
313
  });
282
314
  return { gate: hopGate, scripts: [] };
283
315
  });
316
+ await clearUnfinished(root);
284
317
 
285
318
  const redScripts = scripts.filter((script) => script.ok !== true).map((script) => script.name);
286
319
  // With no script, nothing was checked, and that is never a green.
287
320
  const done =
288
- gate !== undefined ? gate.verify.ok : scripts.length > 0 && redScripts.length === 0;
321
+ gate !== undefined
322
+ ? gate.verify.ok && gate.codemods?.failure === undefined
323
+ : scripts.length > 0 && redScripts.length === 0;
289
324
  const then = thenLine({ hop, dryRun: false, app, gate, scripts });
290
325
  const extra = {
291
326
  data: report({ ...shared, done, dryRun: false, gate, scripts, then }),
@@ -309,7 +344,29 @@ export const createUpgradeCommand = (
309
344
  msg('cli.upgrade.noApp.red', { ...span, names: redScripts.join(', ') }),
310
345
  extra,
311
346
  );
312
- },
313
- });
347
+ }
348
+
349
+ return {
350
+ spec: upgradeSpec,
351
+ async run(ctx: CommandContext): Promise<CommandResult> {
352
+ if (ctx.args.subcommand === 'codemods') return runUpgradeCodemods(ctx);
353
+ const { dir: root, app } = await findUpgradeRoot(ctx.cwd);
354
+ const to = readTarget(ctx);
355
+ // One hop per app at a time, and a stopped hop stops its children: every spawn below is
356
+ // tagged, and SIGINT/SIGTERM kill that tree and release the lock before the signal lands.
357
+ const release = acquireUpgradeLock(root);
358
+ const tag = upgradeTag();
359
+ const pids = new Set<number>();
360
+ const undoSignals = stopChildrenOnSignal({ tag, pids, cleanup: release });
361
+ try {
362
+ const runner = tagRunner(ctx.runner, tag, ctx.env, pids);
363
+ return await runHop({ ...ctx, runner }, root, app, to);
364
+ } finally {
365
+ undoSignals();
366
+ release();
367
+ }
368
+ },
369
+ };
370
+ };
314
371
 
315
372
  export const upgradeCommand: CliCommand = createUpgradeCommand(writeErrorLine);
@@ -0,0 +1,50 @@
1
+ // 31.22.0: the four `.claude/agents/*.md` the scaffold writes may call the app's dev MCP server
2
+ // (`mcp__<app>__*`, the server `.mcp.json` names). Each `tools:` line still as `x new` wrote it
3
+ // gains it; one the app changed is the app's choice, and is left as it is.
4
+
5
+ import { stringField } from '@ultimat3/core';
6
+ import type { Codemod } from './codemod';
7
+ import type { SnippetEdit } from './engine-edits';
8
+ import { editSnippets, mergeResults, readText } from './engine-edits';
9
+
10
+ /** Each agent and the `tools:` line `x new` gave it. */
11
+ export const AGENT_TOOLS: Readonly<Record<string, string>> = {
12
+ '.claude/agents/shape.md': 'tools: Read, Glob, Grep, Bash',
13
+ '.claude/agents/data.md': 'tools: Read, Write, Edit, Glob, Grep, Bash',
14
+ '.claude/agents/server.md': 'tools: Read, Write, Edit, Glob, Grep, Bash',
15
+ '.claude/agents/web.md': 'tools: Read, Write, Edit, Glob, Grep, Bash',
16
+ };
17
+
18
+ /** The app's name as its root package.json declares it; undefined when it declares none usable. */
19
+ export const appName = (manifest: string): string | undefined => {
20
+ let parsed: unknown;
21
+ try {
22
+ parsed = JSON.parse(manifest);
23
+ } catch {
24
+ return undefined;
25
+ }
26
+ const name = stringField(parsed, 'name');
27
+ return name !== undefined && /^[a-z0-9][a-z0-9-]*$/.test(name) ? name : undefined;
28
+ };
29
+
30
+ export const codemod: Codemod = {
31
+ id: 'agents-dev-mcp',
32
+ since: '31.22.0',
33
+ summary:
34
+ ".claude/agents/*.md may call the app's dev MCP server: mcp__<app>__* on each tools: line",
35
+ async run(app) {
36
+ const name = appName((await readText(app, 'package.json'))?.text ?? '');
37
+ if (name === undefined) return { changed: [], skipped: [] };
38
+ const results = [];
39
+ for (const [path, tools] of Object.entries(AGENT_TOOLS)) {
40
+ // The front matter's own line, newline-bounded, so a longer `tools:` line never matches.
41
+ const edit: SnippetEdit = {
42
+ from: `\n${tools}\n`,
43
+ to: `\n${tools}, mcp__${name}__*\n`,
44
+ optional: true,
45
+ };
46
+ results.push(await editSnippets(app, path, [edit]));
47
+ }
48
+ return mergeResults(results);
49
+ },
50
+ };
@@ -0,0 +1,214 @@
1
+ // 31.20.0: the app's session authenticator answers a stale, revoked or forged cookie `null` instead
2
+ // of throwing, so a signed-out socket is closed and sign-in opens for a stale cookie. Both shapes
3
+ // of `apps/web/app/auth/authenticator.ts` (`x new`'s, `x g sign-in`'s) and their tests.
4
+
5
+ import type { Codemod, CodemodApp } from './codemod';
6
+ import type { SnippetEdit } from './engine-edits';
7
+ import { editSnippets, mergeResults, readText } from './engine-edits';
8
+
9
+ const SOURCE = 'apps/web/app/auth/authenticator.ts';
10
+ const TEST = 'apps/web/app/auth/authenticator.test.ts';
11
+
12
+ const lines = (...text: readonly string[]): string => text.join('\n');
13
+
14
+ const CATCH = lines(
15
+ ' try {',
16
+ ' return await authenticate(TARGET, token);',
17
+ ' } catch (error) {',
18
+ ' if (isSessionRefusal(error)) return null;',
19
+ ' throw error;',
20
+ ' }',
21
+ ' };',
22
+ );
23
+
24
+ const SIGNED_OUT_TEST = (name: string, check: string): string =>
25
+ lines(
26
+ "unitTest('a signed-out cookie is nobody, so its socket is closed on re-check', async () => {",
27
+ ' const auth = memoryAuth();',
28
+ ' await register(auth(), {',
29
+ " email: 'ada@example.com',",
30
+ ' password: PASSWORD,',
31
+ ' orgId: DEMO_ORG_ID,',
32
+ " roles: ['member'],",
33
+ ' });',
34
+ " const { token } = await login(auth(), { email: 'ada@example.com', password: PASSWORD });",
35
+ ' await logout(auth(), token);',
36
+ ` const ${name} = requestWith({ [auth().sessions.policy.cookieName]: token });`,
37
+ check,
38
+ '});',
39
+ );
40
+
41
+ const AUTH_IMPORT: SnippetEdit = {
42
+ from: "import { defineAuth, login, memoryAuthAdapter, register } from '@ultimat3/auth';",
43
+ to: "import { defineAuth, login, logout, memoryAuthAdapter, register } from '@ultimat3/auth';",
44
+ };
45
+
46
+ const NULL_NOT_THROW =
47
+ ' // `null`, not a throw: thrown, a stale cookie was a 401 on the sign-in page itself.';
48
+
49
+ /** `x new`'s authenticator: development falls back to the dev viewer, a cookie never does. */
50
+ const SCAFFOLD: readonly SnippetEdit[] = [
51
+ {
52
+ from: "import { type Actor, logger, tryResolveEnvironment } from '@ultimat3/core';",
53
+ to: "import { type Actor, isSessionRefusal, logger, tryResolveEnvironment } from '@ultimat3/core';",
54
+ },
55
+ {
56
+ from: lines(
57
+ " * A session cookie is that session's user, or a refusal — never a fallback to anyone else:",
58
+ ' * `X_SESSION_EXPIRED` for a session past its absolute or idle expiry, `X_UNAUTHENTICATED` for',
59
+ ' * one that is unknown, revoked or forged, or whose user is disabled. No cookie is the development',
60
+ ' * viewer or nobody.',
61
+ ),
62
+ to: lines(
63
+ " * A session cookie is that session's user, or nobody — never a fallback to anyone else. A session",
64
+ ' * past its expiry, or one unknown, revoked or forged, or whose user is disabled, is a refusal',
65
+ ' * `authenticate()` THROWS (`isSessionRefusal`: `X_SESSION_EXPIRED`, `X_UNAUTHENTICATED`), and it',
66
+ ' * is answered `null`: a stale cookie is an anonymous visitor, so sign-in still opens and a live',
67
+ ' * socket it opened is closed. Anything else it throws — a session store that is down — is not an',
68
+ ' * answer about this visitor and propagates. No cookie is the development viewer or nobody.',
69
+ ),
70
+ optional: true,
71
+ },
72
+ {
73
+ from: lines(
74
+ ' if (token !== null && token.length > 0) return await authenticate(auth, token);',
75
+ ' return options.development ? devAuthenticate(request) : null;',
76
+ ' };',
77
+ ),
78
+ to: lines(
79
+ ' if (token === null || token.length === 0) {',
80
+ ' return options.development ? devAuthenticate(request) : null;',
81
+ ' }',
82
+ CATCH.replace('TARGET', 'auth'),
83
+ ),
84
+ },
85
+ ];
86
+
87
+ const SCAFFOLD_TEST: readonly SnippetEdit[] = [
88
+ AUTH_IMPORT,
89
+ {
90
+ from: lines(
91
+ "unitTest('a cookie naming no live session is refused, never answered as the viewer', async () => {",
92
+ ' const auth = memoryAuth();',
93
+ " const request = requestWith({ [auth().sessions.policy.cookieName]: 'forged.token' });",
94
+ ' await expect(sessionAuthenticator({ auth, development: true })(request)).rejects.toMatchObject({',
95
+ " code: 'X_UNAUTHENTICATED',",
96
+ ' });',
97
+ '});',
98
+ ),
99
+ to: lines(
100
+ "unitTest('a cookie naming no live session is nobody, never answered as the viewer', async () => {",
101
+ ' const auth = memoryAuth();',
102
+ " const request = requestWith({ [auth().sessions.policy.cookieName]: 'forged.token' });",
103
+ NULL_NOT_THROW,
104
+ ' expect(await sessionAuthenticator({ auth, development: true })(request)).toBeNull();',
105
+ '});',
106
+ '',
107
+ SIGNED_OUT_TEST(
108
+ 'request',
109
+ lines(
110
+ ' for (const development of [true, false]) {',
111
+ ' expect(await sessionAuthenticator({ auth, development })(request)).toBeNull();',
112
+ ' }',
113
+ ),
114
+ ),
115
+ ),
116
+ },
117
+ ];
118
+
119
+ /** `x g sign-in`'s authenticator: no development fallback at all. */
120
+ const SIGN_IN: readonly SnippetEdit[] = [
121
+ {
122
+ from: "import type { Actor } from '@ultimat3/core';",
123
+ to: "import { type Actor, isSessionRefusal } from '@ultimat3/core';",
124
+ },
125
+ {
126
+ from: lines(
127
+ " * A session cookie is that session's user, or a refusal — never a fallback to anyone else:",
128
+ ' * `X_SESSION_EXPIRED` past its expiry, `X_UNAUTHENTICATED` for one unknown, revoked or forged.',
129
+ ),
130
+ to: lines(
131
+ " * A session cookie is that session's user, or nobody — never a fallback to anyone else. A session",
132
+ ' * past its expiry, or one unknown, revoked or forged, is a refusal `authenticate()` THROWS',
133
+ ' * (`isSessionRefusal`: `X_SESSION_EXPIRED`, `X_UNAUTHENTICATED`), answered `null`: a stale',
134
+ ' * cookie is an anonymous visitor, so sign-in still opens and a live socket it opened is closed.',
135
+ ' * Anything else it throws — a session store that is down — propagates.',
136
+ ),
137
+ optional: true,
138
+ },
139
+ {
140
+ from: lines(
141
+ ' return token !== null && token.length > 0 ? await authenticate(resolved, token) : null;',
142
+ ' };',
143
+ ),
144
+ to: lines(
145
+ ' if (token === null || token.length === 0) return null;',
146
+ CATCH.replace('TARGET', 'resolved'),
147
+ ),
148
+ },
149
+ ];
150
+
151
+ const SIGN_IN_TEST: readonly SnippetEdit[] = [
152
+ {
153
+ from: '// A session cookie is the user it was issued to; a bad one is refused; none is nobody.',
154
+ to: lines(
155
+ '// A session cookie is the user it was issued to; a bad, expired or signed-out one is nobody, and',
156
+ '// so is none.',
157
+ ),
158
+ optional: true,
159
+ },
160
+ AUTH_IMPORT,
161
+ {
162
+ from: lines(
163
+ "unitTest('a forged cookie is refused, and no cookie is anonymous', async () => {",
164
+ ' const auth = memoryAuth();',
165
+ " const forged = requestWith({ [auth().sessions.policy.cookieName]: 'forged.token' });",
166
+ ' await expect(sessionAuthenticator(auth)(forged)).rejects.toMatchObject({',
167
+ " code: 'X_UNAUTHENTICATED',",
168
+ ' });',
169
+ ' expect(await sessionAuthenticator(auth)(requestWith({}))).toBeNull();',
170
+ '});',
171
+ ),
172
+ to: lines(
173
+ "unitTest('a forged cookie is nobody, and no cookie is anonymous', async () => {",
174
+ ' const auth = memoryAuth();',
175
+ " const forged = requestWith({ [auth().sessions.policy.cookieName]: 'forged.token' });",
176
+ NULL_NOT_THROW,
177
+ ' expect(await sessionAuthenticator(auth)(forged)).toBeNull();',
178
+ ' expect(await sessionAuthenticator(auth)(requestWith({}))).toBeNull();',
179
+ '});',
180
+ '',
181
+ SIGNED_OUT_TEST('cookie', ' expect(await sessionAuthenticator(auth)(cookie)).toBeNull();'),
182
+ ),
183
+ },
184
+ ];
185
+
186
+ /** Each shape's edits by file: what the codemod runs, and what its test runs backwards. */
187
+ export const AUTHENTICATOR_EDITS = {
188
+ scaffold: { [SOURCE]: SCAFFOLD, [TEST]: SCAFFOLD_TEST },
189
+ signIn: { [SOURCE]: SIGN_IN, [TEST]: SIGN_IN_TEST },
190
+ } as const;
191
+
192
+ /** `x g sign-in` rewrote the authenticator with no development fallback: its own signature. */
193
+ const isSignIn = async (app: CodemodApp): Promise<boolean> =>
194
+ ((await app.read(SOURCE)) ?? '').includes('(auth: () => Auth) =>');
195
+
196
+ export const codemod: Codemod = {
197
+ id: 'authenticator-session-refusal',
198
+ since: '31.20.0',
199
+ summary:
200
+ 'apps/web/app/auth/authenticator.ts answers a stale, revoked or forged session cookie null instead of throwing (and its test says so)',
201
+ async run(app) {
202
+ // The scaffold's file names `sessionAuthenticator`; one that does not is the app's own, and
203
+ // one that already answers `isSessionRefusal` has been carried across, by hand or otherwise.
204
+ const source = (await readText(app, SOURCE))?.text ?? '';
205
+ if (!source.includes('sessionAuthenticator') || source.includes('isSessionRefusal')) {
206
+ return { changed: [], skipped: [] };
207
+ }
208
+ const signIn = await isSignIn(app);
209
+ return mergeResults([
210
+ await editSnippets(app, SOURCE, signIn ? SIGN_IN : SCAFFOLD),
211
+ await editSnippets(app, TEST, signIn ? SIGN_IN_TEST : SCAFFOLD_TEST),
212
+ ]);
213
+ },
214
+ };
@@ -0,0 +1,58 @@
1
+ // 31.6.0: named exports only, as a lint rule — biome.json turns on `noDefaultExport`, off for
2
+ // `scss.d.ts`. Turned on only where the app holds no default export: elsewhere the change is
3
+ // reported with the files it would red, never a lint failure the hop introduced.
4
+
5
+ import type { Codemod } from './codemod';
6
+ import { unifiedDiff } from './engine-diff';
7
+ import type { SnippetEdit } from './engine-edits';
8
+ import { editSnippets, fileText } from './engine-edits';
9
+
10
+ const BIOME = 'biome.json';
11
+
12
+ export const BIOME_EDITS: readonly SnippetEdit[] = [
13
+ {
14
+ from: ' "style": { "useNodejsImportProtocol": "error" }',
15
+ to: ' "style": { "useNodejsImportProtocol": "error", "noDefaultExport": "error" }',
16
+ },
17
+ {
18
+ from: ' "overrides": [\n {\n "includes": ["**/*.scss"],',
19
+ to: ' "overrides": [\n {\n "includes": ["**/scss.d.ts"],\n "linter": { "rules": { "style": { "noDefaultExport": "off" } } }\n },\n {\n "includes": ["**/*.scss"],',
20
+ },
21
+ ];
22
+
23
+ /** The app's own sources that default-export: what the rule would red. */
24
+ async function defaultExports(app: Parameters<Codemod['run']>[0]): Promise<readonly string[]> {
25
+ const found: string[] = [];
26
+ for (const path of await app.glob('**/*.{ts,tsx,js,mjs}')) {
27
+ if (path.includes('node_modules/') || path.endsWith('scss.d.ts')) continue;
28
+ if (/^export default\b/m.test((await app.read(path)) ?? '')) found.push(path);
29
+ }
30
+ return found;
31
+ }
32
+
33
+ export const codemod: Codemod = {
34
+ id: 'biome-no-default-export',
35
+ since: '31.6.0',
36
+ summary: `${BIOME}: noDefaultExport is an error, off for scss.d.ts — named exports only`,
37
+ async run(app) {
38
+ const held = await app.read(BIOME);
39
+ if (held === undefined || held.includes('"noDefaultExport"'))
40
+ return { changed: [], skipped: [] };
41
+ // Not the file x new wrote (a monorepo child extending the repo's): its rules are the app's.
42
+ const text = fileText(held).text;
43
+ if (BIOME_EDITS.some((edit) => !text.includes(edit.from))) return { changed: [], skipped: [] };
44
+ const blocking = await defaultExports(app);
45
+ if (blocking.length === 0) return editSnippets(app, BIOME, BIOME_EDITS);
46
+ const wanted = BIOME_EDITS.reduce((text, edit) => text.replace(edit.from, () => edit.to), held);
47
+ return {
48
+ changed: [],
49
+ skipped: [
50
+ {
51
+ path: BIOME,
52
+ reason: `noDefaultExport left off: ${blocking.slice(0, 5).join(', ')} default-export, and the rule would red lint. Make them named exports, then apply the diff`,
53
+ diff: unifiedDiff(BIOME, held, wanted),
54
+ },
55
+ ],
56
+ };
57
+ },
58
+ };
@@ -0,0 +1,33 @@
1
+ // 31.27.0: island coverage is credited to its source through the chunk's source map, so the
2
+ // `coveragePathIgnorePatterns` line `x new` wrote to hide the built chunk hides nothing true now.
3
+ // Removed with its comment where it stands as written; an edited bunfig.toml keeps its own.
4
+
5
+ import type { Codemod } from './codemod';
6
+ import type { SnippetEdit } from './engine-edits';
7
+ import { editSnippets } from './engine-edits';
8
+
9
+ const BUNFIG = 'bunfig.toml';
10
+ const PRELOAD = 'preload = ["@ultimat3/testing/preload"]';
11
+
12
+ export const BUNFIG_EDITS: readonly SnippetEdit[] = [
13
+ {
14
+ from: [
15
+ PRELOAD,
16
+ '# An island is mounted from a BUILT chunk that `mountIsland` writes to a temp .mjs, so',
17
+ '# `bun test --coverage` reports that file: two minified lines, under a name no source has. Bun',
18
+ '# does not remap a pre-built module through its sourcemap (measured on 1.4.0, and the build does',
19
+ "# emit one), so the row can only ever be noise — the island's own .island.tsx is not what it",
20
+ '# describes. Ignoring it removes the phantom; it hides no line any test was covering.',
21
+ 'coveragePathIgnorePatterns = ["**/*.mjs"]',
22
+ ].join('\n'),
23
+ // No newline at either end: a bunfig.toml whose last line is the ignore still matches.
24
+ to: PRELOAD,
25
+ },
26
+ ];
27
+
28
+ export const codemod: Codemod = {
29
+ id: 'bunfig-island-coverage',
30
+ since: '31.27.0',
31
+ summary: `${BUNFIG}: the island-chunk coverage ignore goes, now that island coverage maps to its source`,
32
+ run: (app) => editSnippets(app, BUNFIG, BUNFIG_EDITS),
33
+ };
@@ -0,0 +1,73 @@
1
+ // 31.18.0: every chart ships a Grafana dashboard (`dashboards/ultimate-app.json`, its ConfigMap,
2
+ // off by default) and a `dashboard:` values block. A chart that predates it gains all three, as
3
+ // `x g chart-dashboard` writes them; a file or key the app already holds is the app's.
4
+
5
+ import { stringField } from '@ultimat3/core';
6
+ import { CHART_FILE, missingValueBlocks, VALUES_FILE } from '../generate-chart-alerts';
7
+ import { helmDashboardFiles } from '../templates/chart-dashboard';
8
+ import { names } from '../templates/naming';
9
+ import type { Codemod, CodemodApp, CodemodResult } from './codemod';
10
+ import { mergeResults, writeIfAbsent } from './engine-edits';
11
+
12
+ const NOTHING: CodemodResult = { changed: [], skipped: [] };
13
+
14
+ /** The values.yaml line `x new` writes right after the monitoring blocks. */
15
+ const BEFORE = "# The image's `bun` user, the same uid as the Dockerfile's USER";
16
+
17
+ /** The chart's `name`, which its helpers are named after; undefined when it declares none. */
18
+ export const chartName = (source: string): string | undefined => {
19
+ let parsed: unknown;
20
+ try {
21
+ parsed = Bun.YAML.parse(source);
22
+ } catch {
23
+ return undefined;
24
+ }
25
+ const name = stringField(parsed, 'name');
26
+ return name !== undefined && /^[a-z0-9][a-z0-9-]*$/.test(name) ? name : undefined;
27
+ };
28
+
29
+ async function valuesBlock(app: CodemodApp): Promise<CodemodResult> {
30
+ const values = await app.read(VALUES_FILE);
31
+ if (values === undefined) return NOTHING;
32
+ const blocks = missingValueBlocks(values, 'chart-dashboard');
33
+ if (blocks === '') return NOTHING;
34
+ // Where `x new` puts it, before the pod security block; past an edited values.yaml, at its end.
35
+ const at = values.indexOf(BEFORE);
36
+ const next =
37
+ at === -1
38
+ ? `${values.trimEnd()}\n\n${blocks.trimEnd()}\n`
39
+ : `${values.slice(0, at)}${blocks}${values.slice(at)}`;
40
+ await app.write(VALUES_FILE, next);
41
+ return { changed: [VALUES_FILE], skipped: [] };
42
+ }
43
+
44
+ export const codemod: Codemod = {
45
+ id: 'chart-dashboard',
46
+ since: '31.18.0',
47
+ summary:
48
+ 'docker/helm gains the Grafana dashboard: dashboards/ultimate-app.json, templates/dashboard-configmap.yaml and a dashboard: block in values.yaml (off by default)',
49
+ async run(app) {
50
+ const chart = await app.read(CHART_FILE);
51
+ if (chart === undefined) return NOTHING;
52
+ const name = chartName(chart);
53
+ if (name === undefined) {
54
+ return {
55
+ changed: [],
56
+ skipped: [
57
+ {
58
+ path: CHART_FILE,
59
+ reason:
60
+ 'it declares no chart name of lowercase letters, digits and hyphens, and the dashboard ConfigMap is named after it: set name:, then run x g chart-dashboard',
61
+ },
62
+ ],
63
+ };
64
+ }
65
+ const written: CodemodResult[] = [];
66
+ for (const file of helmDashboardFiles(names(name))) {
67
+ if (typeof file.contents === 'string') {
68
+ written.push(await writeIfAbsent(app, file.path, file.contents));
69
+ }
70
+ }
71
+ return mergeResults([...written, await valuesBlock(app)]);
72
+ },
73
+ };