@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,151 @@
1
+ // A hop's codemods, applied by the CLI the hop just installed (`x upgrade codemods`): that CLI holds
2
+ // the target release's list, which this one may predate. An installed CLI with no such subcommand
3
+ // (one older than the engine) answers no document; this CLI applies its own list instead.
4
+
5
+ // why: Bun exposes no path-join primitive; the installed bin is assembled from the app root.
6
+ import { join } from 'node:path';
7
+ import { t } from '@ultimat3/schema';
8
+ import { CODEMODS } from './codemods';
9
+ import type { CodemodsReport } from './codemods/engine';
10
+ import { runCodemods } from './codemods/engine';
11
+ import { fsCodemodApp } from './codemods/engine-fs';
12
+ import { supersededFindings } from './doctor-superseded';
13
+ import type { ExecResult, Runner } from './exec';
14
+ import { LOCAL_CLI_BIN } from './local-cli';
15
+ import type { Finding } from './output';
16
+ import { documentIn } from './upgrade-document';
17
+ import { manifestSnapshot, reinstallIfMoved } from './upgrade-gate-codemods-install';
18
+ import type { HopCodemods } from './upgrade-report-codemods';
19
+
20
+ const SKIP = t.object({ path: t.string, reason: t.string, diff: t.optional(t.string) });
21
+ const OUTCOME = t.object({
22
+ id: t.string,
23
+ since: t.string,
24
+ summary: t.string,
25
+ changed: t.array(t.string),
26
+ skipped: t.array(SKIP),
27
+ });
28
+ const DOCUMENT = t.object({
29
+ data: t.object({
30
+ codemods: t.object({
31
+ from: t.string,
32
+ to: t.string,
33
+ dryRun: t.boolean,
34
+ applied: t.array(OUTCOME),
35
+ }),
36
+ }),
37
+ });
38
+
39
+ /** The installed CLI's report, or undefined when it answered none this one can read. */
40
+ export function readCodemods(result: ExecResult): CodemodsReport | undefined {
41
+ const parsed = DOCUMENT.safeParse(documentIn(result.stdout));
42
+ if (!result.ok || parsed.issues !== undefined) return undefined;
43
+ return (parsed.value as { readonly data: { readonly codemods: CodemodsReport } }).data.codemods;
44
+ }
45
+
46
+ /**
47
+ * The codes an installed CLI with no `x upgrade codemods` answers: an unknown flag or subcommand,
48
+ * an unknown command. Only those leave the span to this CLI; any other failure is the hop's.
49
+ */
50
+ const NO_SUBCOMMAND = new Set(['X_CLI_BAD_FLAG', 'X_CLI_UNKNOWN_COMMAND', 'X_NOT_IMPLEMENTED']);
51
+
52
+ const FAILURE = t.object({
53
+ findings: t.array(t.object({ code: t.string, cause: t.string, fix: t.string })),
54
+ });
55
+
56
+ /** The installed CLI's own failure, when it is one: undefined when it simply lacks the subcommand. */
57
+ function failureOf(result: ExecResult): HopCodemods['failure'] {
58
+ const parsed = FAILURE.safeParse(documentIn(result.stdout));
59
+ if (parsed.issues !== undefined) return undefined;
60
+ const [first] = (parsed.value as { readonly findings: NonNullable<HopCodemods['failure']>[] })
61
+ .findings;
62
+ return first === undefined || NO_SUBCOMMAND.has(first.code) ? undefined : first;
63
+ }
64
+
65
+ /**
66
+ * The span's codemods, by the installed CLI (or this one, only when that one lacks the
67
+ * subcommand), then a second `bun install` when any `package.json` moved — `reinstalled: true`.
68
+ */
69
+ export async function applyHopCodemods(input: {
70
+ readonly runner: Runner;
71
+ readonly root: string;
72
+ readonly from: string;
73
+ readonly to: string;
74
+ }): Promise<HopCodemods> {
75
+ const { runner, root, from, to } = input;
76
+ const before = await manifestSnapshot(root);
77
+ const result = await runner(
78
+ [
79
+ process.execPath,
80
+ join(root, LOCAL_CLI_BIN),
81
+ 'upgrade',
82
+ 'codemods',
83
+ '--from',
84
+ from,
85
+ '--to',
86
+ to,
87
+ '--json',
88
+ ],
89
+ { cwd: root },
90
+ );
91
+ const answered = readCodemods(result);
92
+ const failure = answered === undefined ? failureOf(result) : undefined;
93
+ if (failure !== undefined) {
94
+ return { from, to, dryRun: false, applied: [], source: 'installed', failure };
95
+ }
96
+ const report: HopCodemods =
97
+ answered !== undefined
98
+ ? { ...answered, source: 'installed' }
99
+ : {
100
+ ...(await runCodemods({
101
+ app: fsCodemodApp(root),
102
+ codemods: CODEMODS,
103
+ from,
104
+ to,
105
+ dryRun: false,
106
+ })),
107
+ source: 'driver',
108
+ };
109
+ return (await reinstallIfMoved({ runner, root, to, before }))
110
+ ? { ...report, reinstalled: true }
111
+ : report;
112
+ }
113
+
114
+ /**
115
+ * `x upgrade --dry-run`'s view: this CLI's codemods over the span, written nowhere, and the
116
+ * superseded workarounds the tree holds now. The hop itself applies the installed release's list.
117
+ */
118
+ export async function previewCodemods(
119
+ root: string,
120
+ from: string,
121
+ to: string,
122
+ ): Promise<{ readonly codemods: HopCodemods; readonly superseded: readonly Finding[] }> {
123
+ const own = await runCodemods({
124
+ app: fsCodemodApp(root),
125
+ codemods: CODEMODS,
126
+ from,
127
+ to,
128
+ dryRun: true,
129
+ });
130
+ return { codemods: { ...own, source: 'driver' }, superseded: await supersededFindings(root) };
131
+ }
132
+
133
+ /** Below every release: an app already at its target reruns every codemod, which are idempotent. */
134
+ export const EVERY_RELEASE = '0.0.0';
135
+
136
+ /**
137
+ * No version moves, and still no copy of an old template stays: every codemod up to the release
138
+ * the app is on, through the installed CLI as a hop would (a dry run previews this CLI's list).
139
+ * Each is idempotent, so one already applied is a run that changes nothing.
140
+ */
141
+ export async function atTargetCodemods(input: {
142
+ readonly runner: Runner;
143
+ readonly root: string;
144
+ readonly to: string;
145
+ readonly dryRun: boolean;
146
+ }): Promise<{ readonly codemods: HopCodemods; readonly superseded: readonly Finding[] }> {
147
+ const { runner, root, to } = input;
148
+ if (input.dryRun) return previewCodemods(root, EVERY_RELEASE, to);
149
+ const codemods = await applyHopCodemods({ runner, root, from: EVERY_RELEASE, to });
150
+ return { codemods, superseded: await supersededFindings(root) };
151
+ }
@@ -1,11 +1,12 @@
1
- // A hop's gate, run by the CLI the hop just installed: manifest, doctor, the missing guards and a
2
- // Bun-floor hop's coverage (`upgrade-guards.ts`, `upgrade-coverage.ts`), exercise, verify. Never in
3
- // this process: the installed CLI knows the installed framework (`local-cli.ts`) and may be majors
4
- // older, so each answer is read as a foreign document, and one that will not parse is never green.
1
+ // A hop's gate, run by the CLI the hop just installed: codemods, manifest, doctor, missing guards,
2
+ // a Bun-floor hop's coverage, exercise, verify (`upgrade-gate-codemods.ts`, `upgrade-guards.ts`).
3
+ // Never in this process: the installed CLI may be majors older, so each answer is read as a
4
+ // foreign document (`local-cli.ts`), and one that will not parse is never green.
5
5
 
