@ultimat3/cli 30.9.0 → 31.0.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 (197) hide show
  1. package/CLAUDE.md +75 -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.ts +5 -1
  6. package/src/app-boundaries.ts +88 -9
  7. package/src/app-load-async.ts +133 -0
  8. package/src/app-load-batch.ts +203 -0
  9. package/src/app-load-prebuilt.ts +147 -0
  10. package/src/app-load-register.ts +175 -0
  11. package/src/app-load.ts +143 -175
  12. package/src/app-loader-imports.ts +31 -0
  13. package/src/app-root.ts +13 -0
  14. package/src/app-runtime.ts +5 -1
  15. package/src/boundary-findings.ts +12 -0
  16. package/src/browser-launcher-port.ts +3 -7
  17. package/src/browser-launcher.ts +1 -1
  18. package/src/budgets-scan.ts +8 -0
  19. package/src/budgets.ts +10 -1
  20. package/src/build-registry-background.ts +59 -0
  21. package/src/build-registry.ts +207 -0
  22. package/src/cdp-shot-clock.ts +3 -11
  23. package/src/cdp-shot-driver.ts +3 -2
  24. package/src/cdp-shot-element.ts +3 -2
  25. package/src/cdp-shot-page.ts +2 -2
  26. package/src/cdp-shot-watch.ts +4 -3
  27. package/src/cmd-auth.ts +3 -3
  28. package/src/cmd-db-recount.ts +15 -0
  29. package/src/cmd-drill.ts +10 -6
  30. package/src/cmd-exercise.ts +2 -1
  31. package/src/cmd-generate-spec.ts +6 -0
  32. package/src/cmd-generate.ts +22 -4
  33. package/src/cmd-mail.ts +1 -1
  34. package/src/cmd-routes.ts +2 -2
  35. package/src/cmd-secrets-spec.ts +4 -1
  36. package/src/cmd-shot.ts +14 -4
  37. package/src/cmd-verify-spec.ts +21 -1
  38. package/src/cmd-verify.ts +16 -4
  39. package/src/coverage-source.ts +4 -1
  40. package/src/db-diagnostics.ts +8 -1
  41. package/src/dev-boot.ts +29 -15
  42. package/src/dev-dashboard-invalidations.ts +43 -0
  43. package/src/dev-dashboard.ts +13 -16
  44. package/src/dev-n-plus-one.ts +7 -3
  45. package/src/dev-rebuild.ts +2 -1
  46. package/src/dev-route-table.ts +1 -1
  47. package/src/dev-traces.ts +16 -15
  48. package/src/document-options.ts +12 -1
  49. package/src/drift-store.ts +55 -0
  50. package/src/error-catalog.ts +8 -3
  51. package/src/error-codes-boundary.ts +32 -0
  52. package/src/error-codes.ts +23 -19
  53. package/src/errors.ts +17 -7
  54. package/src/exercise-database.ts +13 -1
  55. package/src/exercise-findings.ts +36 -18
  56. package/src/exercise-services.ts +84 -0
  57. package/src/exercise-subject.ts +38 -13
  58. package/src/failure-capture-boot.ts +9 -5
  59. package/src/framework-schema.ts +5 -5
  60. package/src/generate-exercise.ts +1 -1
  61. package/src/generate-files.ts +27 -7
  62. package/src/generate-kinds.ts +5 -0
  63. package/src/generate-refresh.ts +53 -0
  64. package/src/generate-workspace.ts +169 -0
  65. package/src/generate-write.ts +8 -2
  66. package/src/hold.ts +19 -8
  67. package/src/image-prepare.ts +6 -2
  68. package/src/index.ts +5 -20
  69. package/src/island-bundle.ts +7 -3
  70. package/src/island-capture.ts +2 -2
  71. package/src/island-harness.ts +1 -1
  72. package/src/job-registration.ts +43 -6
  73. package/src/jobs-driver.ts +4 -5
  74. package/src/mcp-errors.ts +18 -4
  75. package/src/mcp-host.ts +5 -1
  76. package/src/mcp-ui-interact.ts +3 -0
  77. package/src/messages-gate.ts +4 -0
  78. package/src/new-shapes-generate.ts +1 -1
  79. package/src/otlp-export.ts +94 -29
  80. package/src/output.ts +3 -7
  81. package/src/page-sync.ts +3 -1
  82. package/src/role-load.ts +17 -11
  83. package/src/role-start.ts +5 -4
  84. package/src/role-sync.ts +7 -8
  85. package/src/route-islands-preload.ts +46 -0
  86. package/src/route-islands.ts +6 -2
  87. package/src/runtime-admin.ts +5 -1
  88. package/src/runtime-bindings.ts +25 -19
  89. package/src/runtime-boot-ports.ts +66 -0
  90. package/src/runtime-bus.ts +29 -5
  91. package/src/runtime-cache-bus.ts +53 -0
  92. package/src/runtime-cache.ts +43 -13
  93. package/src/runtime-isr-outcome.ts +5 -4
  94. package/src/runtime-jobs.ts +2 -2
  95. package/src/runtime-keys.ts +37 -0
  96. package/src/runtime-overrides.ts +148 -42
  97. package/src/runtime-port-bindings-queue.ts +36 -0
  98. package/src/runtime-port-bindings.ts +117 -0
  99. package/src/runtime-ports.ts +164 -0
  100. package/src/runtime-purge.ts +41 -28
  101. package/src/runtime-push.ts +7 -3
  102. package/src/runtime-queue.ts +70 -55
  103. package/src/runtime-realtime.ts +5 -5
  104. package/src/runtime-render-document.ts +4 -1
  105. package/src/runtime-services.ts +110 -158
  106. package/src/runtime-storage-boot.ts +111 -0
  107. package/src/runtime-storage-upload.ts +9 -7
  108. package/src/runtime-storage.ts +7 -1
  109. package/src/serve-boot.ts +8 -4
  110. package/src/serve-entry.ts +3 -0
  111. package/src/serve-env.ts +47 -14
  112. package/src/serve-prebuilt-paths.ts +3 -0
  113. package/src/serve-prebuilt.ts +15 -4
  114. package/src/serve.ts +2 -2
  115. package/src/static-cards.ts +3 -2
  116. package/src/static-report.ts +2 -2
  117. package/src/style-bundle.ts +1 -1
  118. package/src/sync-authenticator.ts +17 -18
  119. package/src/templates/action-tests.ts +4 -4
  120. package/src/templates/backfill.ts +5 -8
  121. package/src/templates/entity.ts +3 -0
  122. package/src/templates/github/ci.yml.ts +3 -1
  123. package/src/templates/github/dependabot.yml.ts +73 -0
  124. package/src/templates/job.ts +13 -22
  125. package/src/templates/naming.ts +20 -1
  126. package/src/templates/pinned/docker-compose.yml +1 -1
  127. package/src/templates/query.ts +7 -8
  128. package/src/templates/route.ts +5 -3
  129. package/src/templates/scaffold-api.ts +1 -1
  130. package/src/templates/scaffold-auth.ts +5 -3
  131. package/src/templates/scaffold-claude-commands.ts +6 -3
  132. package/src/templates/scaffold-claude.ts +4 -4
  133. package/src/templates/scaffold-container-compose.ts +2 -4
  134. package/src/templates/scaffold-domain-package.ts +1 -1
  135. package/src/templates/scaffold-entries.ts +6 -1
  136. package/src/templates/scaffold-helm-fences.ts +3 -2
  137. package/src/templates/scaffold-helm.ts +35 -6
  138. package/src/templates/scaffold-repo.ts +47 -135
  139. package/src/templates/scaffold-runtime-ports.ts +62 -0
  140. package/src/templates/scaffold-verify-floor.ts +97 -0
  141. package/src/templates/shapes/overlay.ts +1 -1
  142. package/src/templates/sign-in-oidc.ts +5 -3
  143. package/src/templates/sign-in-shared.ts +28 -10
  144. package/src/templates/workspace.ts +75 -0
  145. package/src/test-ignores.ts +5 -2
  146. package/src/test-select.ts +4 -1
  147. package/src/upgrade-gate.ts +30 -5
  148. package/src/upgrade-report.ts +7 -1
  149. package/src/verify-changed-facts.ts +53 -0
  150. package/src/verify-changed-scope.ts +161 -0
  151. package/src/verify-changed.ts +174 -0
  152. package/src/verify-checks.ts +31 -19
  153. package/src/verify-drift-owner.ts +30 -0
  154. package/src/verify-e2e.ts +2 -1
  155. package/src/verify-factories.ts +86 -0
  156. package/src/verify-run.ts +13 -11
  157. package/src/verify-step.ts +13 -0
  158. package/src/verify-tests.ts +58 -6
  159. package/src/write-line.ts +21 -6
  160. package/wiki/Actions.md +2 -2
  161. package/wiki/Adapters.md +400 -0
  162. package/wiki/Admin-Dashboard.md +1 -1
  163. package/wiki/Agents.md +9 -9
  164. package/wiki/Auth.md +78 -2
  165. package/wiki/Building-Your-Own-Base.md +1 -1
  166. package/wiki/CLI-Reference.md +34 -7
  167. package/wiki/Caching-And-Invalidation.md +17 -5
  168. package/wiki/Compared.md +8 -2
  169. package/wiki/Configuration.md +14 -14
  170. package/wiki/Deployment.md +28 -1
  171. package/wiki/Entities-And-Migrations.md +47 -1
  172. package/wiki/FAQ.md +8 -2
  173. package/wiki/Feature-Flags.md +1 -1
  174. package/wiki/Home.md +3 -2
  175. package/wiki/Jobs-And-Workflows.md +107 -6
  176. package/wiki/Known-Gaps.md +4 -3
  177. package/wiki/MCP-And-AI.md +18 -4
  178. package/wiki/Mail.md +14 -5
  179. package/wiki/Migrations-And-Backfills.md +29 -4
  180. package/wiki/Money.md +2 -0
  181. package/wiki/N-Plus-One-Detection.md +24 -22
  182. package/wiki/Notify.md +28 -4
  183. package/wiki/Observability.md +121 -15
  184. package/wiki/Queries-And-Live-Queries.md +2 -2
  185. package/wiki/Realtime.md +9 -4
  186. package/wiki/Routes-And-Render-Modes.md +5 -0
  187. package/wiki/Scraping.md +57 -11
  188. package/wiki/Shapes.md +2 -2
  189. package/wiki/Stability.md +7 -5
  190. package/wiki/Storage-And-Uploads.md +56 -4
  191. package/wiki/Testing.md +65 -52
  192. package/wiki/Troubleshooting.md +1 -1
  193. package/wiki/Tutorial-01-First-App.md +1 -1
  194. package/wiki/Tutorial-04-Jobs-And-Realtime.md +1 -1
  195. package/wiki/Tutorial-05-Deploy-Free.md +1 -1
  196. package/wiki/Tutorial-06-Growing-Up.md +8 -8
  197. package/wiki/Upgrading.md +129 -4
