@ultimat3/cli 30.9.0 → 31.1.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 (215) hide show
  1. package/CLAUDE.md +80 -64
  2. package/README.md +4 -1
  3. package/package.json +30 -29
  4. package/src/admin-registration.ts +1 -1
  5. package/src/affected-base.ts +51 -0
  6. package/src/affected.ts +34 -11
  7. package/src/app-boundaries.ts +88 -9
  8. package/src/app-load-async.ts +133 -0
  9. package/src/app-load-batch.ts +203 -0
  10. package/src/app-load-prebuilt.ts +147 -0
  11. package/src/app-load-register.ts +175 -0
  12. package/src/app-load.ts +143 -175
  13. package/src/app-loader-imports.ts +31 -0
  14. package/src/app-root.ts +13 -0
  15. package/src/app-runtime.ts +5 -1
  16. package/src/boundary-findings.ts +12 -0
  17. package/src/browser-launcher-port.ts +3 -7
  18. package/src/browser-launcher.ts +1 -1
  19. package/src/budgets-scan.ts +8 -0
  20. package/src/budgets.ts +10 -1
  21. package/src/build-registry-background.ts +59 -0
  22. package/src/build-registry.ts +207 -0
  23. package/src/cdp-shot-clock.ts +3 -11
  24. package/src/cdp-shot-driver.ts +3 -2
  25. package/src/cdp-shot-element.ts +3 -2
  26. package/src/cdp-shot-page.ts +2 -2
  27. package/src/cdp-shot-watch.ts +4 -3
  28. package/src/ci-log.ts +76 -13
  29. package/src/cmd-affected-spec.ts +7 -3
  30. package/src/cmd-affected.ts +91 -77
  31. package/src/cmd-auth.ts +3 -3
  32. package/src/cmd-ci.ts +6 -3
  33. package/src/cmd-db-recount.ts +15 -0
  34. package/src/cmd-drill.ts +10 -6
  35. package/src/cmd-exercise.ts +2 -1
  36. package/src/cmd-generate-spec.ts +6 -0
  37. package/src/cmd-generate.ts +22 -4
  38. package/src/cmd-mail.ts +1 -1
  39. package/src/cmd-pr-spec.ts +1 -1
  40. package/src/cmd-pr.ts +72 -1
  41. package/src/cmd-routes.ts +2 -2
  42. package/src/cmd-secrets-spec.ts +4 -1
  43. package/src/cmd-shot.ts +14 -262
  44. package/src/cmd-test-spec.ts +2 -2
  45. package/src/cmd-verify-spec.ts +21 -1
  46. package/src/cmd-verify.ts +16 -4
  47. package/src/coverage-source.ts +4 -1
  48. package/src/db-diagnostics.ts +8 -1
  49. package/src/dev-boot.ts +29 -15
  50. package/src/dev-dashboard-invalidations.ts +43 -0
  51. package/src/dev-dashboard.ts +13 -16
  52. package/src/dev-n-plus-one.ts +7 -3
  53. package/src/dev-rebuild.ts +2 -1
  54. package/src/dev-route-table.ts +1 -1
  55. package/src/dev-traces.ts +16 -15
  56. package/src/document-options.ts +12 -1
  57. package/src/drift-store.ts +55 -0
  58. package/src/error-catalog.ts +8 -3
  59. package/src/error-codes-boundary.ts +32 -0
  60. package/src/error-codes-package.ts +38 -0
  61. package/src/error-codes.ts +28 -40
  62. package/src/errors.ts +17 -7
  63. package/src/exercise-database.ts +13 -1
  64. package/src/exercise-findings.ts +36 -18
  65. package/src/exercise-services.ts +84 -0
  66. package/src/exercise-subject.ts +38 -13
  67. package/src/failure-capture-boot.ts +9 -5
  68. package/src/framework-schema.ts +5 -5
  69. package/src/generate-exercise.ts +1 -1
  70. package/src/generate-files.ts +27 -7
  71. package/src/generate-kinds.ts +5 -0
  72. package/src/generate-refresh.ts +53 -0
  73. package/src/generate-workspace.ts +169 -0
  74. package/src/generate-write.ts +8 -2
  75. package/src/hold.ts +19 -8
  76. package/src/image-prepare.ts +6 -2
  77. package/src/index.ts +5 -20
  78. package/src/island-bundle.ts +7 -3
  79. package/src/island-capture.ts +2 -2
  80. package/src/island-harness.ts +1 -1
  81. package/src/job-registration.ts +43 -6
  82. package/src/jobs-driver.ts +4 -5
  83. package/src/mcp-errors.ts +20 -4
  84. package/src/mcp-host.ts +5 -1
  85. package/src/mcp-ui-interact.ts +3 -0
  86. package/src/messages-gate.ts +10 -0
  87. package/src/new-shapes-generate.ts +1 -1
  88. package/src/otlp-export.ts +94 -29
  89. package/src/output.ts +24 -10
  90. package/src/page-sync.ts +3 -1
  91. package/src/pr-activity.ts +150 -0
  92. package/src/pr-bots.ts +109 -0
  93. package/src/pr-threads.ts +7 -2
  94. package/src/role-load.ts +17 -11
  95. package/src/role-start.ts +5 -4
  96. package/src/role-sync.ts +7 -8
  97. package/src/route-islands-preload.ts +46 -0
  98. package/src/route-islands.ts +6 -2
  99. package/src/runtime-admin.ts +5 -1
  100. package/src/runtime-bindings.ts +25 -19
  101. package/src/runtime-boot-ports.ts +66 -0
  102. package/src/runtime-bus.ts +29 -5
  103. package/src/runtime-cache-bus.ts +53 -0
  104. package/src/runtime-cache.ts +43 -13
  105. package/src/runtime-isr-outcome.ts +5 -4
  106. package/src/runtime-jobs.ts +2 -2
  107. package/src/runtime-keys.ts +37 -0
  108. package/src/runtime-overrides.ts +148 -42
  109. package/src/runtime-port-bindings-queue.ts +36 -0
  110. package/src/runtime-port-bindings.ts +117 -0
  111. package/src/runtime-ports.ts +164 -0
  112. package/src/runtime-purge.ts +41 -28
  113. package/src/runtime-push.ts +7 -3
  114. package/src/runtime-queue.ts +70 -55
  115. package/src/runtime-realtime.ts +5 -5
  116. package/src/runtime-render-document.ts +4 -1
  117. package/src/runtime-services.ts +110 -158
  118. package/src/runtime-storage-boot.ts +111 -0
  119. package/src/runtime-storage-upload.ts +9 -7
  120. package/src/runtime-storage.ts +7 -1
  121. package/src/serve-boot.ts +8 -4
  122. package/src/serve-entry.ts +3 -0
  123. package/src/serve-env.ts +47 -14
  124. package/src/serve-prebuilt-paths.ts +3 -0
  125. package/src/serve-prebuilt.ts +15 -4
  126. package/src/serve.ts +2 -2
  127. package/src/shot-gpu.ts +61 -0
  128. package/src/shot-route.ts +95 -0
  129. package/src/shot-run.ts +189 -0
  130. package/src/shot-verdict.ts +5 -0
  131. package/src/static-cards.ts +3 -2
  132. package/src/static-report.ts +2 -2
  133. package/src/style-bundle.ts +1 -1
  134. package/src/sync-authenticator.ts +17 -18
  135. package/src/templates/action-tests.ts +4 -4
  136. package/src/templates/backfill.ts +5 -8
  137. package/src/templates/entity.ts +3 -0
  138. package/src/templates/github/ci.yml.ts +3 -1
  139. package/src/templates/github/dependabot.yml.ts +73 -0
  140. package/src/templates/job.ts +13 -22
  141. package/src/templates/naming.ts +20 -1
  142. package/src/templates/pinned/docker-compose.yml +1 -1
  143. package/src/templates/query.ts +7 -8
  144. package/src/templates/route.ts +5 -3
  145. package/src/templates/scaffold-api.ts +1 -1
  146. package/src/templates/scaffold-auth.ts +5 -3
  147. package/src/templates/scaffold-claude-commands.ts +6 -3
  148. package/src/templates/scaffold-claude.ts +4 -4
  149. package/src/templates/scaffold-container-compose.ts +2 -4
  150. package/src/templates/scaffold-domain-package.ts +1 -1
  151. package/src/templates/scaffold-entries.ts +6 -1
  152. package/src/templates/scaffold-helm-fences.ts +3 -2
  153. package/src/templates/scaffold-helm.ts +35 -6
  154. package/src/templates/scaffold-repo.ts +47 -135
  155. package/src/templates/scaffold-runtime-ports.ts +62 -0
  156. package/src/templates/scaffold-verify-floor.ts +97 -0
  157. package/src/templates/shapes/overlay.ts +1 -1
  158. package/src/templates/sign-in-oidc.ts +5 -3
  159. package/src/templates/sign-in-shared.ts +28 -10
  160. package/src/templates/workspace.ts +75 -0
  161. package/src/test-ignores.ts +5 -2
  162. package/src/test-select.ts +4 -1
  163. package/src/tsconfig-aliases.ts +85 -0
  164. package/src/upgrade-gate.ts +30 -5
  165. package/src/upgrade-report.ts +7 -1
  166. package/src/verify-changed-facts.ts +53 -0
  167. package/src/verify-changed-scope.ts +162 -0
  168. package/src/verify-changed.ts +174 -0
  169. package/src/verify-checks.ts +33 -19
  170. package/src/verify-drift-owner.ts +30 -0
  171. package/src/verify-e2e.ts +2 -1
  172. package/src/verify-factories.ts +86 -0
  173. package/src/verify-run.ts +13 -11
  174. package/src/verify-step.ts +13 -0
  175. package/src/verify-tests.ts +58 -6
  176. package/src/workspace-external-deps.ts +164 -0
  177. package/src/write-line.ts +21 -6
  178. package/wiki/Actions.md +2 -2
  179. package/wiki/Adapters.md +400 -0
  180. package/wiki/Admin-Dashboard.md +1 -1
  181. package/wiki/Agents.md +9 -9
  182. package/wiki/Auth.md +78 -2
  183. package/wiki/Building-Your-Own-Base.md +1 -1
  184. package/wiki/CLI-Reference.md +45 -14
  185. package/wiki/Caching-And-Invalidation.md +17 -5
  186. package/wiki/Compared.md +8 -2
  187. package/wiki/Configuration.md +14 -14
  188. package/wiki/Deployment.md +28 -1
  189. package/wiki/Entities-And-Migrations.md +47 -1
  190. package/wiki/FAQ.md +8 -2
  191. package/wiki/Feature-Flags.md +1 -1
  192. package/wiki/Home.md +3 -2
  193. package/wiki/Jobs-And-Workflows.md +107 -6
  194. package/wiki/Known-Gaps.md +4 -3
  195. package/wiki/MCP-And-AI.md +18 -4
  196. package/wiki/Mail.md +14 -5
  197. package/wiki/Migrations-And-Backfills.md +29 -4
  198. package/wiki/Money.md +2 -0
  199. package/wiki/N-Plus-One-Detection.md +24 -22
  200. package/wiki/Notify.md +28 -4
  201. package/wiki/Observability.md +121 -15
  202. package/wiki/Queries-And-Live-Queries.md +2 -2
  203. package/wiki/Realtime.md +9 -4
  204. package/wiki/Routes-And-Render-Modes.md +5 -0
  205. package/wiki/Scraping.md +57 -11
  206. package/wiki/Shapes.md +2 -2
  207. package/wiki/Stability.md +7 -5
  208. package/wiki/Storage-And-Uploads.md +56 -4
  209. package/wiki/Testing.md +65 -52
  210. package/wiki/Troubleshooting.md +1 -1
  211. package/wiki/Tutorial-01-First-App.md +1 -1
  212. package/wiki/Tutorial-04-Jobs-And-Realtime.md +1 -1
  213. package/wiki/Tutorial-05-Deploy-Free.md +1 -1
  214. package/wiki/Tutorial-06-Growing-Up.md +8 -8
  215. package/wiki/Upgrading.md +136 -5