6
6
  // why: Bun exposes no path-join primitive; the installed bin is assembled from the app root.
7
7
  import { join } from 'node:path';
8
8
  import { t } from '@ultimat3/schema';
9
+ import { supersededFindings } from './doctor-superseded';
9
10
  import type { ExecResult, Runner } from './exec';
10
11
  import { execOutput } from './exec';
11
12
  import { exerciseReportStamp } from './exercise-floor-report';
@@ -15,9 +16,11 @@ import { rebaselineCoverage, statedCoverage } from './upgrade-coverage';
15
16
  import { documentIn } from './upgrade-document';
16
17
  import type { HopExerciseFloor } from './upgrade-exercise-floor';
17
18
  import { ratchetExerciseFloor } from './upgrade-exercise-floor';
19
+ import { applyHopCodemods } from './upgrade-gate-codemods';
18
20
  import type { BaselinedGuard, WithheldGuard } from './upgrade-guards';
19
21
  import { installMissingGuards } from './upgrade-guards';
20
22
  import { parseJson } from './upgrade-registry';
23
+ import type { HopCodemods } from './upgrade-report-codemods';
21
24
 
22
25
  // Where it always was: `verify-exercise.ts` and `verify-budgets-build.ts` read it from here.
23
26
  export { documentIn } from './upgrade-document';