@@ -27,6 +27,7 @@ import { routeQuery } from './isr-query-guard';
27
27
  import { navigationTagsOf } from './page-navigation';
28
28
  import { servedPins } from './page-pins';
29
29
  import { bootScript, collectorFor } from './route-islands';
30
+ import { preloadTags } from './route-islands-preload';
30
31
  import { siteAssetTable } from './site-assets';
31
32
  import { styleBundle } from './style-bundle';
32
33
 
@@ -197,8 +198,10 @@ export async function documentFrom(
197
198
  headFor(entry, ctx, data, options, scope),
198
199
  routeBody(entry, ctx, data, islands),
199
200
  ]);
201
+ const boot = bootScript(entry, islands, options, scope);
202
+ const preloads = preloadTags(entry, islands, options, boot !== '');
200
203
  return (
201
204
  `<!doctype html><html lang="${lang()}"><head>${head}${stylesFor(entry, options)}</head>` +
202
- `<body>${body}${bootScript(entry, islands, options, scope)}${hydrateRuntime(islands.directives)}</body></html>`
205
+ `<body>${body}${boot}${preloads}${hydrateRuntime(islands.directives)}</body></html>`
203
206
  );
204
207
  }
@@ -1,46 +1,30 @@
1
1
  // Starting the services `runtime-bindings.ts` resolved. Resolution answers "which database"; this