package/src/errors.ts CHANGED
@@ -130,9 +130,15 @@ export class NotInAppError extends UltimateError {
130
130
  below?: readonly string[];
131
131
  /** `from` already depends on the framework, so `x new` would be a second project, not a fix. */
132
132
  adopter?: boolean;
133
+ /** `from`'s `package.json` has an `x` script (the framework repo): `bun run x -- … --cwd`. */
134
+ xScript?: boolean;
133
135
  }) {
134
136
  const [first] = input.below ?? [];
135
137
  const found = (input.below ?? []).join(', ');
138
+ // Word by word: `'vapid create'` pasted as one quoted token is a command `x` does not have.
139
+ // Assembled from arrays of screened words, so no value is spliced where a shell runs it.
140
+ const argv = input.command.split(' ').map(quoteArg);
141
+ const words = argv.join(' ');
136
142
  super({
137
143
  code: 'X_NOT_IN_APP',
138
144
  cause:
@@ -143,9 +149,13 @@ export class NotInAppError extends UltimateError {
143
149
  : `"x ${input.command}" must run inside an Ultimate app; no app.config.ts at or above ${input.from}`,
144
150
  fix:
145
151
  first !== undefined
146
- ? `cd ${quoteArg(first)} && x ${quoteArg(input.command)} --json`
152
+ ? // Never a bare `x` (on no PATH outside an app), nor `bunx x`: with no `node_modules` it
153
+ // fetches the unrelated npm package `x`. The framework's own package name always resolves.
154
+ input.xScript === true
155
+ ? ['bun', 'run', 'x', '--', ...argv, '--cwd', quoteArg(first), '--json'].join(' ')
156
+ : ['cd', quoteArg(first), '&&', 'bunx', '@ultimat3/cli', ...argv, '--json'].join(' ')
147
157
  : input.adopter === true
148
- ? `x new scratch-app --dry-run --json # its file list carries app.config.ts; write one at the app root, then re-run: x ${quoteArg(input.command)} --json`
158
+ ? `x new scratch-app --dry-run --json # its file list carries app.config.ts; write one at the app root, then re-run: x ${words} --json`
149
159
  : 'bunx create-ultimate myapp && cd myapp',
150
160
  });
151
161
  }
@@ -195,7 +205,7 @@ export class ScaffoldPathEscapeError extends UltimateError {
195
205
  cause: `generated path "${input.path}" resolves outside ${input.dir}`,
196
206
  fix:
197
207
  input.fix ??
198
- `make the path relative to the app root with no ".." segment, then re-run: bun test packages/cli/src/scaffold-typecheck.contract.test.ts`,
208
+ `make the path relative to the app root with no ".." segment, then re-run: bun test ./packages/cli/src/scaffold-typecheck.contract.test.ts`,
199
209
  });
