@ultimat3/cli 31.26.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 (206) hide show
  1. package/CLAUDE.md +47 -37
  2. package/README.md +19 -8
  3. package/package.json +29 -29
  4. package/src/app-manifest.ts +6 -1
  5. package/src/app-mcp.ts +17 -3
  6. package/src/cmd-cache-spec.ts +5 -2
  7. package/src/cmd-db-spec.ts +2 -3
  8. package/src/cmd-db.ts +0 -2
  9. package/src/cmd-deploy-verify-sample.ts +93 -0
  10. package/src/cmd-deploy-verify.ts +2 -41
  11. package/src/cmd-dev-spec.ts +15 -1
  12. package/src/cmd-dev.ts +31 -4
  13. package/src/cmd-doctor.ts +15 -4
  14. package/src/cmd-exercise-spec.ts +7 -1
  15. package/src/cmd-exercise.ts +22 -10
  16. package/src/cmd-generate.ts +2 -0
  17. package/src/cmd-jobs-spec.ts +3 -6
  18. package/src/cmd-jobs.ts +1 -7
  19. package/src/cmd-logs-spec.ts +2 -1
  20. package/src/cmd-logs.ts +9 -28
  21. package/src/cmd-planned.ts +11 -45
  22. package/src/cmd-profile-frames.ts +99 -0
  23. package/src/cmd-profile-spec.ts +24 -0
  24. package/src/cmd-profile.ts +164 -0
  25. package/src/cmd-repro-spec.ts +13 -1
  26. package/src/cmd-repro.ts +37 -5
  27. package/src/cmd-status-sample.ts +57 -0
  28. package/src/cmd-status-spec.ts +30 -0
  29. package/src/cmd-status.ts +108 -0
  30. package/src/cmd-token-spec.ts +5 -2
  31. package/src/cmd-token.ts +7 -3
  32. package/src/cmd-upgrade-codemods.ts +71 -0
  33. package/src/cmd-upgrade-spec.ts +19 -5
  34. package/src/cmd-upgrade.ts +91 -34
  35. package/src/codemods/agents-dev-mcp.ts +50 -0
  36. package/src/codemods/authenticator-session-refusal.ts +214 -0
  37. package/src/codemods/biome-no-default-export.ts +58 -0
  38. package/src/codemods/bunfig-island-coverage.ts +33 -0
  39. package/src/codemods/chart-dashboard.ts +73 -0
  40. package/src/codemods/ci-e2e-browser-stock.ts +75 -0
  41. package/src/codemods/ci-e2e-browser.ts +63 -0
  42. package/src/codemods/codemod.ts +58 -0
  43. package/src/codemods/define-error-leaf.ts +73 -0
  44. package/src/codemods/docs-ci-parts.ts +65 -0
  45. package/src/codemods/docs-gate-prose.ts +53 -0
  46. package/src/codemods/docs-island-rows.ts +31 -0
  47. package/src/codemods/docs-shipped-guards.ts +100 -0
  48. package/src/codemods/docs-test-services.ts +62 -0
  49. package/src/codemods/engine-diff.ts +104 -0
  50. package/src/codemods/engine-edits.ts +111 -0
  51. package/src/codemods/engine-fs.ts +95 -0
  52. package/src/codemods/engine.ts +191 -0
  53. package/src/codemods/format-edited-hook-3122.ts +28 -0
  54. package/src/codemods/format-edited-hook.ts +152 -0
  55. package/src/codemods/helm-alerts-objective.ts +105 -0
  56. package/src/codemods/helm-alerts-stock.ts +108 -0
  57. package/src/codemods/index.ts +56 -0
  58. package/src/codemods/metrics-probe-healthz.ts +47 -0
  59. package/src/codemods/pending.ts +36 -0
  60. package/src/codemods/repro-gitignore.ts +40 -0
  61. package/src/codemods/runtime-pin-lines.ts +109 -0
  62. package/src/codemods/runtime-pin.ts +116 -0
  63. package/src/codemods/solid-floor.ts +63 -0
  64. package/src/codemods/test-ports.ts +86 -0
  65. package/src/codemods/test-suites.ts +37 -0
  66. package/src/codemods/theme-toggle-mount-over.ts +70 -0
  67. package/src/codemods/vendored-guards.ts +186 -0
  68. package/src/codemods/verify-floor-skips.ts +88 -0
  69. package/src/codemods/verify-floor-steps.ts +90 -0
  70. package/src/coverage-island.ts +121 -0
  71. package/src/coverage-lcov.ts +49 -5
  72. package/src/coverage-remap.ts +146 -0
  73. package/src/db-replay-engine-prepared.ts +66 -0
  74. package/src/db-replay-engine-template.ts +156 -0
  75. package/src/db-replay-engine.ts +4 -0
  76. package/src/db-replay-scratch-reap.ts +54 -0
  77. package/src/deploy-verify-flags.ts +9 -2
  78. package/src/deploy-verify-grade.ts +10 -3
  79. package/src/dev-boot.ts +14 -1
  80. package/src/dev-dashboard-guard.ts +57 -10
  81. package/src/dev-host.ts +46 -0
  82. package/src/dev-tls-cache.ts +103 -0
  83. package/src/dev-tls-der.ts +69 -0
  84. package/src/dev-tls.ts +120 -0
  85. package/src/doctor-advisory-floors.ts +113 -0
  86. package/src/doctor-browser.ts +60 -0
  87. package/src/doctor-guards.ts +39 -86
  88. package/src/doctor-superseded.ts +67 -0
  89. package/src/error-codes-doctor.ts +12 -4
  90. package/src/error-codes-verify.ts +47 -0
  91. package/src/error-codes.ts +20 -23
  92. package/src/exercise-database.ts +47 -9
  93. package/src/exercise-push-device.ts +51 -0
  94. package/src/exercise-route-api.ts +74 -0
  95. package/src/exercise-routes.ts +14 -5
  96. package/src/exercise-services.ts +3 -1
  97. package/src/exercise-shard-flag.ts +47 -0
  98. package/src/fix-command.ts +2 -2
  99. package/src/generate-factories.ts +5 -11
  100. package/src/generate-feature-required.ts +9 -4
  101. package/src/generate-files.ts +26 -7
  102. package/src/generate-kinds.ts +5 -1
  103. package/src/guards-built-in-codes.ts +36 -0
  104. package/src/guards-built-in-refusal.ts +25 -0
  105. package/src/guards-built-in.ts +134 -0
  106. package/src/guards-materialize.ts +42 -0
  107. package/src/guards-paths.ts +37 -0
  108. package/src/guards-shipped-names.ts +38 -0
  109. package/src/guards-vendored.ts +73 -0
  110. package/src/guards.ts +105 -34
  111. package/src/index.ts +10 -0
  112. package/src/island-bundle-options.ts +48 -0
  113. package/src/island-bundle.ts +18 -46
  114. package/src/island-link.ts +5 -0
  115. package/src/island-outputs.ts +5 -0
  116. package/src/lint-findings.ts +3 -3
  117. package/src/mcp-errors-verify.ts +35 -0
  118. package/src/mcp-errors.ts +21 -20
  119. package/src/mcp-host-logs.ts +121 -0
  120. package/src/mcp-host.ts +12 -73
  121. package/src/measure-scope.ts +23 -3
  122. package/src/messages-floor.ts +19 -0
  123. package/src/messages-repro.ts +16 -2
  124. package/src/messages-status.ts +10 -0
  125. package/src/messages-upgrade.ts +15 -0
  126. package/src/messages.ts +22 -1
  127. package/src/registry.ts +4 -0
  128. package/src/repro-archive-collect.ts +161 -0
  129. package/src/repro-archive-write.ts +96 -0
  130. package/src/repro-archive.ts +161 -0
  131. package/src/repro-bundle.ts +8 -16
  132. package/src/repro-errors.ts +14 -2
  133. package/src/repro-framework.ts +53 -0
  134. package/src/repro-parse.ts +87 -0
  135. package/src/repro-redact.ts +218 -0
  136. package/src/repro-scrub.ts +257 -0
  137. package/src/role-start-types.ts +7 -0
  138. package/src/role-start.ts +4 -0
  139. package/src/serve-boot.ts +7 -1
  140. package/src/serve-env-tls.ts +57 -0
  141. package/src/solid-loader.ts +27 -10
  142. package/src/superseded-match.ts +87 -0
  143. package/src/superseded.ts +84 -0
  144. package/src/templates/bun-image.ts +48 -0
  145. package/src/templates/generate-export-rows.ts +136 -0
  146. package/src/templates/generate-import-rows.ts +186 -0
  147. package/src/templates/generate-rows-slice.ts +95 -0
  148. package/src/templates/github/ci.yml.ts +5 -1
  149. package/src/templates/guard-released-forms.ts +112 -0
  150. package/src/templates/guard-runtime-pin-test.ts +54 -0
  151. package/src/templates/guard-runtime-pin.ts +189 -0
  152. package/src/templates/scaffold-claude-agents.ts +6 -6
  153. package/src/templates/scaffold-claude-commands.ts +1 -1
  154. package/src/templates/scaffold-claude-hook.ts +18 -8
  155. package/src/templates/scaffold-claude.ts +2 -2
  156. package/src/templates/scaffold-db-package.ts +3 -0
  157. package/src/templates/scaffold-docs.ts +34 -30
  158. package/src/templates/scaffold-guards.ts +73 -39
  159. package/src/templates/scaffold-repo.ts +4 -8
  160. package/src/templates/scaffold-site.ts +4 -1
  161. package/src/templates/scaffold-suites.ts +72 -0
  162. package/src/templates/scaffold-test-services.ts +35 -10
  163. package/src/templates/scaffold-verify-floor.ts +53 -31
  164. package/src/templates/shapes/api.ts +4 -0
  165. package/src/templates/slice-foundation.ts +3 -3
  166. package/src/unthrown-codes.ts +3 -1
  167. package/src/upgrade-bun-floor.ts +4 -0
  168. package/src/upgrade-clean-tree.ts +54 -0
  169. package/src/upgrade-gate-codemods-install.ts +40 -0
  170. package/src/upgrade-gate-codemods.ts +151 -0
  171. package/src/upgrade-gate.ts +44 -7
  172. package/src/upgrade-guards-baseline.ts +43 -0
  173. package/src/upgrade-guards.ts +37 -2
  174. package/src/upgrade-lock.ts +118 -0
  175. package/src/upgrade-plan.ts +2 -1
  176. package/src/upgrade-report-codemods.ts +54 -0
  177. package/src/upgrade-report.ts +55 -27
  178. package/src/upgrade-signals.ts +91 -0
  179. package/src/upgrade-unfinished.ts +61 -0
  180. package/src/verify-coverage-run.ts +42 -11
  181. package/src/verify-e2e.ts +115 -4
  182. package/src/verify-floor.ts +27 -0
  183. package/src/verify-guard-baseline.ts +109 -0
  184. package/src/verify-live.ts +72 -0
  185. package/src/verify-merge-skips.ts +51 -0
  186. package/src/verify-merge.ts +36 -2
  187. package/src/verify-run.ts +48 -7
  188. package/src/verify-services.ts +287 -0
  189. package/src/verify-skip-reason.ts +53 -0
  190. package/src/verify-strict.ts +108 -0
  191. package/src/verify-test-command.ts +129 -0
  192. package/src/verify-tests.ts +39 -126
  193. package/types/babel-modules.d.ts +2 -0
  194. package/wiki/CLI-Reference.md +200 -27
  195. package/wiki/Caching-And-Invalidation.md +1 -1
  196. package/wiki/Entities-And-Migrations.md +1 -1
  197. package/wiki/Interface-Rules.md +17 -8
  198. package/wiki/Jobs-And-Workflows.md +3 -3
  199. package/wiki/Known-Gaps.md +5 -1
  200. package/wiki/MCP-And-AI.md +1 -1
  201. package/wiki/Observability.md +1 -0
  202. package/wiki/PWA-And-Offline.md +1 -1
  203. package/wiki/Project-Layout.md +4 -4
  204. package/wiki/Troubleshooting.md +3 -3
  205. package/wiki/Tutorial-05-Deploy-Free.md +2 -2
  206. package/wiki/Upgrading.md +8 -0