2
2
  // answers "it is running, and every ambient accessor in the framework now points at it" — so
3
3
  // `db()`, `jobDriver()`, `mailDriver()` and the realtime transport are the objects a production
4
- // boot installs, only backed by embedded drivers.
4
+ // boot installs, only backed by embedded drivers. The storage disk is `runtime-storage-boot.ts`.
5
5
 
6
- import { mkdirSync } from 'node:fs';
7
- import {
8
- configureAuthLimiters,
9
- configureTotpReplay,
10
- postgresAuthLimiter,
11
- postgresTotpReplayGuard,
12
- resetAuthLimiters,
13
- resetTotpReplay,
14
- } from '@ultimat3/auth';
6
+ import { postgresAuthLimiter, postgresTotpReplayGuard } from '@ultimat3/auth';
15
7
  import type { PurgeDriver } from '@ultimat3/cache';
16
8
  import { isNoopPurgeDriver, selectPurgeDriver } from '@ultimat3/cache';
17
9
  import {
18
- isLocal,
19
10
  type RealtimeConfig,
20
11
  type Role,
21
12
  registerReadinessCheck,
22
- renderThrowable,
23
- resolveEnvironment,
24
13
  systemClock,
25
14
  } from '@ultimat3/core';
15
+ import type { FailureStore } from '@ultimat3/core/adapter';
26
16
  import { dbExecutor } from '@ultimat3/db';
27
17
  import type { RateLimitStore } from '@ultimat3/http';
28
- import { adoptRateLimitStore, postgresRateLimitStore } from '@ultimat3/http';
18
+ import { postgresRateLimitStore } from '@ultimat3/http';
29
19
  import type { EventBus, JobDriver, OutboxStore } from '@ultimat3/jobs';
30
20
  import type { MailDriver } from '@ultimat3/mail';
31
- import {
32
- isMemoryDriver,
33
- isUnconfiguredDriver,
34
- resetMailDriver,
35
- setMailDriver,
36
- } from '@ultimat3/mail';
21
+ import { isMemoryDriver, isUnconfiguredDriver } from '@ultimat3/mail';
37
22
  import type { BusUse, Transport } from '@ultimat3/realtime/server';
38
23
  import type { Storage } from '@ultimat3/storage';
39
- import { defineStorage, localDriver, s3Driver, usesDevStorageSecret } from '@ultimat3/storage';
40
24
  import { loadAppConfig } from './app-config-load';
41
- import { LocalDiskUnsafeError, StorageUnwritableError } from './errors';
42
25
  import { msg } from './messages';
43
26
  import type { DevServices, Env } from './runtime-bindings';
27
+ import { installBootPorts } from './runtime-boot-ports';
44
28
  import { selectBus } from './runtime-bus';
45
29
  import { cacheTiersOf, startCacheTiers } from './runtime-cache';
46
30
  import { type WorkerConfig, workerConfigOf } from './runtime-jobs';
@@ -48,12 +32,14 @@ import { jobsRetentionTargets } from './runtime-jobs-retention';
48
32
  import { selectAppMailDriver } from './runtime-mail';
49
33
  import { inboxRetentionOf } from './runtime-notify-retention';
50
34
  import type { RuntimeOverrides } from './runtime-overrides';
35
+ import { notifyStoresWithLedger, PORT_BINDINGS } from './runtime-port-bindings';
36
+ import { installPorts, suppliedOr } from './runtime-ports';
51
37
  import { installRetentionSweep } from './runtime-purge';
52
38
  import { installAppWebPush, selectWebPush } from './runtime-push';
53
39
  import { type DevDbClient, type SchemaMode, startQueue } from './runtime-queue';
54
40
  import { realtimeConfigOf } from './runtime-realtime';
55
- import { s3PathStyleOf } from './runtime-s3-path-style';
56
41
  import { reportStatementBound } from './runtime-statement-bound';
42
+ import { startStorage } from './runtime-storage-boot';
57
43
 