200
210
  }
201
211
  }
@@ -211,7 +221,7 @@ export class GenerateJsonInvalidError extends UltimateError {
211
221
  super({
212
222
  code: 'X_GENERATE_JSON_INVALID',
213
223
  cause: `${input.path} is declared merge: 'json' but the generator's own contents for it do not parse as a JSON object`,
214
- fix: `fix the template that emits ${input.path}, then re-run: bun test packages/cli/src/cmd-generate.test.ts`,
224
+ fix: `fix the template that emits ${input.path}, then re-run: bun test ./packages/cli/src/cmd-generate.test.ts`,
215
225
  });
216
226
  }
217
227
  }
@@ -407,8 +417,8 @@ export class RoleUnknownError extends UltimateError {
407
417
  * The enqueue side and the claim side are looking at two different queues.
408
418
  *
409
419
  * `startServices` builds the drivers and captures them; `loadApp` imports the app's modules after
410
- * it, and a module calling `setJobDriver()` at import time moves the ambient slot without touching
411
- * the captured object. The worker then claims from what was captured while every
420
+ * it, and a module calling `installJobDriver()` (`@ultimat3/jobs/adapter`, since v31 the only
421
+ * installer) at import time moves the ambient slot without touching the captured object. The worker then claims from what was captured while every
412
422
  * `handle.enqueue()` publishes to what is ambient — jobs that are accepted, acknowledged, visible
413
423
  * in `/_x` and never run. Refused at boot, because the alternative is a deployment that only ever
414
424
  * looks healthy.
@@ -420,7 +430,7 @@ export class RuntimeDriverSplitError extends UltimateError {
420
430
  // Both names are printed even when they are the same string — two `memory` drivers are two
421
431
  // queues, and "they match" is exactly the reading that makes this bug invisible.
422
432
  cause: `an app module installed a ${input.driver} driver (ambient: "${input.ambient}") that is not the object this boot captured ("${input.captured}"), so enqueues and claims would use different queues`,
423
- fix: `pass the driver to the boot instead of installing it from an app module: runRole({ root, env, runtime: { ${input.driver}: yourDriver } })`,
433
+ fix: `export const runtime = { ${quoteArg(input.driver)}: yourDriver } satisfies RuntimeOverrides; // in apps/web/runtime.ts — and delete the module's own install call`,
424
434
  });
425
435
  }
426
436
  }
@@ -6,14 +6,16 @@
6
6
  import type { Environment } from '@ultimat3/core';
7
7
  import { ENVIRONMENT_KEY, resolveEnvironment, UltimateError } from '@ultimat3/core';