@@ -120,6 +123,10 @@ export interface HopExercise {
120
123
  }
121
124
 
122
125
  export interface HopGate {
126
+ /** The codemods the hop applied before anything below judged the tree; null when none were asked. */
127
+ readonly codemods?: HopCodemods | null;
128
+ /** Workarounds the hop's framework made unnecessary, read after the codemods: warnings, never red. */
129
+ readonly superseded?: readonly GateFinding[];
123
130
  readonly manifest: { readonly ok: boolean; readonly findings: readonly GateFinding[] };
124
131
  /**
125
132
  * The installed `x doctor`'s `data.warnings[]`: never red on this major, the next one's red —
@@ -225,7 +232,14 @@ const readGuards = (doctor: DoctorDocument['data']): HopGuards => {
225
232
  };
226
233
  };
227
234
 
228
- export type HopStage = 'manifest' | 'doctor' | 'guards' | 'coverage' | 'exercise' | 'verify';
235
+ export type HopStage =
236
+ | 'codemods'
237
+ | 'manifest'
238
+ | 'doctor'
239
+ | 'guards'
240
+ | 'coverage'
241
+ | 'exercise'
242
+ | 'verify';
229
243
 
230
244
  /**
231
245
  * The gate, in order, each stage told apart by `onStage` so a long gate is not a long silence.
@@ -238,10 +252,18 @@ export async function runHopGate(input: {
238
252
  readonly onStage: (stage: HopStage) => void;
239
253
  /** Present when the hop moved the Bun floor: what the coverage rebaseline's `why` says. */
240
254
  readonly bunMoved?: CoverageRebaseline;
255
+ /** The span whose codemods run first, so every later stage judges the carried-across tree. */
256
+ readonly codemods?: { readonly from: string; readonly to: string };
241
257
  }): Promise<HopGate> {
242
258
  const { runner, root, onStage } = input;
243
259
  const installed = (args: readonly string[]): Promise<ExecResult> =>
244
260
  runner([process.execPath, join(root, LOCAL_CLI_BIN), ...args], { cwd: root });
261
+ let codemods: HopCodemods | null = null;
262
+ if (input.codemods !== undefined) {
263
+ onStage('codemods');
264
+ codemods = await applyHopCodemods({ runner, root, ...input.codemods });
265
+ }
266
+ const superseded = (await supersededFindings(root)).map(pick);
245
267
  onStage('manifest');
246
268
  const manifest = readManifest(await installed(['manifest', '--json']));
247
269
  onStage('doctor');
@@ -273,7 +295,17 @@ export async function runHopGate(input: {
273
295
  const exerciseFloor = await ratchetExerciseFloor(root, stamp);
274
296
  onStage('verify');
275
297
  const verify = readVerify(await installed(['verify', '--json']));
276
- return { manifest, doctorWarnings, guards, coverage, exercise, exerciseFloor, verify };
298
+ return {
299
+ codemods,
300
+ superseded,
301
+ manifest,
302
+ doctorWarnings,
303
+ guards,
304
+ coverage,
305
+ exercise,
306
+ exerciseFloor,
307
+ verify,
308
+ };
277
309
  }
278
310
 
279
311
  /** What a repository with no app can still be asked, in the order an author would run them. */
@@ -0,0 +1,118 @@
1
+ // One `x upgrade` per app at a time: `.x/upgrade.lock`, claimed the way `dev-lock.ts` claims
2
+ // `dev.lock` — written whole to a staging file, then hard-linked into place, so the create and the
3
+ // exclusivity are one syscall. Two hops over one tree would each write pins and install under the other.
4
+
5
+ // why: the claim is synchronous link/write/unlink syscalls with no Bun equivalent, kept in one turn.
6
+ import { linkSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
7
+ // why: Bun exposes no path-join primitive.
8
+ import { join } from 'node:path';
9
+ import { renderFixShellArg, stringField, UltimateError } from '@ultimat3/core';
10
+ import { isProcessAlive } from './dev-lock';
11
+ import { stealStale } from './dev-lock-steal';
12
+
13
+ /** App-root relative, beside the hop's record in the `.x/` every scaffold ignores. */
14
+ export const UPGRADE_LOCK_FILE = join('.x', 'upgrade.lock');
15
+
16
+ interface Holder {
17
+ readonly pid: number;
18
+ readonly startedAt: string;
19
+ }
20
+
21
+ const parseHolder = (raw: string | undefined): Holder | undefined => {
22
+ if (raw === undefined) return undefined;
23
+ try {
24
+ const value = JSON.parse(raw) as { pid?: unknown; startedAt?: unknown };
25
+ if (typeof value.pid !== 'number') return undefined;
26
+ return {
27
+ pid: value.pid,
28
+ startedAt: typeof value.startedAt === 'string' ? value.startedAt : '',
29
+ };
30
+ } catch {
31
+ return undefined;
32
+ }
33
+ };
34
+
35
+ const readText = (path: string): string | undefined => {
36
+ try {
37
+ return readFileSync(path, 'utf8');
38
+ } catch {
39
+ return undefined;
40
+ }
41
+ };
42
+
43
+ const unwritable = (path: string, error: unknown): UltimateError =>
44
+ new UltimateError({
45
+ code: 'X_UPGRADE_LOCKED',
46
+ cause: `${path} could not be created (${stringField(error, 'code') ?? 'unknown error'}), so this hop cannot prove it is the only one in this app`,
47
+ fix: `ls -ld ${renderFixShellArg(join(path, '..'), '<app>/.x')} # make it writable by this user, on a filesystem with hard links, then: x upgrade --json`,
48
+ });
49
+
50
+ /** Create `path` holding `text`, exclusively: `false` when it already exists. */
51
+ function claim(path: string, text: string): boolean {
52
+ const staged = `${path}.${process.pid}.${crypto.randomUUID().slice(0, 8)}.tmp`;
53
+ try {
54
+ writeFileSync(staged, text);
55
+ linkSync(staged, path);
56
+ return true;
57
+ } catch (error) {
58
+ if (stringField(error, 'code') === 'EEXIST') return false;
59
+ throw unwritable(path, error);
60
+ } finally {
61
+ try {
62
+ unlinkSync(staged);
63
+ } catch {
64
+ // Never written, or already gone: the staging name is unique to this call.
65
+ }
66
+ }
67
+ }
68
+
69
+ export interface LockDeps {
70
+ /** Whether a pid is a live process. */
71
+ readonly alive?: (pid: number) => boolean;
72
+ /** The pid this run records; a test claims as another process. */
73
+ readonly pid?: number;
74
+ }
75
+
76
+ /**
77
+ * Take the app's upgrade lock, or refuse with `X_UPGRADE_LOCKED` naming the live holder. A lock
78
+ * whose holder is gone — a hop killed hard — is taken over under `stealStale`'s guard. Returns the
79
+ * release, which removes the lock only while it still holds this run's bytes.
80
+ */
81
+ export function acquireUpgradeLock(root: string, deps: LockDeps = {}): () => void {
82
+ const alive = deps.alive ?? isProcessAlive;
83
+ const path = join(root, UPGRADE_LOCK_FILE);
84
+ try {
85
+ mkdirSync(join(root, '.x'), { recursive: true });
86
+ } catch (error) {
87
+ throw unwritable(path, error);
88
+ }
89
+ const mine = `${JSON.stringify({ pid: deps.pid ?? process.pid, startedAt: new Date().toISOString() })}\n`;
90
+ for (let attempt = 0; attempt < 3; attempt += 1) {
91
+ if (claim(path, mine)) {
92
+ return () => {
93
+ if (readText(path) === mine) unlinkSync(path);
94
+ };
95
+ }
96
+ const raw = readText(path);
97
+ const holder = parseHolder(raw);
98
+ if (holder !== undefined && alive(holder.pid)) {
99
+ throw new UltimateError({
100
+ code: 'X_UPGRADE_LOCKED',
101
+ cause: `another x upgrade (pid ${String(holder.pid)}, since ${holder.startedAt || 'an unknown time'}) holds ${path}, and two hops in one app would write pins and install under each other`,
102
+ fix: `ps -p ${String(holder.pid)} -o pid,etime,args # the hop holding the lock: let it finish, or stop it, then: x upgrade --json`,
103
+ });
104
+ }
105
+ // Gone, torn or unreadable: stale. Removed only while it still holds the bytes judged.
106
+ if (
107
+ raw !== undefined &&
108
+ stealStale({ path, judged: raw, claim: (p) => claim(p, mine), alive }) === 'busy'
109
+ ) {
110
+ break;
111
+ }
112
+ }
113
+ throw new UltimateError({
114
+ code: 'X_UPGRADE_LOCKED',
115
+ cause: `${path} is being taken over by another x upgrade right now`,
116
+ fix: `cat ${renderFixShellArg(path, '<app>/.x/upgrade.lock')} # the pid now holding it; when that process is gone: x upgrade --json`,
117
+ });
118
+ }
@@ -63,7 +63,8 @@ export function releaseOf(version: string): Triple | undefined {
63
63
 
64
64
  const tripleOf = (version: string): Triple => releaseOf(version) ?? [0, 0, 0];
65
65
 
66
- const compareVersions = (a: string, b: string): number => {
66
+ /** Release order over plain `major.minor.patch`; anything else sorts as `0.0.0`. */
67
+ export const compareVersions = (a: string, b: string): number => {
67
68
  const left = tripleOf(a);
68
69
  const right = tripleOf(b);
69
70
  return left[0] - right[0] || left[1] - right[1] || left[2] - right[2];
@@ -0,0 +1,54 @@
1
+ // The codemod half of what `x upgrade` says: one line per codemod that ran, one per file it
2
+ // changed, and each file it left for the author with the reason and the diff to apply by hand.
3
+
4
+ import type { CodemodsReport } from './codemods/engine';
5
+ import { msg } from './messages';
6
+
7
+ /** Where a hop's codemods came from: the CLI it installed, or this one when that one has none. */
8
+ export type CodemodSource = 'installed' | 'driver';
9
+
10
+ export interface HopCodemods extends CodemodsReport {
11
+ readonly source: CodemodSource;
12
+ /** Present when a codemod changed a `package.json` and the hop ran `bun install` again. */
13
+ readonly reinstalled?: true;
14
+ /** The installed CLI's codemods run failed: nothing applied, and the hop is not done. */
15
+ readonly failure?: { readonly code: string; readonly cause: string; readonly fix: string };
16
+ }
17
+
18
+ export const codemodCounts = (
19
+ report: CodemodsReport,
20
+ ): { readonly count: number; readonly changed: number; readonly skipped: number } => ({
21
+ count: report.applied.length,
22
+ changed: report.applied.reduce((sum, one) => sum + one.changed.length, 0),
23
+ skipped: report.applied.reduce((sum, one) => sum + one.skipped.length, 0),
24
+ });
25
+
26
+ export function codemodLines(report: CodemodsReport | HopCodemods | null): readonly string[] {
27
+ if (report !== null && 'failure' in report && report.failure !== undefined) {
28
+ return [msg('cli.upgrade.codemods.failed', { ...report.failure })];
29
+ }
30
+ if (report === null || report.applied.length === 0) return [];
31
+ return [
32
+ ...('source' in report && report.source === 'driver'
33
+ ? [msg('cli.upgrade.codemods.fromDriver')]
34
+ : []),
35
+ ...report.applied.flatMap((one) => [
36
+ msg('cli.upgrade.codemod', {
37
+ id: one.id,
38
+ since: one.since,
39
+ summary: one.summary,
40
+ changed: one.changed.length,
41
+ skipped: one.skipped.length,
42
+ }),
43
+ ...one.changed.map((path) => msg('cli.upgrade.codemod.changed', { path })),
44
+ ...one.skipped.flatMap((skip) => [
45
+ msg('cli.upgrade.codemod.skipped', { path: skip.path, reason: skip.reason }),
46
+ ...(skip.diff ?? '')
47
+ .trimEnd()
48
+ .split('\n')
49
+ .filter((line) => line !== '')
50
+ .map((line) => ` ${line}`),
51
+ ]),
52
+ ]),
53
+ ];
54
+ }
@@ -9,6 +9,23 @@ import type { BunEdit, BunManual } from './upgrade-bun-floor';
9
9
  import type { GateFinding, HopGate, RepoScript } from './upgrade-gate';
10
10
  import type { UpgradeHop, UpgradePin } from './upgrade-plan';
11
11
  import { pinMoves } from './upgrade-plan';
12
+ import type { HopCodemods } from './upgrade-report-codemods';
13
+ import { codemodLines } from './upgrade-report-codemods';
14
+
15
+ /** A dry run's codemod preview and superseded scan; a hop's come from its gate. */
16
+ interface Previewed {
17
+ readonly codemods?: HopCodemods;
18
+ readonly superseded?: readonly GateFinding[];
19
+ }
20
+
21
+ const supersededLines = (findings: readonly GateFinding[]): readonly string[] =>
22
+ findings.map((finding) =>
23
+ msg('cli.upgrade.superseded', {
24
+ at: finding.at === undefined ? '' : ` (${finding.at})`,
25
+ cause: finding.cause,
26
+ fix: finding.fix,
27
+ }),
28
+ );
12
29
 
13
30
  export interface PlannedWrites {
14
31
  /** Absolute path to final text; a manifest holding both a pin and a floor is written once. */
@@ -63,16 +80,18 @@ const findingLines = (findings: readonly GateFinding[]): readonly string[] =>
63
80
  ]);
64
81
 
65
82
  /** The terminal's form of the report: the url first, then each finding's `fix:`. */
66
- export const humanLines = (input: {
67
- readonly hop: UpgradeHop;
68
- readonly writes: PlannedWrites;
69
- readonly gate: HopGate | undefined;
70
- readonly scripts: readonly RepoScript[];
71
- readonly then: string;
72
- readonly agentsMd?: AgentsLinkState;
73
- /** Manifests whose TypeScript lags the scaffold's: by hand, the hop never moves a compiler. */
74
- readonly typescript: readonly TypescriptLag[];
75
- }): readonly string[] => {
83
+ export const humanLines = (
84
+ input: {
85
+ readonly hop: UpgradeHop;
86
+ readonly writes: PlannedWrites;
87
+ readonly gate: HopGate | undefined;
88
+ readonly scripts: readonly RepoScript[];
89
+ readonly then: string;
90
+ readonly agentsMd?: AgentsLinkState;
91
+ /** Manifests whose TypeScript lags the scaffold's: by hand, the hop never moves a compiler. */
92
+ readonly typescript: readonly TypescriptLag[];
93
+ } & Previewed,
94
+ ): readonly string[] => {
76
95
  const { hop, writes, gate, scripts, then, agentsMd, typescript } = input;
77
96
  return [
78
97
  ...(hop.section === null
@@ -88,6 +107,8 @@ export const humanLines = (input: {
88
107
  ...(agentsMd === 'link' || agentsMd === 'differs'
89
108
  ? [msg(agentsMd === 'link' ? 'cli.upgrade.agentsMd.link' : 'cli.upgrade.agentsMd.differs')]
90
109
  : []),
110
+ ...codemodLines(input.codemods ?? gate?.codemods ?? null),
111
+ ...supersededLines(input.superseded ?? gate?.superseded ?? []),
91
112
  ...(gate?.guards.installed ?? []).map((name) => msg('cli.upgrade.guardInstalled', { name })),
92
113
  ...(gate?.guards.baselined ?? []).map((guard) =>
93
114
  msg('cli.upgrade.guardBaselined', { name: guard.name, count: guard.findings }),
@@ -140,23 +161,25 @@ export const humanLines = (input: {
140
161
  const asJson = (value: unknown): JsonValue => value as JsonValue;
141
162
 
142
163
  /** The one shape every outcome reports: `--json` and the terminal project this and nothing else. */
143
- export const report = (input: {
144
- readonly hop: UpgradeHop;
145
- readonly done: boolean;
146
- readonly dryRun: boolean;
147
- readonly pins: readonly UpgradePin[];
148
- readonly bunFrom: string | null;
149
- readonly bunTo: string | null;
150
- readonly writes: PlannedWrites;
151
- readonly app: boolean;
152
- readonly gate: HopGate | undefined;
153
- readonly scripts: readonly RepoScript[];
154
- readonly then: string;
155
- /** What the hop does to `AGENTS.md` (`upgrade-agents-link.ts`); absent when no hop is planned. */
156
- readonly agentsMd?: AgentsLinkState;
157
- /** `typescript-floor.ts`'s lags — reported on every outcome, an at-target app's included. */
158
- readonly typescript: readonly TypescriptLag[];
159
- }): JsonValue => {
164
+ export const report = (
165
+ input: {
166
+ readonly hop: UpgradeHop;
167
+ readonly done: boolean;
168
+ readonly dryRun: boolean;
169
+ readonly pins: readonly UpgradePin[];
170
+ readonly bunFrom: string | null;
171
+ readonly bunTo: string | null;
172
+ readonly writes: PlannedWrites;
173
+ readonly app: boolean;
174
+ readonly gate: HopGate | undefined;
175
+ readonly scripts: readonly RepoScript[];
176
+ readonly then: string;
177
+ /** What the hop does to `AGENTS.md` (`upgrade-agents-link.ts`); absent when no hop is planned. */
178
+ readonly agentsMd?: AgentsLinkState;
179
+ /** `typescript-floor.ts`'s lags — reported on every outcome, an at-target app's included. */
180
+ readonly typescript: readonly TypescriptLag[];
181
+ } & Previewed,
182
+ ): JsonValue => {
160
183
  const { hop, done, dryRun, pins, bunFrom, bunTo, writes, app, gate, scripts, then } = input;
161
184
  return asJson({
162
185
  from: hop.from,
@@ -175,6 +198,8 @@ export const report = (input: {
175
198
  bun: { from: bunFrom, to: bunTo, edited: writes.edited, manual: writes.manual },
176
199
  typescript: input.typescript,
177
200
  agentsMd: input.agentsMd ?? null,
201
+ codemods: input.codemods ?? gate?.codemods ?? null,
202
+ superseded: input.superseded ?? gate?.superseded ?? [],
178
203
  guards: gate?.guards ?? null,
179
204
  coverage: gate?.coverage ?? null,
180
205
  manifest: gate?.manifest ?? null,
@@ -0,0 +1,91 @@
1
+ // A stopped `x upgrade` stops what it started. Every child carries the hop's tag in
2
+ // `STEP_TAG_ENV`, inherited by the gate's own children; SIGTERM or SIGINT kills that tree
3
+ // (`killTagged`, by pid on Windows), runs the cleanup, then re-raises like `signal-shred.ts`.
4
+
5
+ import type { Runner } from './exec';
6
+ import { killTagged, STEP_TAG_ENV, taskkillTree } from './verify-deadline';
7
+
8
+ /** This hop's word in `STEP_TAG_ENV`: unique per process, so a nested hop never kills its parent's. */
9
+ export const upgradeTag = (pid: number = process.pid): string => `x-upgrade-${String(pid)}`;
10
+
11
+ /**
12
+ * `runner` with the tag added to every child's env — after any tag an outer gate already set, as
13
+ * `guardStep` does — and each child's pid held in `pids` while it runs: Windows reads no
14
+ * process's environment, so the pid recorded at spawn is the only handle there.
15
+ */
16
+ export const tagRunner =
17
+ (
18
+ runner: Runner,
19
+ tag: string,
20
+ env: Readonly<Record<string, string | undefined>>,
21
+ pids: Set<number>,
22
+ ): Runner =>
23
+ async (command, options) => {
24
+ const inherited = options.env?.[STEP_TAG_ENV] ?? env[STEP_TAG_ENV];
25
+ const value = inherited === undefined || inherited === '' ? tag : `${inherited} ${tag}`;
26
+ let pid: number | undefined;
27
+ try {
28
+ return await runner(command, {
29
+ ...options,
30
+ env: { ...options.env, [STEP_TAG_ENV]: value },
31
+ onSpawn: (spawned) => {
32
+ pid = spawned;
33
+ pids.add(spawned);
34
+ options.onSpawn?.(spawned);
35
+ },
36
+ });
37
+ } finally {
38
+ if (pid !== undefined) pids.delete(pid);
39
+ }
40
+ };
41
+
42
+ /** Kill every process carrying `tag`; on Windows, tree-kill each recorded pid. */
43
+ export const killUpgradeTree = async (tag: string, pids: ReadonlySet<number>): Promise<void> => {
44
+ if (process.platform === 'win32') {
45
+ for (const pid of pids) await taskkillTree(pid);
46
+ return;
47
+ }
48
+ await killTagged(tag);
49
+ };
50
+
51
+ const STOP_SIGNALS = ['SIGINT', 'SIGTERM'] as const;
52
+
53
+ export interface StopInput {
54
+ readonly tag: string;
55
+ readonly pids: ReadonlySet<number>;
56
+ readonly kill?: (tag: string, pids: ReadonlySet<number>) => Promise<void>;
57
+ /** Synchronous: the lock is released before the process dies. */
58
+ readonly cleanup: () => void;
59
+ readonly reraise?: (signal: NodeJS.Signals) => void;
60
+ }
61
+
62
+ /**
63
+ * On SIGINT/SIGTERM: kill the tagged tree, clean up, then remove the listeners and re-raise the
64
+ * same signal so it meets its default action. The listeners stay until that is done and a repeat
65
+ * is ignored (`signal-shred.ts`' reason: a forwarded second Ctrl-C would otherwise kill mid-sweep).
66
+ * Returns the undo for the normal path.
67
+ */
68
+ export function stopChildrenOnSignal(input: StopInput): () => void {
69
+ const kill = input.kill ?? killUpgradeTree;
70
+ const reraise = input.reraise ?? ((signal) => process.kill(process.pid, signal));
71
+ let stopping = false;
72
+ const undo = (): void => {
73
+ for (const signal of STOP_SIGNALS) process.off(signal, handler);
74
+ };
75
+ function handler(signal: NodeJS.Signals): void {
76
+ if (stopping) return;
77
+ stopping = true;
78
+ void kill(input.tag, input.pids)
79
+ .catch(() => undefined)
80
+ .finally(() => {
81
+ try {
82
+ input.cleanup();
83
+ } finally {
84
+ undo();
85
+ reraise(signal);
86
+ }
87
+ });
88
+ }
89
+ for (const signal of STOP_SIGNALS) process.on(signal, handler);
90
+ return undo;
91
+ }