@@ -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';
18
- import type { WithheldGuard } from './upgrade-guards';
19
+ import { applyHopCodemods } from './upgrade-gate-codemods';
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';
@@ -101,6 +104,11 @@ export interface HopGuards {
101
104
  readonly installed: readonly string[];
102
105
  /** Not written, with how many findings each would have added (`upgrade-guards.ts`). */
103
106
  readonly withheld: readonly WithheldGuard[];
107
+ /**
108
+ * Also in `installed`: kept at its measured count, `guardBaseline` in `x.verify.json`. Absent
109
+ * when none, so `--json` of a hop that baselined nothing is unchanged.
110
+ */
111
+ readonly baselined?: readonly BaselinedGuard[];
104
112
  }
105
113
 
106
114
  /**
@@ -115,6 +123,10 @@ export interface HopExercise {
115
123
  }
116
124
 
117
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[];
118
130
  readonly manifest: { readonly ok: boolean; readonly findings: readonly GateFinding[] };
119
131
  /**
120
132
  * The installed `x doctor`'s `data.warnings[]`: never red on this major, the next one's red —
@@ -220,7 +232,14 @@ const readGuards = (doctor: DoctorDocument['data']): HopGuards => {
220
232
  };
221
233
  };
222
234
 
223
- 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';
224
243
 
225
244
  /**
226
245
  * The gate, in order, each stage told apart by `onStage` so a long gate is not a long silence.
@@ -233,10 +252,18 @@ export async function runHopGate(input: {
233
252
  readonly onStage: (stage: HopStage) => void;
234
253
  /** Present when the hop moved the Bun floor: what the coverage rebaseline's `why` says. */