58
44
  export interface RunningServices {
59
45
  readonly services: DevServices;
@@ -64,8 +50,8 @@ export interface RunningServices {
64
50
  readonly events: EventBus;
65
51
  readonly transport: Transport;
66
52
  /**
67
- * `app.config.ts`'s `realtime` section as this boot obeyed it. `transport` and `urlEnv` chose
68
- * `transport` above; `enabled` is what `startRoles` reads before it starts `sync` or a replicator.
53
+ * `app.config.ts`'s `realtime` section as this boot obeyed it: `enabled` is what `startRoles`
54
+ * reads before it starts `sync` or a replicator. The bus is `NATS_URL`'s or `runtime.transport`.
69
55
  */
70
56
  readonly realtime: RealtimeConfig;
71
57
  /**
@@ -112,6 +98,11 @@ export interface RunningServices {
112
98
  */
113
99
  readonly rateLimitStore?: RateLimitStore;
114
100
  readonly purge: PurgeDriver;
101
+ /**
102
+ * `runtime.ts`'s `failureStore`, carried to the boot step that arms capture after `loadApp`
103
+ * (`failure-capture-boot.ts`); `undefined` is its Postgres default.
104
+ */
105
+ readonly failureStore?: FailureStore | undefined;
115
106
  /** Same rule as `mailDetail`: the env key that selected the CDN, never the token behind it. */
116
107
  readonly purgeDetail: string;
117
108
  stop(): Promise<void>;
@@ -166,88 +157,6 @@ export function cdnLabel(runtime: RunningServices): string {
166
157
  : msg('cli.dev.cdn.external', { driver: runtime.purge.name, detail: runtime.purgeDetail });
167
158
  }
168
159
 
169
- const FILE_SCHEME = 'file://';
170
-
171
- /**
172
- * The storage disk this process will use.
173
- *
174
- * An `external` binding now reaches `s3Driver`. It used to fall through to a LOCAL directory —
175
- * `S3_ENDPOINT` selected a different root and nothing else, so every deployment that configured
176
- * object storage silently wrote to a container-local disk, and every upload was destroyed by the
177
- * next restart while the configured bucket stayed empty. Nothing failed; the files just went
178
- * nowhere.
179
- *
180
- * The embedded branch is also where a hardened container died. `mkdirSync` on a
181
- * `readOnlyRootFilesystem` throws a bare `EROFS` from inside Bun's fs, with no code, no fix and no
182
- * mention of storage — the demo CrashLooped 22 times on it. A read-only filesystem is a normal way
183
- * to run a container, so this reports what to do instead of what went wrong.
184
- */
185
- export function startStorage(services: DevServices, env: Env, override?: Storage): Storage {
186
- // First arm, not a branch beside the two below: a host that handed the boot a `Storage` has
187
- // already answered "which disk", and re-deriving one from `S3_ENDPOINT` would be a second answer.
188
- if (override !== undefined) return override;
189
- const binding = services.storage;
190
-
191
- if (binding.mode === 'external') {
192
- const bucket = env['S3_BUCKET'] ?? '';
193
- if (bucket === '') {
194
- throw new StorageUnwritableError(
195
- `S3_ENDPOINT is set to ${binding.url} but S3_BUCKET is empty, so there is no disk to write to`,
196
- 'set S3_BUCKET to the bucket name, or unset S3_ENDPOINT to use the embedded disk',
197
- );
198
- }
199
- return defineStorage({
200
- disks: {
201
- object: s3Driver({
202
- bucket,
203
- endpoint: binding.url,
204
- ...(env['S3_REGION'] === undefined ? {} : { region: env['S3_REGION'] }),
205
- forcePathStyle: s3PathStyleOf(env),
206
- }),
207
- },
208
- default: 'object',
209
- });
210
- }
211
-
212
- const root = binding.url.slice(FILE_SCHEME.length);
213
- // The embedded disk is what this branch falls back to whenever `S3_ENDPOINT`/`S3_BUCKET` are
214
- // unset — including in `production` and `staging`, where an unset `STORAGE_SIGNING_SECRET` means
215
- // every signed upload grant is minted with the string published in this repo, and
216
- // `acceptSignedUpload` trusts a signed constraint over the app's own `uploadPolicy`.
217
- //
218
- // `localDriver` refuses that at construction on its own (`X_ENV_MISSING`). Pre-empted here so
219
- // the message names the STORAGE CHOICE and both ways out, rather than arriving as "a secret is
220
- // missing" from a helper the operator never configured. Not an outright ban on the local disk in
221
- // production: a single-node Compose deploy on a mounted volume WITH a real secret is a rung on
222
- // the scale ladder, and refusing it would be a deploy-shape decision, not a security fix.
223
- // `{ env }` on ALL THREE, never the ambient `process.env`: this function is HANDED the boot's
224
- // environment and reads `S3_BUCKET` off it one branch above, so a guard asking a second source
225
- // could answer `development` for a process booting as `production` — or, with
226
- // `usesDevStorageSecret({ env })` left bare, refuse a boot whose own env carries a real
227
- // `STORAGE_SIGNING_SECRET` because the PROCESS does not. Which environment, whether a secret
228
- // exists, and the name the message prints are one question about one table.
229
- // `fallback: 'production'` on both, the reading `localDriver` itself takes: a boot that names no
230
- // environment is not a development one, and this message beats the driver's to it.
231
- if (!isLocal({ env, fallback: 'production' }) && usesDevStorageSecret({ env })) {
232
- throw new LocalDiskUnsafeError({
233
- environment: resolveEnvironment({ env, fallback: 'production' }),
234
- root,
235
- });
236
- }
237
- try {
238
- mkdirSync(root, { recursive: true });
239
- } catch (cause) {
240
- const detail = renderThrowable(cause);
241
- throw new StorageUnwritableError(
242
- `the embedded storage disk needs ${root} and it could not be created: ${detail}`,
243
- `mount a writable volume at ${root}, or set S3_ENDPOINT and S3_BUCKET to use object storage instead`,
244
- );
245
- }
246
- // The guard three lines up reads `env`; so must the disk it guards. Otherwise the boot's
247
- // environment decides whether signing is allowed and the process's decides what key is used.
248
- return defineStorage({ disks: { local: localDriver({ root, env }) }, default: 'local' });
249
- }
250
-
251
160
  /**
252
161
  * A readiness check over a dependency that can only be asked asynchronously.
253
162
  *
@@ -325,20 +234,18 @@ export async function releaseOrThrow(
325
234
  if (failures.length > 0) throw failures[0];
326
235
  }
327
236
 
328
- export async function startServices(
329
- services: DevServices,
330
- env: Env,
331
- overrides?: RuntimeOverrides,
332
- /** `'verify'` for a serving role on an external database — `runtime-queue.ts`'s `SchemaMode`. */
333
- schema: SchemaMode = 'apply',
334
- /**
335
- * The roles this process will start, which decide whether the boot waits for the bus: only a
336
- * `sync` node or a replicator does (`runtime-bus.ts`). Unset is the strictest reading.
337
- */
338
- roles?: readonly Role[],
339
- /** `x dev`: a bus the realtime roles need is waited for in the background, never refused. */
340
- dev = false,
341
- ): Promise<RunningServices> {
237
+ interface PrepareInput {
238
+ readonly services: DevServices;
239
+ readonly env: Env;
240
+ readonly overrides: RuntimeOverrides | undefined;
241
+ readonly schema: SchemaMode;
242
+ readonly roles: readonly Role[] | undefined;
243
+ readonly dev: boolean;
244
+ }
245
+
246
+ /** Everything selected before a service runs, and the queue — the first thing that does. */
247
+ async function prepareServices(input: PrepareInput) {
248
+ const { services, env, overrides, schema, roles, dev } = input;
342
249
  // The app's config is loaded ONCE, here, first, and every section below is read out of that one
343
250
  // validated object — mail's `retainMime` is the first reader, so it is loaded before mail.
344
251
  const config = await loadAppConfig(services.root);
@@ -350,9 +257,8 @@ export async function startServices(
350
257
  // Same reason, same place: building a purge driver reads env and dials nothing, so a half-set
351
258
  // `FASTLY_API_TOKEN` without its service id fails here rather than on the first stale page.
352
259
  const cdn = selectPurgeDriver(env);
353
- // Third of the same kind. `realtime.transport` selects the bus and `realtime.urlEnv` names the
354
- // variable holding its url; a config and an environment that disagree refuse here, before any
355
- // service starts, rather than quietly keeping the in-process bus. Which transport, which KV
260
+ // Third of the same kind: `runtime.transport`, else `NATS_URL` set is NATS and unset the
261
+ // in-process bus — a bucket name NATS cannot take refuses here, before any service. Which KV
356
262
  // bucket and which presence TTL is `@ultimat3/realtime`'s decision, and it is the same call a
357
263
  // `ROLE=sync` container makes, so this process cannot resolve the bus differently from the
358
264
  // container it stands in for. What the bus is USED for is the roles' (`runtime-bus.ts`).
@@ -366,44 +272,91 @@ export async function startServices(
366
272
  // reader here already uses it, so a queue that asked `process.env` would decide the standby from
367
273
  // a different answer than the middleware that routes to it.
368
274
  const queue = await startQueue(services, overrides, env, schema);
275
+ return { config, selection, cdn, realtime, push, workerConfig, bus, queue };
276
+ }
277
+
278
+ type Prepared = Awaited<ReturnType<typeof prepareServices>>;
279
+
280
+ export async function startServices(
281
+ services: DevServices,
282
+ env: Env,
283
+ overrides?: RuntimeOverrides,
284
+ /** `'verify'` for a serving role on an external database — `runtime-queue.ts`'s `SchemaMode`. */
285
+ schema: SchemaMode = 'apply',
286
+ /**
287
+ * The roles this process will start, which decide whether the boot waits for the bus: only a
288
+ * `sync` node or a replicator does (`runtime-bus.ts`). Unset is the strictest reading.
289
+ */
290
+ roles?: readonly Role[],
291
+ /** `x dev`: a bus the realtime roles need is waited for in the background, never refused. */
292
+ dev = false,
293
+ ): Promise<RunningServices> {
294
+ // Before ANYTHING evaluates the app's config: `app.config.ts`'s `installSecrets()` asks the
295
+ // secret source, and every "now" from here on reads the clock. `runtime.ts`'s, or the defaults.
296
+ const booted = await installBootPorts(overrides);
297
+ let prepared: Prepared;
298
+ try {
299
+ prepared = await prepareServices({ services, env, overrides, schema, roles, dev });
300
+ } catch (error) {
301
+ await release(booted);
302
+ throw error;
303
+ }
304
+ const { config, selection, cdn, realtime, push, workerConfig, bus, queue } = prepared;
369
305
  const { db, jobs, outbox, events } = queue;
370
306
  await reportStatementBound(db);
371
307
  // The same executor the jobs driver, the outbox, the event bus and the idempotency store run
372
308
  // on — one pool, one `Bun.sql` that does NOT satisfy `PgExecutor` (`Bun.sql.query` is
373
309
  // `undefined`), one wrapper.
374
310
  const executor = dbExecutor(() => db);
375
- const rateLimitStore = postgresRateLimitStore({ executor });
311
+ // Built only when `runtime.ts` is silent, so the retention sweep below expires the boot's own
312
+ // tables and never a store the app handed over.
313
+ const rateLimit = suppliedOr(overrides?.rateLimitStore, () =>
314
+ postgresRateLimitStore({ executor }),
315
+ );
316
+ const rateLimitStore = rateLimit.value;
317
+ const totpReplay = suppliedOr(overrides?.totpReplay, () => postgresTotpReplayGuard({ executor }));
376
318
  // Boot is a sequence of external resources, and every step after the first can reject — the
377
319
  // queue is already up, so from here an unwind must release it exactly like everything after it.
378
320
  // Which is why the `try` opens on the NEXT line and not eight steps further down: it did, and
379
- // the steps above it registered process-wide state (`configureAuthLimiters`, the `purge()` job
321
+ // the steps above it registered process-wide state (the auth limiters, the `purge()` job
380
322
  // and its `task`) that throws on a name a previous boot in this process left in the registry —
381
323
  // `X_JOB_NAME_TAKEN`, outside the unwind, so `x dev` exited holding the PGlite lock, the pool
382
324
  // and the ambient accessors. Nothing may be pushed onto `started` from outside this block.
383
- const started: (() => void | Promise<void>)[] = [() => queue.stop()];
325
+ const started: (() => void | Promise<void>)[] = [...booted, () => queue.stop()];
384
326
  try {
385
- // Where failed sign-ins are counted, installed BEFORE `loadApp` for the reason the idempotency
386
- // store is: `defineAuth` is the app's call and it runs when the app's modules import, so a seam
387
- // filled afterwards is one every app would have to fill itself. A FACTORY and not a limiter —
388
- // the app declares `maxAttempts`/`windowMs`/`lockoutMs` and this boot has not read them yet, so
389
- // a limiter built here would be refused by `assertAuthLimiterPolicy` on any app that tuned one.
327
+ // The `services` ports, in ONE loop, BEFORE `loadApp`: `defineAuth`, `registerAction` and
328
+ // every notifier are the app's calls and run when its modules import, so a seam filled
329
+ // afterwards is one every app would have to fill itself.
390
330
  //
391
- // Until this line every deployment the framework produces counted lockouts per POD, while
392
- // `x new` scaffolds `replicas: 2` and `docker/helm` runs three — `maxAttempts × N` guesses per
393
- // account, and a lockout one replica established invisible to the rest.
394
- configureAuthLimiters((policy) =>
395
- postgresAuthLimiter({ executor, clock: systemClock, policy }),
331
+ // `authLimiter` is a FACTORY and not a limiter — the app declares `maxAttempts`/`windowMs`/
332
+ // `lockoutMs` and this boot has not read them yet. Until it was installed here every deployment
333
+ // counted lockouts per POD while `docker/helm` runs three: `maxAttempts × N` guesses per
334
+ // account. `totpReplay`: a code one replica accepted must be refused by the rest.
335
+ // `rateLimitStore`: an action's or a query's declared `rateLimit:` is counted on every surface,
336
+ // so a task spends from the fleet's table too; `startRoles` stacks the same store again.
337
+ // `mail`: with no credential the memory driver — caught, not sent, so the `/_x` mail panel can
338
+ // show it; `SMTP_URL` or `RESEND_API_KEY` makes it a real transport.
339
+ const clock = overrides?.clock ?? systemClock;
340
+ const mail = overrides?.mail ?? selection.driver;
341
+ started.push(
342
+ ...(await installPorts(PORT_BINDINGS, 'services', {
343
+ aiGateway: overrides?.aiGateway,
344
+ auditSink: overrides?.auditSink,
345
+ authLimiter:
346
+ overrides?.authLimiter ?? ((policy) => postgresAuthLimiter({ executor, clock, policy })),
347
+ // Supplied only: unset, each package's slot answers Postgres over the ambient pool.
348
+ authServerStore: overrides?.authServerStore,
349
+ errorReporter: overrides?.errorReporter,
350
+ mail,
351
+ mcpConfirmationStore: overrides?.mcpConfirmationStore,
352
+ // Zero config still has a shared ledger: Postgres over this pool unless `runtime.ts` named one.
353
+ notifyStores: notifyStoresWithLedger(overrides?.notifyStores, executor),
354
+ rateLimitStore,
355
+ scrapeDriver: overrides?.scrapeDriver,
356
+ smsTransport: overrides?.smsTransport,
357
+ totpReplay: totpReplay.value,
358
+ })),
396
359
  );
397
- started.push(() => resetAuthLimiters());
398
- // Where spent TOTP steps are kept, for the same reason: a code one replica accepted must be
399
- // refused by the rest, and `defineAuth` runs when the app's modules import.
400
- const totpReplay = postgresTotpReplayGuard({ executor });
401
- configureTotpReplay(() => totpReplay);
402
- started.push(() => resetTotpReplay());
403
- // Where an action's or a query's declared `rateLimit:` is counted — on every surface, so a
404
- // task or a one-off command spends from the fleet's table too, not one process' memory. Before
405
- // `loadApp` for the auth limiters' reason; `startRoles` stacks a deployment's override over it.
406
- started.push(adoptRateLimitStore(rateLimitStore));
407
360
  // The hourly sweep over the framework tables this boot is responsible for. Every one of them
408
361
  // ships a `purgeExpired()` that nothing called, so every row written was a row kept —
409
362
  // `x_rate_limit` takes one upsert per request the web role serves, assets included.
@@ -413,9 +366,10 @@ export async function startServices(
413
366
  // indistinguishable from an app that chose it.
414
367
  started.push(
415
368
  installRetentionSweep({
369
+ // The boot's OWN stores only: one `runtime.ts` supplied is the app's to expire.
416
370
  idempotency: queue.idempotency,
417
- rateLimit: rateLimitStore,
418
- totpReplay,
371
+ rateLimit: rateLimit.own,
372
+ totpReplay: totpReplay.own,
419
373
  events,
420
374
  ...jobsRetentionTargets(executor, config),
421
375
  inboxRetention: inboxRetentionOf(config),
@@ -437,15 +391,10 @@ export async function startServices(
437
391
  const transport = running.transport;
438
392
  // Before `loadApp` for the auth limiters' reason: `pushSubscribe()` is declared when the app's
439
393
  // modules import, and reads this runtime per call.
440
- if (push !== undefined) started.push(await installAppWebPush(push, executor));
394
+ if (push !== undefined) {
395
+ started.push(await installAppWebPush(push, executor, overrides?.pushSubscriptionStore));
396
+ }
441
397
  const storage = startStorage(services, env, overrides?.storage);
442
- // With no credential this is the memory driver: caught, not sent, so the `/_x` mail panel can
443
- // show what a template renders in every locale without a mailbox or a message escaping to a
444
- // real address. `SMTP_URL` or `RESEND_API_KEY` makes it a real transport instead — the same
445
- // "an unset variable means the embedded default" law the other three bindings follow.
446
- const mail = overrides?.mail ?? selection.driver;
447
- setMailDriver(mail);
448
- started.push(() => resetMailDriver());
449
398
  const purge = overrides?.purge ?? cdn.driver;
450
399
  // Every tier this process reads through, plus the cross-instance invalidation hop, in one
451
400
  // call. The CDN tier used to be the only one registered here — so `redisTier`,
@@ -457,7 +406,9 @@ export async function startServices(
457
406
  // validated and documented while NOTHING read it — so an app asking for one rung got four,
458
407
  // and one asking for a shared tier got whatever `REDIS_URL` happened to say.
459
408
  const tiers = cacheTiersOf(config);
460
- started.push(startCacheTiers({ env, purge, transport, tiers }));
409
+ started.push(
410
+ startCacheTiers({ env, purge, transport, tiers, supplied: overrides?.cacheTiers }),
411
+ );
461
412
 
462
413
  return {
463
414
  services,
@@ -481,6 +432,7 @@ export async function startServices(
481
432
  presenceTtlMs: bus.presenceTtlMs,
482
433
  purge,
483
434
  purgeDetail: cdn.detail,
435
+ failureStore: overrides?.failureStore,
484
436
  // The same list the boot unwind uses, in the same reverse order, so a service added to the
485
437
  // boot is released by both paths — a second copy of these steps is how one of them came to
486
438
  // release three things and the other four. A stop that fails says so, unlike that unwind:
@@ -0,0 +1,111 @@
1
+ // Single responsibility: the storage disk a boot installs — s3 when `S3_ENDPOINT` names one, the
2
+ // embedded local disk otherwise — and the two refusals that must come before the first upload
3
+ // rather than after it. Split from `runtime-services.ts` at its 500-line ceiling.
4
+
5
+ // why: Bun has no `mkdir`; the embedded root must exist before the disk is handed out.
6
+ import { mkdirSync } from 'node:fs';
7
+ import { isLocal, renderThrowable, resolveEnvironment } from '@ultimat3/core';
8
+ import { configuredHttp, defineHttpConfig } from '@ultimat3/http';
9
+ import type { Storage } from '@ultimat3/storage';
10
+ import { defineStorage, localDriver, s3Driver, usesDevStorageSecret } from '@ultimat3/storage';
11
+ import type { StorageDriver } from '@ultimat3/storage/adapter';
12
+ import { LocalDiskUnsafeError, StorageUnwritableError } from './errors';
13
+ import type { DevServices, Env } from './runtime-bindings';
14
+ import { s3PathStyleOf } from './runtime-s3-path-style';
15
+
16
+ const FILE_SCHEME = 'file://';
17
+
18
+ /**
19
+ * The most one request to this server carries — `http.maxRequestBodyBytes` as the server resolves
20
+ * it, read at each signing because the boot builds its disk before the app's `configureHttp` runs.
21
+ * Handed to `localDriver({ maxRequestBytes })`, so a single-PUT grant this server would refuse
22
+ * with `X_BODY_TOO_LARGE` is refused when it is signed instead, naming `grantMultipart`.
23
+ */
24
+ export const servedRequestCeiling = (): number =>
25
+ defineHttpConfig({ ...configuredHttp(), rateLimit: { scope: 'process' } }).maxRequestBodyBytes;
26
+
27
+ /**
28
+ * The storage disk this process will use.
29
+ *
30
+ * An `external` binding now reaches `s3Driver`. It used to fall through to a LOCAL directory —
31
+ * `S3_ENDPOINT` selected a different root and nothing else, so every deployment that configured
32
+ * object storage silently wrote to a container-local disk, and every upload was destroyed by the
33
+ * next restart while the configured bucket stayed empty. Nothing failed; the files just went
34
+ * nowhere.
35
+ *
36
+ * The embedded branch is also where a hardened container died. `mkdirSync` on a
37
+ * `readOnlyRootFilesystem` throws a bare `EROFS` from inside Bun's fs, with no code, no fix and no
38
+ * mention of storage — the demo CrashLooped 22 times on it. A read-only filesystem is a normal way
39
+ * to run a container, so this reports what to do instead of what went wrong.
40
+ */
41
+ export function startStorage(services: DevServices, env: Env, override?: StorageDriver): Storage {
42
+ // First arm, not a branch beside the two below: `runtime.ts` handing the boot a driver has
43
+ // already answered "which disk", and re-deriving one from `S3_ENDPOINT` would be a second answer.
44
+ // Registered under the driver's own name — its signed URLs hang off that key (`defineStorage`).
45
+ if (override !== undefined) {
46
+ return defineStorage({ disks: { [override.name]: override }, default: override.name });
47
+ }
48
+ const binding = services.storage;
49
+
50
+ if (binding.mode === 'external') {
51
+ const bucket = env['S3_BUCKET'] ?? '';
52
+ if (bucket === '') {
53
+ throw new StorageUnwritableError(
54
+ `S3_ENDPOINT is set to ${binding.url} but S3_BUCKET is empty, so there is no disk to write to`,
55
+ 'set S3_BUCKET to the bucket name, or unset S3_ENDPOINT to use the embedded disk',
56
+ );
57
+ }
58
+ return defineStorage({
59
+ disks: {
60
+ object: s3Driver({
61
+ bucket,
62
+ endpoint: binding.url,
63
+ ...(env['S3_REGION'] === undefined ? {} : { region: env['S3_REGION'] }),
64
+ forcePathStyle: s3PathStyleOf(env),
65
+ }),
66
+ },
67
+ default: 'object',
68
+ });
69
+ }
70
+
71
+ const root = binding.url.slice(FILE_SCHEME.length);
72
+ // The embedded disk is what this branch falls back to whenever `S3_ENDPOINT`/`S3_BUCKET` are
73
+ // unset — including in `production` and `staging`, where an unset `STORAGE_SIGNING_SECRET` means
74
+ // every signed upload grant is minted with the string published in this repo, and
75
+ // `acceptSignedUpload` trusts a signed constraint over the app's own `uploadPolicy`.
76
+ //
77
+ // `localDriver` refuses that at construction on its own (`X_ENV_MISSING`). Pre-empted here so
78
+ // the message names the STORAGE CHOICE and both ways out, rather than arriving as "a secret is
79
+ // missing" from a helper the operator never configured. Not an outright ban on the local disk in
80
+ // production: a single-node Compose deploy on a mounted volume WITH a real secret is a rung on
81
+ // the scale ladder, and refusing it would be a deploy-shape decision, not a security fix.
82
+ // `{ env }` on ALL THREE, never the ambient `process.env`: this function is HANDED the boot's
83
+ // environment and reads `S3_BUCKET` off it one branch above, so a guard asking a second source
84
+ // could answer `development` for a process booting as `production` — or, with
85
+ // `usesDevStorageSecret({ env })` left bare, refuse a boot whose own env carries a real
86
+ // `STORAGE_SIGNING_SECRET` because the PROCESS does not. Which environment, whether a secret
87
+ // exists, and the name the message prints are one question about one table.
88
+ // `fallback: 'production'` on both, the reading `localDriver` itself takes: a boot that names no
89
+ // environment is not a development one, and this message beats the driver's to it.
90
+ if (!isLocal({ env, fallback: 'production' }) && usesDevStorageSecret({ env })) {
91
+ throw new LocalDiskUnsafeError({
92
+ environment: resolveEnvironment({ env, fallback: 'production' }),
93
+ root,
94
+ });
95
+ }
96
+ try {
97
+ mkdirSync(root, { recursive: true });
98
+ } catch (cause) {
99
+ const detail = renderThrowable(cause);
100
+ throw new StorageUnwritableError(
101
+ `the embedded storage disk needs ${root} and it could not be created: ${detail}`,
102
+ `mount a writable volume at ${root}, or set S3_ENDPOINT and S3_BUCKET to use object storage instead`,
103
+ );
104
+ }
105
+ // The guard three lines up reads `env`; so must the disk it guards. Otherwise the boot's
106
+ // environment decides whether signing is allowed and the process's decides what key is used.
107
+ // `maxRequestBytes`: a signed PUT lands on THIS server, so a grant it could never accept in one
108
+ // request is refused at signing, naming the multipart grant.
109
+ const disk = localDriver({ root, env, maxRequestBytes: servedRequestCeiling });
110
+ return defineStorage({ disks: { local: disk }, default: 'local' });
111
+ }
@@ -9,7 +9,7 @@ import { jsonResponse, NO_STORE } from '@ultimat3/http';
9
9
  import type { Storage } from '@ultimat3/storage';
10
10
  import {
11
11
  acceptSignedPart,
12
- acceptSignedUpload,
12
+ acceptSignedUploadStream,
13
13
  DEFAULT_MAX_UPLOAD_BYTES,
14
14
  DEFAULT_SIGNED_URL_BASE,
15
15
  objectNotFound,
@@ -59,22 +59,24 @@ async function acceptUpload(
59
59
  constraints.maxBytes === undefined ? DEFAULT_MAX_UPLOAD_BYTES : constraints.maxBytes,
60
60
  1,
61
61
  );
62
- const read = await readWithinLimit(request.raw.body, ceiling);
63
- if ('over' in read) throw tooLarge(constraints.key, read.over, ceiling);
64
-
65
62
  // A part URL (`signPart` on a local disk) writes one part into its open session — never the
66
63
  // object, which `completeUpload` assembles. The signature says which, so the one PUT route
67
- // serves both: a second route on the same path could only shadow this one.
64
+ // serves both: a second route on the same path could only shadow this one. A part is bounded by
65
+ // its own signed size, so it is read whole.
68
66
  if (constraints.part !== undefined) {
67
+ const read = await readWithinLimit(request.raw.body, ceiling);
68
+ if ('over' in read) throw tooLarge(constraints.key, read.over, ceiling);
69
69
  const part = await acceptSignedPart({ url, disk, orgId, bytes: read.bytes });
70
70
  return jsonResponse(part, { status: 200 });
71
71
  }
72
72
 
73
- const stored = await acceptSignedUpload({
73
+ // STREAMED to the disk: memory per upload is the sniff window, never the body. A 2 GB grant
74
+ // used to be 2 GB of this process's heap before the first byte reached the disk.
75
+ const stored = await acceptSignedUploadStream({
74
76
  url,
75
77
  disk,
76
78
  orgId,
77
- bytes: read.bytes,
79
+ body: request.raw.body,
78
80
  declaredContentType: request.header('content-type') ?? undefined,
79
81
  policy: uploadPolicy({
80
82
  maxBytes: ceiling,
@@ -192,10 +192,16 @@ export async function readStorageObject(
192
192
  await assertVariantCurrent(driver, input.disk, key);
193
193
  const object = await driver.stat(key);
194
194
  if (object === undefined) throw objectNotFound(input.disk, key);
195
+ // Pinned to the revision the headers are built from: an overwrite between the stat and the read
196
+ // is `X_STORAGE_OBJECT_CHANGED`, never new bytes under the old ETag and length. An object whose
197
+ // disk knows no etag is read unpinned — there is nothing to pin it to.
198
+ const pin = object.etag === '' ? undefined : { etag: object.etag };
195
199
  return {
196
200
  object,
197
201
  open: async (range) =>
198
- range === undefined ? driver.stream(key) : driver.streamRange(key, [range.start, range.end]),
202
+ range === undefined
203
+ ? driver.stream(key, pin)
204
+ : driver.streamRange(key, [range.start, range.end], pin),
199
205
  };
200
206
  }
201
207
 
package/src/serve-boot.ts CHANGED
@@ -147,7 +147,10 @@ async function bootRoles(boot: {
147
147
  adoptPrebuiltStyles(options.root);
148
148
  const bootBuilds = watchBootBuilds();
149
149
  // Importing the app's modules IS the registration: every route, action and job below is
150
- // whatever this call put in the registries — for THIS role (`role-load.ts`).
150
+ // whatever this call put in the registries — for THIS role (`role-load.ts`). Every role imports
151
+ // the image's prebuilt registry when it has one that is the app on disk (`x build --target
152
+ // prebuilt`) — a worker its background subset — and scans only when it has not: the scan is
153
+ // what grew a pod's start with the app's file count.
151
154
  const loaded = await loadAppForRole(options.root, role);
152
155
  // A module that would not import registered nothing — its routes, actions, policies and jobs
153
156
  // are simply absent — so each is logged with its own cause, and then the role refuses to serve.
@@ -162,13 +165,14 @@ async function bootRoles(boot: {
162
165
  const appConfig = await loadAppConfig(options.root);
163
166
  acquired.push(await armRowSecurity(rowSecurityDeclared(appConfig), { embedded }));
164
167
  // `failureCapture.enabled`: a 5xx keeps a replayable bundle for `x repro` (off by default).
165
- acquired.push(armFailureCapture(appConfig));
168
+ acquired.push(armFailureCapture(appConfig, { store: runtime.failureStore }));
166
169
  // After the app's modules: an app swaps the store at import time, after `startServices`.
167
170
  warnIfIdempotencyProcessScoped();
168
171
  const buildId = await buildIdFor(options, role);
169
172
  // Before the first socket opens: everything above this line fails loudly into the container's
170
173
  // own logs, everything below it is a served request, a claimed job or a routed frame.
171
- configureReporting(options.env, buildId);
174
+ // Released with the boot, so a second boot in this process starts from the app's reporter alone.
175
+ acquired.push(configureReporting(options.env, buildId));
172
176
  // Only the web role serves pages, so only it builds islands and assembles a route table: a
173
177
  // worker, scheduler, sync or replicator pod compiled every island of the app on every boot for
174
178
  // nothing it would ever serve (plan 101, slice 12 e). The MODULE is the web role's as well —
@@ -183,7 +187,7 @@ async function bootRoles(boot: {
183
187
  // Islands and stylesheets are the image build's to make (`x build --target prebuilt`). A role
184
188
  // that made either here served correctly and paid for it — seconds of CPU and a compiler's
185
189
  // memory, on every start of every replica — so it says so once, with the Dockerfile line.
186
- reportBootBuilds(role, bootBuilds(web?.islandsBuilt));
190
+ reportBootBuilds(role, bootBuilds(web?.islandsBuilt), options.env);
187
191
  const port = options.port ?? portFromEnv(options.env);
188
192
  // An in-process caller asking for an ephemeral app port is a test, and a test that grabbed the
189
193
  // fixed 9090 would fail the next suite to boot beside it. An environment that names the port
@@ -2,5 +2,8 @@
2
2
  // `@ultimat3/cli` barrel is 1,349 modules — every command, every template, the e2e driver — and a
3
3
  // production process that booted through it loaded all of them to call one function.
4
4
 
5
+ // The type `apps/<app>/runtime.ts` is checked against (`satisfies RuntimeOverrides`). Type-only:
6
+ // erased, so the serve graph loads nothing for it.
7
+ export type { PortValues, RuntimeOverrides } from './runtime-overrides';
5
8
  export { runRole } from './serve';
6
9
  export type { MigratedApp, ServedApp, ServeOptions, StartedApp } from './serve-types';