8
8
  import type { DbClient } from '@ultimat3/db';
9
- import { migrate, raw, setDbClient } from '@ultimat3/db';
9
+ import { dbExecutor, migrate, raw, setDbClient } from '@ultimat3/db';
10
10
  import {
11
11
  captureDeterminism,
12
12
  installDeterminism,
13
13
  restoreCapturedDeterminism,
14
14
  testSealKeyEnv,
15
15
  } from '@ultimat3/testing';
16
+ import { loadAppConfig } from './app-config-load';
16
17
  import { chooseReplayEngine, withScratchDatabase } from './db-replay-engine';
18
+ import { installExerciseServices } from './exercise-services';
17
19
  import { applyFrameworkSchema } from './framework-schema';
18
20
  import { readMigrations } from './migrations';
19
21
  import { resolveServices } from './runtime-bindings';
@@ -104,9 +106,19 @@ export async function withExerciseDatabase<T>(
104
106
  await applyFrameworkSchema((statement) => client.execute(raw(statement)));
105
107
  await migrate({ migrations, client });
106
108
  setDbClient(client);
109
+ // What a server's boot installs beside its database, over this one: a primitive that reads a
110
+ // disk, a shared rate limit or the push runtime runs, rather than needing `{ off }`.
111
+ // Inside the `try`: a config or a key pair refused here still hands the client back.
112
+ let release: () => void = () => undefined;
107
113
  try {
114
+ release = await installExerciseServices({
115
+ config: await loadAppConfig(root),
116
+ env,
117
+ executor: dbExecutor(() => client),
118
+ });
108
119
  return await work(client);
109
120
  } finally {
121
+ release();
110
122
  setDbClient(undefined);
111
123
  }
112
124
  });
@@ -59,26 +59,41 @@ const defectOf = (record: ExerciseRecord): string => {
59
59
  return ` — cause: ${renderCauseValue(defect.cause)}${fields}`;
60
60
  };
61
61
 
62
+ /** Whether the app has an `apps/web/exercise.ts` yet: what an unreached finding's fix pastes into. */
63
+ export type ExerciseFileState = 'present' | 'absent';
64
+
65
+ const PASTE_NOTE =
66
+ "an inline .contract({ exercise: {...} }) in a test is not read here: move it, then pass .contract({ exercise }); or give the entry { off: '<why>' }";
67
+
62
68
  /**
63
69
  * `X_CONTRACT_EXERCISE_UNREACHED`, `@ultimat3/action`'s code for the same silence one level up: a
64
- * primitive no run got to as an allowed actor. The fix is the override the pass printed, or the
65
- * input shape to fill when it printed none — then the one-primitive rerun that proves it.
70
+ * primitive no run got to as an allowed actor. The fix is pasted from its first character: into a
71
+ * file that exists, the bare entry (thirty findings are thirty entries inside the ONE export, never
72
+ * thirty `defineExercise` calls to unwrap); with no file yet, the whole file to create. Then the
73
+ * one-primitive rerun that proves it.
66
74
  */