235
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 };
236
257
  }): Promise<HopGate> {
237
258
  const { runner, root, onStage } = input;
238
259
  const installed = (args: readonly string[]): Promise<ExecResult> =>
239
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);
240
267
  onStage('manifest');
241
268
  const manifest = readManifest(await installed(['manifest', '--json']));
242
269
  onStage('doctor');
@@ -268,7 +295,17 @@ export async function runHopGate(input: {
268
295
  const exerciseFloor = await ratchetExerciseFloor(root, stamp);
269
296
  onStage('verify');
270
297
  const verify = readVerify(await installed(['verify', '--json']));
271
- 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
+ };
272
309
  }
273
310
 
274
311
  /** What a repository with no app can still be asked, in the order an author would run them. */
@@ -0,0 +1,43 @@
1
+ // A withheld guard's measured count, merged into `x.verify.json` as `guardBaseline` so the hop can
2
+ // keep it on disk at that count (`verify-guard-baseline.ts` judges it). The app's own keys are never
3
+ // touched: a baseline it already wrote for that guard, or a file that is not a JSON object, refuses.
4
+
5
+ // why: Bun exposes no path-join primitive; `x.verify.json` sits at the app root.
6
+ import { join } from 'node:path';
7
+ import { parseJson } from './upgrade-registry';
8
+ import { VERIFY_FLOOR_FILE } from './verify-floor';
9
+ import { GUARD_BASELINE_FIELD } from './verify-guard-baseline';
10
+
11
+ /** The floor's bytes before the write, or null when there was no file: what a rollback restores. */
12
+ export type FloorPrior = string | null;
13
+
14
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
15
+ typeof value === 'object' && value !== null && !Array.isArray(value);
16
+
17
+ /**
18
+ * Writes `guardBaseline[name] = findings`; the prior bytes, or undefined when it refused. No file
19
+ * is a floor requiring no step, so the one written changes nothing but the baseline.
20
+ */
21
+ export async function writeGuardBaseline(
22
+ root: string,
23
+ name: string,
24
+ findings: number,
25
+ ): Promise<{ readonly prior: FloorPrior } | undefined> {
26
+ const file = Bun.file(join(root, VERIFY_FLOOR_FILE));
27
+ const prior = (await file.exists()) ? await file.text() : null;
28
+ const payload = prior === null ? { steps: [] } : parseJson(prior);
29
+ if (!isRecord(payload)) return undefined;
30
+ const current = payload[GUARD_BASELINE_FIELD];
31
+ if (current !== undefined && !isRecord(current)) return undefined;
32
+ if (current !== undefined && Object.hasOwn(current, name)) return undefined;
33
+ const next = { ...payload, [GUARD_BASELINE_FIELD]: { ...(current ?? {}), [name]: findings } };
34
+ await Bun.write(file, `${JSON.stringify(next, null, 2)}\n`);
35
+ return { prior };
36
+ }
37
+
38
+ /** Puts the floor back as it was: rewritten, or deleted when the write created it. */
39
+ export async function restoreFloor(root: string, prior: FloorPrior): Promise<void> {
40
+ const file = Bun.file(join(root, VERIFY_FLOOR_FILE));
41
+ if (prior !== null) await Bun.write(file, prior);
42
+ else if (await file.exists()) await file.delete();
43
+ }
@@ -9,6 +9,7 @@ import { MANIFEST_FILENAME } from '@ultimat3/manifest';
9
9
  import { t } from '@ultimat3/schema';
10
10
  import type { ExecResult } from './exec';
11
11
  import { documentIn } from './upgrade-document';
12
+ import { restoreFloor, writeGuardBaseline } from './upgrade-guards-baseline';
12
13
 
13
14
  const GENERATED = t.object({
14
15
  data: t.optional(t.object({ files: t.optional(t.array(t.string)) })),
@@ -28,9 +29,20 @@ export interface WithheldGuard {
28
29
  readonly findings: number | null;
29
30
  }
30
31
 
32
+ /** A guard the tree breaks, installed anyway at its measured count (`guardBaseline`). */
33
+ export interface BaselinedGuard {
34
+ readonly name: string;
35
+ readonly findings: number;
36
+ }
37
+
31
38
  export interface GuardInstall {
32
39
  readonly installed: readonly string[];
33
40
  readonly withheld: readonly WithheldGuard[];
41
+ /**
42
+ * Also in `installed`: kept because `x.verify.json` now holds it at this many findings. Absent
43
+ * when none, so a hop that baselined nothing reports exactly what it always did.
44
+ */
45
+ readonly baselined?: readonly BaselinedGuard[];
34
46
  }
35
47
 
36
48
  /** Runs the installed CLI with these arguments in the app root. */
@@ -122,7 +134,9 @@ export async function installMissingGuards(input: {
122
134
  findings: null,
123
135
  });
124
136
  const base = await boundariesCount(cli);
125
- if (base === undefined) return { installed: [], withheld: missing.map(unmeasured) };
137
+ if (base === undefined) {
138
+ return { installed: [], withheld: missing.map(unmeasured) };
139
+ }
126
140
 
127
141
  const written = new Map<string, Generated>();
128
142
  const withheld: WithheldGuard[] = [];
@@ -140,6 +154,7 @@ export async function installMissingGuards(input: {
140
154
  // Newest first, so each artifact ends at the bytes it held before the first run.
141
155
  for (const run of [...written.values()].reverse()) await rollback(root, run);
142
156
  const installed: string[] = [];
157
+ const baselined: BaselinedGuard[] = [];
143
158
  let held = base;
144
159
  for (const guard of missing.filter(({ name }) => written.has(name))) {
145
160
  const run = await generate(cli, root, guard.name);
@@ -149,10 +164,30 @@ export async function installMissingGuards(input: {
149
164
  held = count;
150
165
  continue;
151
166
  }
167
+ // Measured and over: held at its own count, kept only if this CLI's `boundaries` then finds
168
+ // no more than before — a release that ignores `guardBaseline` leaves it withheld, as it was.
169
+ if (run !== undefined && count !== undefined) {
170
+ const findings = count - held;
171
+ const floor = await writeGuardBaseline(root, guard.name, findings);
172
+ if (floor !== undefined) {
173
+ const recount = await boundariesCount(cli);
174
+ if (recount !== undefined && recount <= held) {
175
+ installed.push(guard.name);
176
+ baselined.push({ name: guard.name, findings });
177
+ held = recount;
178
+ continue;
179
+ }
180
+ await restoreFloor(root, floor.prior);
181
+ }
182
+ }
152
183
  await rollback(root, run);
153
184
  withheld.push({ ...guard, findings: count === undefined ? null : count - held });
154
185
  }
155
- return { installed, withheld: sortByName(withheld) };
186
+ return {
187
+ installed,
188
+ withheld: sortByName(withheld),
189
+ ...(baselined.length === 0 ? {} : { baselined }),
190
+ };
156
191
  }
157
192
 
158
193
  const sortByName = (list: readonly WithheldGuard[]): readonly WithheldGuard[] =>
@@ -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,7 +107,12 @@ 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 })),
113
+ ...(gate?.guards.baselined ?? []).map((guard) =>
114
+ msg('cli.upgrade.guardBaselined', { name: guard.name, count: guard.findings }),
115
+ ),
92
116
  ...(gate?.guards.withheld ?? []).map((guard) =>
93
117
  guard.findings === null
94
118
  ? msg('cli.upgrade.guardUnmeasured', { fix: guard.add })
@@ -137,23 +161,25 @@ export const humanLines = (input: {
137
161
  const asJson = (value: unknown): JsonValue => value as JsonValue;
138
162
 
139
163
  /** The one shape every outcome reports: `--json` and the terminal project this and nothing else. */
140
- export const report = (input: {
141
- readonly hop: UpgradeHop;
142
- readonly done: boolean;
143
- readonly dryRun: boolean;
144
- readonly pins: readonly UpgradePin[];
145
- readonly bunFrom: string | null;
146
- readonly bunTo: string | null;
147
- readonly writes: PlannedWrites;
148
- readonly app: boolean;
149
- readonly gate: HopGate | undefined;
150
- readonly scripts: readonly RepoScript[];
151
- readonly then: string;
152
- /** What the hop does to `AGENTS.md` (`upgrade-agents-link.ts`); absent when no hop is planned. */
153
- readonly agentsMd?: AgentsLinkState;
154
- /** `typescript-floor.ts`'s lags — reported on every outcome, an at-target app's included. */
155
- readonly typescript: readonly TypescriptLag[];
156
- }): 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 => {
157
183
  const { hop, done, dryRun, pins, bunFrom, bunTo, writes, app, gate, scripts, then } = input;
158
184
  return asJson({
159
185
  from: hop.from,
@@ -172,6 +198,8 @@ export const report = (input: {
172
198
  bun: { from: bunFrom, to: bunTo, edited: writes.edited, manual: writes.manual },
173
199
  typescript: input.typescript,
174
200
  agentsMd: input.agentsMd ?? null,
201
+ codemods: input.codemods ?? gate?.codemods ?? null,
202
+ superseded: input.superseded ?? gate?.superseded ?? [],
175
203
  guards: gate?.guards ?? null,
176
204
  coverage: gate?.coverage ?? null,
177
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
+ }