67
- const unreachedFinding = (record: ExerciseRecord): Finding => {
68
- const name = renderFixShellArg(record.name, '<name>');
69
- const override = record.override ?? `${record.name}: { input: { /* a value it accepts */ } }`;
70
- const stopped = record.code === undefined ? '' : ` — stopped on ${record.code}`;
71
- const why = record.reason === undefined ? '' : ` (${renderCauseValue(record.reason)})`;
72
- return {
73
- code: 'X_CONTRACT_EXERCISE_UNREACHED',
74
- cause: `${record.kind} ${renderCauseValue(record.name)} never reached its handler as an allowed actor in the exercise pass${stopped}${why}${defectOf(record)}`,
75
- fix:
76
- record.fix ??
77
- `defineExercise({ ${override} }) # paste the entry into ${EXERCISE_FILE} (an inline .contract({ exercise: {...} }) in a test is not read here: move it, then pass .contract({ exercise })), or { off: '<why>' }; then: x exercise ${name} --json`,
78
- docs: ERROR_DOCS_URL,
79
- at: EXERCISE_FILE,
75
+ const unreachedFinding =
76
+ (file: ExerciseFileState) =>
77
+ (record: ExerciseRecord): Finding => {
78
+ const name = renderFixShellArg(record.name, '<name>');
79
+ const entry = (
80
+ record.override ?? `${record.name}: { input: { /* a value it accepts */ } }`
81
+ ).replace(/[\s,]+$/, '');
82
+ const stopped = record.code === undefined ? '' : ` — stopped on ${record.code}`;
83
+ const why = record.reason === undefined ? '' : ` (${renderCauseValue(record.reason)})`;
84
+ const rerun = `then: x exercise ${name} --json`;
85
+ const paste =
86
+ file === 'present'
87
+ ? `${entry}, # paste inside export const exercise = defineExercise({ … }) in ${EXERCISE_FILE} (${PASTE_NOTE}); ${rerun}`
88
+ : `import { defineExercise } from '@ultimat3/testing'; export const exercise = defineExercise({ ${entry} }); # create ${EXERCISE_FILE} with this (${PASTE_NOTE}); ${rerun}`;
89
+ return {
90
+ code: 'X_CONTRACT_EXERCISE_UNREACHED',
91
+ cause: `${record.kind} ${renderCauseValue(record.name)} never reached its handler as an allowed actor in the exercise pass${stopped}${why}${defectOf(record)}`,
92
+ fix: record.fix ?? paste,
93
+ docs: ERROR_DOCS_URL,
94
+ at: EXERCISE_FILE,
95
+ };
80
96
  };
81
- };
82
97
 
83
98
  type CrashFinding = Extract<
84
99
  NonNullable<ExerciseRecord['crash']>,
@@ -133,8 +148,11 @@ export const crashFindingLines = (records: readonly ExerciseRecord[]): readonly
133
148
  * A's row; then the crash proof's diverged jobs. `unproven`, either proof's, is reported on the
134
149
  * record and never red — the pass could not ask, which is not an answer.
135
150
  */
136
- export const exerciseFindings = (records: readonly ExerciseRecord[]): readonly Finding[] => [
137
- ...records.filter((one) => one.outcome === 'unreached').map(unreachedFinding),
151
+ export const exerciseFindings = (
152
+ records: readonly ExerciseRecord[],
153
+ file: ExerciseFileState = 'present',
154
+ ): readonly Finding[] => [
155
+ ...records.filter((one) => one.outcome === 'unreached').map(unreachedFinding(file)),
138
156
  ...tenantProofFindings(records).map((one) => ({ ...one, docs: ERROR_DOCS_URL })),
139
157
  ...records.flatMap(crashFindings),
140
158
  // The plan and scale sweeps: a statement no index serves, a shape that grows with the rows.
@@ -0,0 +1,84 @@
1
+ // The runtime services a server's boot installs (`runtime-services.ts`) that `x exercise` stands in
2
+ // for: a storage disk, a fleet-wide rate-limit store and the Web Push runtime, over the pass's
3
+ // scratch database. Without them every primitive reading one stopped on a boot-only refusal and
4
+ // the app had to declare `{ off }` for it — the pass's job, not the app's.
5
+
6
+ import type { AppConfig, PgExecutor } from '@ultimat3/core';
7
+ import { ENVIRONMENT_KEY } from '@ultimat3/core';
8
+ import { postgresRateLimitStore } from '@ultimat3/http';
9
+ import { installRateLimitStore } from '@ultimat3/http/adapter';
10
+ import {
11
+ definedStorage,
12
+ defineStorage,
13
+ memoryStorageDriver,
14
+ resetStorage,
15
+ } from '@ultimat3/storage';
16
+ import type { Env } from './runtime-bindings';
17
+ import { selectWebPush } from './runtime-push';
18
+
19
+ export interface ExerciseServiceInputs {
20
+ /** The app's one loaded config — `undefined` for an app with no `app.config.ts`. */
21
+ readonly config: AppConfig | undefined;
22
+ readonly env: Env;
23
+ /** The scratch database the pass seeds: the boot's stores live there, as on a server. */
24
+ readonly executor: PgExecutor;
25
+ }
26
+
27
+ /**
28
+ * The disk an embedded boot names (`startStorage`'s `local`), held in memory: the pass's objects
29
+ * die with it, exactly as its rows die with the scratch database. Only when the app installed none
30
+ * — an app that defined its own storage keeps it, and gets it back untouched.
31
+ */
32
+ function installStorage(): () => void {
33
+ if (definedStorage() !== undefined) return () => undefined;
34
+ const installed = defineStorage({ disks: { local: memoryStorageDriver() }, default: 'local' });
35
+ return () => {
36
+ if (definedStorage() === installed) resetStorage();
37
+ };
38
+ }
39
+
40
+ /**
41
+ * A push service that accepts every message, as the memory mail driver accepts every mail: the pass
42
+ * seals the network, and a notifier fanning out to a seeded device must reach its handler's end,
43
+ * not a 5xx from a send nobody could receive.
44
+ */
45
+ const capturedPush: typeof fetch = Object.assign(
46
+ async (): Promise<Response> => new Response(null, { status: 201 }),
47
+ { preconnect: fetch.preconnect },
48
+ );
49
+
50
+ async function installPush(inputs: ExerciseServiceInputs): Promise<() => void> {
51
+ // As `test`, whatever the caller's env names: the pass always runs as one (`exerciseEnvironment`),
52
+ // so an app with no sealed pair signs with the development pair, as its `bun test` does.
53
+ const env = { ...inputs.env, [ENVIRONMENT_KEY]: 'test' };
54
+ const selection = await selectWebPush(inputs.config, env);
55
+ if (selection === undefined) return () => undefined;
56
+ const { installWebPush, postgresPushSubscriptionStore } = await import('@ultimat3/pwa');
57
+ return installWebPush({
58
+ store: postgresPushSubscriptionStore({ executor: inputs.executor }),
59
+ keys: selection.resolved.keys,
60
+ subject: selection.subject,
61
+ pushHosts: selection.pushHosts,
62
+ fetch: capturedPush,
63
+ });
64
+ }
65
+
66
+ /** Installs every stand-in; answers the release, newest first. Installing sends no statement. */
67
+ export async function installExerciseServices(inputs: ExerciseServiceInputs): Promise<() => void> {
68
+ const released: (() => void)[] = [];
69
+ const undo = (): void => {
70
+ for (const release of released.toReversed()) release();
71
+ };
72
+ try {
73
+ released.push(installStorage());
74
+ // `scope: 'shared'`, as the boot's: a `rateLimit: { scope: 'shared' }` declaration is judged
75
+ // against the installed store, and one process' memory refused it with X_RATE_LIMIT_NOT_SHARED.
76
+ released.push(installRateLimitStore(postgresRateLimitStore({ executor: inputs.executor })));
77
+ // Last, and the one that can refuse (a half VAPID pair): what is already in is undone first.
78
+ released.push(await installPush(inputs));
79
+ } catch (error) {
80
+ undo();
81
+ throw error;
82
+ }
83
+ return undo;
84
+ }
@@ -1,14 +1,15 @@
1
1
  // The subject proof under the `exercise` step. Static: every `defineSubject()` planned against
2
- // every registered entity — a table keyed to the subject with no treatment is
3
- // `X_SUBJECT_TABLE_UNDECLARED` naming it, so "you forgot last month's table" is a red gate.
2
+ // every registered entity: an untreated subject table is `X_SUBJECT_TABLE_UNDECLARED`; a
3
+ // `.personalData()` column an erase would leave, or a marked table no subject reaches, is red too.
4
4
  // Dynamic: `subjectProof` erases one generated person and searches every table for them.
5
5
 
6
6
  import { isUltimateError } from '@ultimat3/core';
7
7
  import type { DbClient } from '@ultimat3/db';
8
8
  import { identifier, sql } from '@ultimat3/db';
9
- import type { EntityCore, RegistryEntry } from '@ultimat3/entity';
10
- import type { Subject } from '@ultimat3/jobs';
11
- import { planSubject } from '@ultimat3/jobs';
9
+ import type { EntityCore, PersonalDataEntity, RegistryEntry } from '@ultimat3/entity';
10
+ import { personalDataOf } from '@ultimat3/entity';
11
+ import type { Subject, SubjectPlan } from '@ultimat3/jobs';
12
+ import { planSubject, unerasedPersonalData, unreachedPersonalData } from '@ultimat3/jobs';
12
13
  import type { SeedFactory, SeedGraph } from '@ultimat3/testing';
13
14
  import { entitySeedWriter, subjectProof } from '@ultimat3/testing';
14
15
  import type { Finding } from './output';
@@ -17,20 +18,44 @@ export function subjectFindings(
17
18
  subjects: readonly Subject<never>[],
18
19
  entries: readonly RegistryEntry[],
19
20
  ): readonly Finding[] {
20
- return subjects.flatMap((subject) =>
21
- planSubject({
21
+ const findings: Finding[] = [];
22
+ const plans: SubjectPlan[] = [];
23
+ const push = (problem: unknown, at: string): void => {
24
+ if (isUltimateError(problem)) {
25
+ findings.push({ code: problem.code, cause: problem.cause, fix: problem.fix, at });
26
+ }
27
+ };
28
+ for (const subject of subjects) {
29
+ const { plan, problems } = planSubject({
22
30
  subject: subject.entity,
23
31
  tables: subject.init.tables,
24
32
  columns: subject.init.columns,
25
33
  entries,
26
- }).problems.flatMap((problem): Finding[] =>
27
- isUltimateError(problem)
28
- ? [{ code: problem.code, cause: problem.cause, fix: problem.fix, at: subject.entity }]
29
- : [],
30
- ),
31
- );
34
+ });
35
+ for (const problem of problems) push(problem, subject.entity);
36
+ // A refused plan's reach is not known: its coverage is not a question with an answer.
37
+ if (problems.length > 0) continue;
38
+ plans.push(plan);
39
+ }
40
+ // `.personalData()` coverage (`@ultimat3/jobs`' `gdpr-coverage.ts`), over the same entries.
41
+ const marked = markedOf(entries);
42
+ for (const plan of plans) {
43
+ for (const leak of unerasedPersonalData(plan, marked)) push(leak, plan.subject);
44
+ }
45
+ for (const lost of unreachedPersonalData(plans, marked)) push(lost, String(lost.meta?.['table']));
46
+ return findings;
32
47
  }
33
48
 
49
+ /** The entries carrying `.personalData()` columns, as `personalDataEntities()` shapes them. */
50
+ const markedOf = (entries: readonly RegistryEntry[]): readonly PersonalDataEntity[] =>
51
+ entries.flatMap((entry) => {
52
+ const core = entry.core;
53
+ const columns = core === undefined ? [] : personalDataOf(core);
54
+ return core === undefined || columns.length === 0
55
+ ? []
56
+ : [{ entity: core, tenantColumn: core.$tenantColumn, columns }];
57
+ });
58
+
34
59
  /**
35
60
  * The dynamic half: each declared subject erased on its own generated graph, on the pass's scratch
36
61
  * database, and every table searched (`subjectProof`). A seed of its own, so the proof's rows never
@@ -1,14 +1,18 @@
1
1
  // Single responsibility: arming failure capture for a booted role. `failureCapture.enabled` in
2
- // `app.config.ts` installs the Postgres bundle store (`x_failures`, applied by the boot's framework
3
- // schema); `x dev` arms it whatever the file says. Off, nothing is installed and `invoke` runs bare.
2
+ // `app.config.ts` installs the `failureStore` port — `runtime.ts`'s, else the Postgres bundle store
3
+ // (`x_failures`, applied by the boot's framework schema); `x dev` arms it whatever the file says.
4
+ // Off, nothing is installed and `invoke` runs bare.
4
5
 
5
6
  import type { AppConfig } from '@ultimat3/core';
6
- import { FAILURE_CAPTURE_DEFAULTS, setFailureStore, settleFailureCaptures } from '@ultimat3/core';
7
+ import { FAILURE_CAPTURE_DEFAULTS, settleFailureCaptures } from '@ultimat3/core';
8
+ import { type FailureStore, installFailureStore } from '@ultimat3/core/adapter';
7
9
  import { postgresFailureStore } from '@ultimat3/db';
8
10
 
9
11
  export interface ArmFailureCaptureOptions {
10
12
  /** `x dev`: on whatever `app.config.ts` says — a development process's input is the developer's. */
11
13
  readonly force?: boolean | undefined;
14
+ /** `runtime.ts`'s `failureStore`. Omitted, the Postgres store over the boot's pool. */
15
+ readonly store?: FailureStore | undefined;
12
16
  }
13
17
 
14
18
  /** Install the store when capture is on; answer the undo, which settles in-flight saves first. */
@@ -18,13 +22,13 @@ export function armFailureCapture(
18
22
  ): () => Promise<void> {
19
23
  const block = config?.failureCapture ?? FAILURE_CAPTURE_DEFAULTS;
20
24
  if (!block.enabled && options.force !== true) return async () => undefined;
21
- const previous = setFailureStore(postgresFailureStore(), {
25
+ const release = installFailureStore(options.store ?? postgresFailureStore(), {
22
26
  perHour: block.perHour,
23
27
  maxRows: block.maxRows,
24
28
  maxBytes: block.maxBytes,
25
29
  });
26
30
  return async () => {
27
31
  await settleFailureCaptures();
28
- setFailureStore(previous);
32
+ release();
29
33
  };
30
34
  }
@@ -54,7 +54,7 @@ export interface FrameworkSchema {
54
54
  * `create table if not exists` on an unused table costs one round trip at boot. The alternative
55
55
  * costs a request: a store installed later must never be the thing that discovers the schema was
56
56
  * never applied, and several of these are installed AFTER this runs — `defineAuth` builds its
57
- * limiter when the app's modules import, and `setNotifyStores` is an app's boot line.
57
+ * limiter when the app's modules import, and a `runtime.ts` `notifyStores` may name Postgres stores.
58
58
  *
59
59
  * Ordered so a foreign key never precedes its target. Only `AUTH_TABLES` has any, and they are
60
60
  * internal to that entry, which is why it ships as an ordered list rather than one string.
@@ -82,7 +82,7 @@ export const FRAMEWORK_SCHEMA: readonly FrameworkSchema[] = Object.freeze([
82
82
  tables: Object.freeze(['x_idempotency']),
83
83
  ddl: Object.freeze([SQL_IDEMPOTENCY_TABLE]),
84
84
  }),
85
- // The DDL only, and deliberately NO `setAuditSink`: there is no default audit sink on purpose,
85
+ // The DDL only, and deliberately NO `installAuditSink`: there is no default audit sink on purpose,
86
86
  // so `X_AUDIT_SINK_MISSING` keeps firing at boot for an app that declares `audit: true` and
87
87
  // installs none.
88
88
  Object.freeze({
@@ -144,8 +144,8 @@ export const FRAMEWORK_SCHEMA: readonly FrameworkSchema[] = Object.freeze([
144
144
  * The delivery ledger is what stops a replayed notifier job sending twice, and it is the entry
145
145
  * whose absence is least visible: without the table the ledger's first `claim` raises `42P01`
146
146
  * from inside a worker, which reads as a dead-lettered notification rather than as a missing
147
- * schema. Installed whether or not this boot calls `setNotifyStores`, for the same reason as
148
- * every row above it — that call is an APP's boot line and runs after this one.
147
+ * schema. Installed whether or not `runtime.ts` supplies `notifyStores`, for the same reason as
148
+ * every row above it — the store is the app's choice and is first used after this runs.
149
149
  */
150
150
  Object.freeze({
151
151
  pkg: '@ultimat3/notify',
@@ -158,7 +158,7 @@ export const FRAMEWORK_SCHEMA: readonly FrameworkSchema[] = Object.freeze([
158
158
  ddl: Object.freeze([SQL_NOTIFY_INBOX_TABLE]),
159
159
  }),
160
160
  // `postgresDigestStore`'s windows. Installed whether or not the app picks that store, for the
161
- // reason every notify row is: `setNotifyStores` is the app's boot line and runs after this one.
161
+ // reason every notify row is: `notifyStores` is `runtime.ts`'s choice, used after this runs.
162
162
  Object.freeze({
163
163
  pkg: '@ultimat3/notify',
164
164
  tables: Object.freeze(['x_notify_digests']),
@@ -70,7 +70,7 @@ export function withDeclaredExercises(files: readonly GeneratedFile[]): readonly
70
70
  throw new UltimateError({
71
71
  code: 'X_EXERCISE_FILE_UNEDITABLE',
72
72
  cause: `x new's own ${EXERCISE_FILE} ${edit.reason}, so its contract tests would read no entry`,
73
- fix: 'bun test packages/cli/src/generate-exercise.test.ts # the scaffold template and the editor disagree',
73
+ fix: 'bun test ./packages/cli/src/generate-exercise.test.ts # the scaffold template and the editor disagree',
74
74
  });
75
75
  }
76
76
  return files.map((one, index) => (index === at ? { ...one, contents: edit.source } : one));
@@ -31,6 +31,7 @@ import { adminCatalogFiles } from './templates/admin-catalog';
31
31
  import { helmMonitoringFiles } from './templates/scaffold-helm-alerts';
32
32
  import { oidcSignInFiles } from './templates/sign-in-oidc';
33
33
  import { passwordSignInFiles } from './templates/sign-in-password';
34
+ import { workspaceAppFiles, workspacePackageFiles } from './templates/workspace';
34
35
 
35
36
  export interface GenerateOptions {
36
37
  readonly kind: Generator;
@@ -95,16 +96,25 @@ export interface GenerateOptions {
95
96
  readonly sibling?: boolean;
96
97
  /** `sign-in` only: which shape — `--password` or `--oidc <provider>`. Required for that kind. */
97
98
  readonly signIn?: SignInMode;
99
+ /**
100
+ * `app` and `package`: the repo's scope, `<scope>` of `@<scope>/<name>` — read off the root
101
+ * manifest by `run` (`generate-workspace.ts`). `app` when absent.
102
+ */
103
+ readonly scope?: string;
104
+ /** The app workspace a slice lands in, `apps/<app>/` (`--app`). Default `web`. */
105
+ readonly app?: string;
98
106
  }
99
107
 
100
- const DEFAULT_SURFACE_DIR: Record<Surface, string> = {
101
- site: 'apps/web/site',
102
- app: 'apps/web/app',
103
- };
108
+ /** The app every generator wrote into before `--app`, and still the default. */
109
+ export const DEFAULT_APP = 'web';
110
+
111
+ /** A surface's directory in one app workspace: `apps/<app>/<surface>`. */
112
+ const surfaceDirOf = (surface: Surface, app: string = DEFAULT_APP): string =>
113
+ `apps/${app}/${surface}`;
104
114
 
105
115
  /** Where a feature slice lives, relative to the app root — the one derivation `run` reads from. */
106
- export const sliceDir = (surface: Surface, feature: string): string =>
107
- `${DEFAULT_SURFACE_DIR[surface]}/${feature}`;
116
+ export const sliceDir = (surface: Surface, feature: string, app: string = DEFAULT_APP): string =>
117
+ `${surfaceDirOf(surface, app)}/${feature}`;
108
118
 
109
119
  /**
110
120
  * `x g resource <name> --feature <other>`. A resource IS its feature: every file it composes — the
@@ -134,7 +144,7 @@ export function generate(options: GenerateOptions): readonly GeneratedFile[] {
134
144
  const surface: Surface = options.surface ?? 'app';
135
145
  assertSurfaceSupported(options.kind, surface, options.name);
136
146
  assertLiveSupported(options.kind, options.live === true, options.name);
137
- const surfaceDir = DEFAULT_SURFACE_DIR[surface];
147
+ const surfaceDir = surfaceDirOf(surface, options.app);
138
148
  refuseResourceFeature(options, surfaceDir);
139
149
  // Kebab, always: `x g entity BlogPost` wrote `app/BlogPost/` while `resource` wrote
140
150
  // `app/blog-post/`, so one feature grew two slice directories depending on the generator.
@@ -254,6 +264,15 @@ export function generate(options: GenerateOptions): readonly GeneratedFile[] {
254
264
  : oidcSignInFiles(signIn.provider, shape),
255
265
  );
256
266
  }
267
+ case 'app':
268
+ case 'package': {
269
+ // `run` reads the scope off the root manifest (`generate-workspace.ts`); a direct caller
270
+ // that names none — a test sweeping every generator — gets the template scope `app`.
271
+ const scope = names(options.scope ?? 'app');
272
+ return options.kind === 'app'
273
+ ? workspaceAppFiles(scope, kebab(options.name))
274
+ : workspacePackageFiles(scope, kebab(options.name));
275
+ }
257
276
  case 'chart-alerts':
258
277
  // `name` is the chart's own (`Chart.yaml`), which its helpers are named after. The values
259
278
  // blocks are an edit to a file the app owns, so `generate-chart-alerts.ts` makes it.
@@ -264,6 +283,7 @@ export function generate(options: GenerateOptions): readonly GeneratedFile[] {
264
283
  return dedupe(
265
284
  routeFiles(options.name, {
266
285
  surface,
286
+ ...(options.app === undefined ? {} : { app: options.app }),
267
287
  ...(options.locales === undefined ? {} : { locales: options.locales }),
268
288
  ...(options.catalogModule === undefined ? {} : { catalogModule: options.catalogModule }),
269
289
  }),
@@ -29,6 +29,8 @@ export const GENERATORS = [
29
29
  'guard',
30
30
  'sign-in',
31
31
  'chart-alerts',
32
+ 'app',
33
+ 'package',
32
34
  ] as const;
33
35
 
34
36
  export type Generator = (typeof GENERATORS)[number];
@@ -286,4 +288,7 @@ const EXAMPLE_NAME: Readonly<Record<Generator, string>> = {
286
288
  'sign-in': '--password',
287
289
  // No name either: an app has one chart. `--print` runs with or without one.
288
290
  'chart-alerts': '--print',
291
+ // A workspace: `apps/admin`, `packages/domain`.
292
+ app: 'admin',
293
+ package: 'domain',
289
294
  };
@@ -0,0 +1,53 @@
1
+ // Whether an `x g` run's files can change a fact `x.manifest.json` holds — and so whether the run
2
+ // has to load the whole app to re-project it. Every manifest fact is read off a registry the app
3
+ // scan fills, except the `X_*` codes, which are read off the source: a file the scan never imports
4
+ // and that declares no code cannot move either, so the run skips the load (plan 101, slice 22 B5).
5
+
6
+ // why: Bun ships no path API; the scan's own rule takes an absolute path.
7
+ import { resolve } from 'node:path';
8
+ import { isAppModulePath } from './app-load';
9
+ import { isTest } from './source-files';
10
+ import { scanCodes } from './ts-scan';
11
+
12
+ /** Source the codes walk reads; anything else is data, a stylesheet or a doc. */
13
+ const SOURCE = /\.[cm]?[jt]sx?$/;
14
+
15
+ /**
16
+ * Whether one written or edited file can change the manifest. Unreadable (a dry run's planned file
17
+ * is not on disk) is answered from `planned` when the caller has its bytes, and is `true` when it
18
+ * has none: a refresh too many costs seconds, one too few is a stale contract.
19
+ */
20
+ async function moves(
21
+ root: string,
22
+ path: string,
23
+ planned: ReadonlyMap<string, string>,
24
+ ): Promise<boolean> {
25
+ // The app root's own files — `package.json`, `app.config.ts` — are the manifest's identity.
26
+ if (!path.includes('/')) return true;
27
+ // Neither imported nor walked for codes (`collectDeclaredCodes` skips them too).
28
+ if (isTest(path)) return false;
29
+ if (isAppModulePath(root, path)) return true;
30
+ if (!SOURCE.test(path)) return !/\.(?:s?css|md|json)$/.test(path);
31
+ const text =
32
+ planned.get(path) ??
33
+ (await Bun.file(resolve(root, path))
34
+ .text()
35
+ .catch(() => undefined));
36
+ return text === undefined || scanCodes(text, path).length > 0;
37
+ }
38
+
39
+ /**
40
+ * Whether any of `paths` (app-root-relative) can change `x.manifest.json`. A `.json` file is no
41
+ * manifest input: a catalog's keys are not in it, and a workspace manifest's edit always arrives
42
+ * with the module whose import it declares.
43
+ */
44
+ export async function manifestCanChange(
45
+ root: string,
46
+ paths: readonly string[],
47
+ planned: ReadonlyMap<string, string> = new Map(),
48
+ ): Promise<boolean> {
49
+ for (const path of paths) {
50
+ if (await moves(root, path, planned)) return true;
51
+ }
52
+ return false;
53
+ }