@ultimat3/cli 30.8.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 +2 -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 +48 -2
  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 +31 -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 +69 -56
  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
@@ -0,0 +1,117 @@
1
+ // Where this boot honours each `ADAPTER_PORTS` row: its installer and its undo, or the module that
2
+ // reads it as a value. Typed `PortBindings`, so a row core adds is a build error HERE until it is
3
+ // bound.
4
+
5
+ import {
6
+ installAuthLimiters,
7
+ installAuthServerStore,
8
+ installTotpReplay,
9
+ } from '@ultimat3/auth/adapter';
10
+ import type { PgExecutor } from '@ultimat3/core';
11
+ import { installAuditSink, installErrorReporter } from '@ultimat3/core/adapter';
12
+ import { installSearchIndex } from '@ultimat3/entity/adapter';
13
+ import { installRateLimitStore } from '@ultimat3/http/adapter';
14
+ import { installMailDriver } from '@ultimat3/mail/adapter';
15
+ import { postgresDeliveryLedger } from '@ultimat3/notify';
16
+ import type { NotifyStores } from '@ultimat3/notify/adapter';
17
+ import { installNotifyStores, installSmsTransport } from '@ultimat3/notify/adapter';
18
+ import { installUploadScanner } from '@ultimat3/storage/adapter';
19
+ import { BOOT_PORT_BINDINGS, QUEUE_PORT_BINDINGS } from './runtime-port-bindings-queue';
20
+ import type { PortBindings } from './runtime-ports';
21
+
22
+ /** Every row, bound. Pure data plus closures: installing happens only in `installPorts`. */
23
+ export const PORT_BINDINGS: PortBindings = {
24
+ aiGateway: {
25
+ phase: 'services',
26
+ // Imported only when supplied: most apps run no model, and no role should load `@ultimat3/ai`.
27
+ install: async (gateway) => (await import('@ultimat3/ai/adapter')).installAiGateway(gateway),
28
+ },
29
+ auditSink: { phase: 'services', install: (sink) => installAuditSink(sink) },
30
+ authLimiter: {
31
+ phase: 'services',
32
+ install: (factory) => installAuthLimiters(factory),
33
+ },
34
+ // Installed only when supplied: unset, auth's own slot answers its env default — Postgres over
35
+ // the ambient pool, the pool this boot installed (`runtime-queue.ts`'s `setDbClient`).
36
+ authServerStore: { phase: 'services', install: (store) => installAuthServerStore(store) },
37
+ cacheTiers: { phase: 'read', at: 'runtime-cache.ts, each replacing the rung of its own name' },
38
+ clock: BOOT_PORT_BINDINGS.clock,
39
+ // Imported only when supplied, for `aiGateway`'s reason.
40
+ embedder: {
41
+ phase: 'services',
42
+ install: async (embedder) => (await import('@ultimat3/ai/adapter')).installAiEmbedder(embedder),
43
+ },
44
+ // Before `loadApp`; `serve-env.ts`'s `configureReporting` later chains its `SENTRY_DSN`
45
+ // transport in a frame above it, so this counts as the app's reporter there.
46
+ errorReporter: { phase: 'services', install: (reporter) => installErrorReporter(reporter) },
47
+ eventBus: QUEUE_PORT_BINDINGS.eventBus,
48
+ failureStore: { phase: 'read', at: 'failure-capture-boot.ts, while failureCapture is on' },
49
+ idempotencyStore: QUEUE_PORT_BINDINGS.idempotencyStore,
50
+ images: { phase: 'read', at: 'serve-web.ts, the /media/* transform' },
51
+ isrStore: { phase: 'read', at: 'serve-web.ts, the ISR controller' },
52
+ jobs: QUEUE_PORT_BINDINGS.jobs,
53
+ mail: {
54
+ phase: 'services',
55
+ install: (driver) => installMailDriver(driver),
56
+ },
57
+ mcpConfirmationStore: {
58
+ phase: 'services',
59
+ // Imported only when supplied, for `aiGateway`'s reason: most roles load no MCP module, and
60
+ // unset, mcp's own slot answers its env default (Postgres over the ambient pool).
61
+ install: async (store) =>
62
+ (await import('@ultimat3/mcp/adapter')).installConfirmationStore(store),
63
+ },
64
+ meterStore: QUEUE_PORT_BINDINGS.meterStore,
65
+ notifyStores: {
66
+ phase: 'services',
67
+ // Always a value: `startServices` fills a missing ledger with Postgres over its pool.
68
+ install: (stores) => installNotifyStores(stores),
69
+ },
70
+ outboxStore: { phase: 'read', at: 'runtime-queue.ts, behind the jobs facade with the jobs port' },
71
+ purge: { phase: 'read', at: 'runtime-cache.ts, the cdn tier' },
72
+ pushSubscriptionStore: { phase: 'read', at: 'runtime-push.ts, while pwa.vapid is set' },
73
+ rateLimitStore: {
74
+ phase: 'services',
75
+ install: (store) => installRateLimitStore(store),
76
+ },
77
+ scrapeDriver: {
78
+ phase: 'services',
79
+ // Imported only when supplied, for `aiGateway`'s reason: a browser driver is a scraping app's.
80
+ install: async (driver) =>
81
+ (await import('@ultimat3/scraping/adapter')).installScrapeDriver(driver),
82
+ },
83
+ // Installed only when supplied: unset, entity's own slot answers `postgresSearchIndex()`.
84
+ searchIndex: { phase: 'services', install: (index) => installSearchIndex(index) },
85
+ secretSource: BOOT_PORT_BINDINGS.secretSource,
86
+ semanticCache: {
87
+ phase: 'services',
88
+ install: async (factory) =>
89
+ (await import('@ultimat3/ai/adapter')).installSemanticCache(factory),
90
+ },
91
+ // Installed only when supplied: unset, notify's own slot answers memory locally, a refusal elsewhere.
92
+ smsTransport: { phase: 'services', install: (transport) => installSmsTransport(transport) },
93
+ storage: { phase: 'read', at: 'runtime-storage-boot.ts, the default disk' },
94
+ totpReplay: {
95
+ phase: 'services',
96
+ install: (guard) => installTotpReplay(() => guard),
97
+ },
98
+ transport: { phase: 'read', at: 'runtime-bus.ts, which installs the channel transport it dials' },
99
+ // Installed only when supplied: unset, storage's slot answers no scanner and nothing is scanned.
100
+ uploadScanner: { phase: 'services', install: (scanner) => installUploadScanner(scanner) },
101
+ };
102
+
103
+ /**
104
+ * The `notifyStores` value with zero config: a booted app has a database, so a MISSING ledger is
105
+ * Postgres over the boot's pool — an app's own ledger, inbox, preferences and digest are never
106
+ * replaced. `x_notify_deliveries` is applied every boot (`framework-schema.ts`) and swept hourly
107
+ * (`runtime-purge.ts`). Notify's own default (memory in development/test, `X_NOTIFY_STORE_MISSING`
108
+ * elsewhere) stays the net for a process no boot installed into. Here, beside the binding, so the
109
+ * serving graph pays no module for it.
110
+ */
111
+ export function notifyStoresWithLedger(
112
+ supplied: NotifyStores | undefined,
113
+ executor: PgExecutor,
114
+ ): NotifyStores {
115
+ if (supplied?.ledger !== undefined) return supplied;
116
+ return { ...supplied, ledger: postgresDeliveryLedger({ executor }) };
117
+ }
@@ -0,0 +1,164 @@
1
+ // Every `ADAPTER_PORTS` row bound to where this boot honours it, and the ONE install loop over the
2
+ // rows (`installPorts`). `PortBindings` is keyed by `AdapterPortName`, so a row core adds without a
3
+ // binding is a build error (TS2741). Which value fills a slot — `runtime.ts`'s, else the env
4
+ // default — is the caller's one `suppliedOr`.
5
+
6
+ import { ADAPTER_PORT_NAMES, type AdapterPortName } from '@ultimat3/core';
7
+ import type { PortValues } from './runtime-overrides';
8
+
9
+ /** A port this boot fills: the subset of `ADAPTER_PORTS` that is a `RuntimeOverrides` field. */
10
+ export type WiredPort = keyof PortValues;
11
+
12
+ /** A row with no `RuntimeOverrides` field yet — see `PendingBinding`. */
13
+ export type PendingPort = Exclude<AdapterPortName, WiredPort>;
14
+
15
+ /** What an install answers: the undo, run newest first by the boot's own unwind. */
16
+ export type PortRelease = () => void | Promise<void>;
17
+
18
+ /** The values one phase chose — each one `runtime.ts`'s field or the env default, never both. */
19
+ export type ChosenPorts = { readonly [P in WiredPort]?: PortValues[P] | undefined };
20
+
21
+ /**
22
+ * Installed by the loop, in the phase that owns its dependencies: `boot` ports first, before
23
+ * `app.config.ts` evaluates (its `installSecrets()` asks the secret source); `queue` ports by
24
+ * `startQueue` (`x jobs` boots exactly those); `services` ports by `startServices`, before `loadApp`.
25
+ */
26
+ export interface InstalledBinding<P extends WiredPort> {
27
+ readonly phase: InstallPhase;
28
+ /**
29
+ * May be async: an adapter most apps never swap (`aiGateway`, `scrapeDriver`) is imported only
30
+ * when `runtime.ts` supplies one, so no serving role pays for a package it does not use.
31
+ */
32
+ readonly install: (value: PortValues[P]) => PortRelease | Promise<PortRelease>;
33
+ }
34
+
35
+ export type InstallPhase = 'boot' | 'queue' | 'services';
36
+
37
+ /** Read as a value where it is used, never installed ambiently: `at` names that reader. */
38
+ export interface ReadBinding {
39
+ readonly phase: 'read';
40
+ readonly at: string;
41
+ }
42
+
43
+ /**
44
+ * A row with no `RuntimeOverrides` field yet, because the package owning it exposes no installer
45
+ * this boot can call. Stated rather than faked: a field nothing reads is the defect this seam
46
+ * exists to end. `X_ADAPTER_PORT_INCOMPLETE` (slice 21 part B) reports it until `owner` ships one.
47
+ */
48
+ export interface PendingBinding {
49
+ readonly phase: 'pending';
50
+ readonly owner: string;
51
+ }
52
+
53
+ export type WiredBindings = { readonly [P in WiredPort]: InstalledBinding<P> | ReadBinding };
54
+ export type PendingBindings = { readonly [P in PendingPort]: PendingBinding };
55
+ /** Complete over `AdapterPortName`: a new row is a missing key, a removed one an excess key. */
56
+ export type PortBindings = WiredBindings & PendingBindings;
57
+
58
+ /** Every `RuntimeOverrides` port names a real row — a stray key is a build error here. */
59
+ const noStrayPorts: [Exclude<WiredPort, AdapterPortName>] extends [never] ? true : never = true;
60
+ void noStrayPorts;
61
+
62
+ /** The wired keys as a value, so the loop can narrow a row's name. Complete by its type. */
63
+ const WIRED: { readonly [P in WiredPort]: true } = {
64
+ aiGateway: true,
65
+ auditSink: true,
66
+ authLimiter: true,
67
+ authServerStore: true,
68
+ cacheTiers: true,
69
+ clock: true,
70
+ embedder: true,
71
+ errorReporter: true,
72
+ eventBus: true,
73
+ failureStore: true,
74
+ idempotencyStore: true,
75
+ images: true,
76
+ isrStore: true,
77
+ jobs: true,
78
+ mail: true,
79
+ mcpConfirmationStore: true,
80
+ meterStore: true,
81
+ notifyStores: true,
82
+ outboxStore: true,
83
+ purge: true,
84
+ pushSubscriptionStore: true,
85
+ rateLimitStore: true,
86
+ scrapeDriver: true,
87
+ searchIndex: true,
88
+ secretSource: true,
89
+ semanticCache: true,
90
+ smsTransport: true,
91
+ storage: true,
92
+ totpReplay: true,
93
+ transport: true,
94
+ uploadScanner: true,
95
+ };
96
+
97
+ /** Whether a row is a `RuntimeOverrides` field — the scaffold marks the rest as pending. */
98
+ export const isWired = (port: string): port is WiredPort => Object.hasOwn(WIRED, port);
99
+
100
+ /** Generic so the binding's parameter and the chosen value are the SAME port's type. */
101
+ function installOne<P extends WiredPort>(
102
+ binding: WiredBindings[P],
103
+ port: P,
104
+ phase: InstallPhase,
105
+ chosen: ChosenPorts,
106
+ ): PortRelease | Promise<PortRelease> | undefined {
107
+ if (binding.phase !== phase) return undefined;
108
+ const value: PortValues[P] | undefined = chosen[port];
109
+ // Absent: a port this phase builds no default for (`notifyStores`, `auditSink`), so the
110
+ // package's own default stands — which is the env default its row documents.
111
+ return value === undefined ? undefined : binding.install(value);
112
+ }
113
+
114
+ /**
115
+ * Install every port `phase` owns, in `ADAPTER_PORTS` order, and answer the releases in that order
116
+ * — the caller's unwind runs them newest first. The ONE place a backend becomes ambient. `bindings`
117
+ * is the full `PORT_BINDINGS`, or one phase's slice where loading the rest would weigh down a light
118
+ * boot (`runtime-port-bindings-queue.ts`).
119
+ */
120
+ export async function installPorts(
121
+ bindings: { readonly [P in WiredPort]?: WiredBindings[P] },
122
+ phase: InstallPhase,
123
+ chosen: ChosenPorts,
124
+ ): Promise<PortRelease[]> {
125
+ const releases: PortRelease[] = [];
126
+ try {
127
+ for (const port of ADAPTER_PORT_NAMES) {
128
+ if (!isWired(port)) continue;
129
+ const binding = bindings[port];
130
+ if (binding === undefined) continue;
131
+ // In order, one at a time: a later port may read an earlier one (the clock before the rest).
132
+ const release = await installOne(binding, port, phase, chosen);
133
+ if (release !== undefined) releases.push(release);
134
+ }
135
+ } catch (error) {
136
+ // A port that would not install (an adapter module that failed to load) must not strand the
137
+ // ones before it: released newest first, each tried, and the install's rejection is the cause.
138
+ for (const release of releases.reverse()) {
139
+ try {
140
+ await release();
141
+ } catch {
142
+ // Cleanup noise never replaces the install failure.
143
+ }
144
+ }
145
+ throw error;
146
+ }
147
+ return releases;
148
+ }
149
+
150
+ /** A port's value, and the default the boot BUILT for it — `undefined` when `runtime.ts` supplied it. */
151
+ export interface Chosen<T, O extends T> {
152
+ readonly value: T;
153
+ readonly own: O | undefined;
154
+ }
155
+
156
+ /**
157
+ * `runtime.ts`'s value, else the env default — built only when needed, and kept apart so the
158
+ * retention sweep expires the boot's own tables and never a store the app handed over.
159
+ */
160
+ export function suppliedOr<T, O extends T>(supplied: T | undefined, build: () => O): Chosen<T, O> {
161
+ if (supplied !== undefined) return { value: supplied, own: undefined };
162
+ const own = build();
163
+ return { value: own, own };
164
+ }
@@ -47,18 +47,20 @@ export const PURGE_TASK_NAME = 'x.purge.hourly';
47
47
  * deletes reservations a retry is still entitled to.
48
48
  *
49
49
  * The auth limiter is absent on purpose: it does not exist yet at boot. `defineAuth` builds it
50
- * through the factory `configureAuthLimiters` installed, and that happens when the app's modules
50
+ * through the `authLimiter` port's factory, and that happens when the app's modules
51
51
  * import — after this. `purgeAuthLimits()` is the seam that reads whatever was built.
52
52
  */
53
53
  export interface RetentionStores {
54
- readonly idempotency: PostgresIdempotencyStore;
55
- readonly rateLimit: PostgresRateLimitStore;
54
+ /** `undefined` when `runtime.ts` supplied the store: the app's backend is the app's to expire. */
55
+ readonly idempotency: PostgresIdempotencyStore | undefined;
56
+ /** `undefined` for `idempotency`'s reason. */
57
+ readonly rateLimit: PostgresRateLimitStore | undefined;
56
58
  /**
57
- * The guard this boot installed through `configureTotpReplay`. Unlike the limiter it takes
58
- * nothing from the app, so it exists here. REQUIRED, or `x_totp_steps` keeps a row per second
59
- * factor for the life of the deployment.
59
+ * The guard this boot built for the `totpReplay` port. Unlike the limiter it takes nothing from
60
+ * the app, so it exists here. Passed whenever the boot built it, or `x_totp_steps` keeps a row
61
+ * per second factor for the life of the deployment; `undefined` when `runtime.ts` supplied one.
60
62
  */
61
- readonly totpReplay: PostgresTotpReplayGuard;
63
+ readonly totpReplay: PostgresTotpReplayGuard | undefined;
62
64
  /**
63
65
  * The bus this boot installed for `step.waitForEvent`. REQUIRED: `x_job_events` takes a row per
64
66
  * publish and `find` only filters an expired one, so a boot that left it out is the table
@@ -85,9 +87,9 @@ export interface RetentionStores {
85
87
 
86
88
  /**
87
89
  * The three notify tables, and no store is in `RetentionStores` — deliberately, and for the
88
- * reason `authTarget` is not either. `setNotifyStores` is an APP's boot line and runs when the
89
- * app's modules import, which is AFTER this install; `framework-schema.ts` says so where it
90
- * applies the DDL "whether or not this boot calls `setNotifyStores`". So the sweep can only ask,
90
+ * reason `authTarget` is not either. The `notifyStores` port is `runtime.ts`'s and the boot builds
91
+ * no default (`framework-schema.ts` applies the DDL whether or not one is supplied). So the sweep
92
+ * can only ask,
91
93
  * per attempt, what is installed now — `purgeNotifyInbox`/`purgeNotifyDeliveries` answer 0 for a
92
94
  * memory store or none at all, which is a boot that made a decision, not a failure.
93
95
  */
@@ -122,7 +124,7 @@ function notifyTargets(retention: InboxRetention): readonly PurgeTarget[] {
122
124
  /**
123
125
  * Read per attempt by the job, and emptied by the disposer `installRetentionSweep` returns: a
124
126
  * sweep left declared after its boot has stopped must not reach through a closed pool. Module
125
- * scope for the reason `setJobDriver` and `configureKdfGate` are — a process has one boot at a
127
+ * scope for the reason the installed job driver and `installKdfGate` are — a process has one boot at a
126
128
  * time, and the registry the job lives in is process-wide too.
127
129
  */
128
130
  let installed: readonly PurgeTarget[] = [];
@@ -141,26 +143,37 @@ const authTarget: PurgeTarget = {
141
143
  purgeExpired: () => purgeAuthLimits(),
142
144
  };
143
145
 
146
+ /** The sweep over a store this boot built, or none when `runtime.ts` supplied it. */
147
+ const own = (target: PurgeTarget | undefined): readonly PurgeTarget[] =>
148
+ target === undefined ? [] : [target];
149
+
144
150
  function retentionTargets(stores: RetentionStores): readonly PurgeTarget[] {
151
+ const { idempotency, rateLimit, totpReplay } = stores;
145
152
  return [
146
- {
147
- name: 'x_idempotency',
148
- purgeExpired: (): Promise<number> => stores.idempotency.purgeExpired(),
149
- },
150
- {
151
- name: 'x_rate_limit',
152
- // The job's clock, not the server's. `last_ms` is written by whichever process took the
153
- // token, so a purge measured against `now()` in Postgres computes a refill from the offset
154
- // between two clocks — and against a frozen one it read 20,000,000 seconds of refill and
155
- // deleted a bucket holding 0 of 4 tokens, which is a free limit reset from the cleanup.
156
- purgeExpired: (nowMs: number): Promise<number> => stores.rateLimit.purgeExpired(nowMs),
157
- },
153
+ ...own(
154
+ idempotency && {
155
+ name: 'x_idempotency',
156
+ purgeExpired: (): Promise<number> => idempotency.purgeExpired(),
157
+ },
158
+ ),
159
+ ...own(
160
+ rateLimit && {
161
+ name: 'x_rate_limit',
162
+ // The job's clock, not the server's. `last_ms` is written by whichever process took the
163
+ // token, so a purge measured against `now()` in Postgres computes a refill from the offset
164
+ // between two clocks — and against a frozen one it read 20,000,000 seconds of refill and
165
+ // deleted a bucket holding 0 of 4 tokens, which is a free limit reset from the cleanup.
166
+ purgeExpired: (nowMs: number): Promise<number> => rateLimit.purgeExpired(nowMs),
167
+ },
168
+ ),
158
169
  authTarget,
159
- {
160
- name: 'x_totp_steps',
161
- // The job's clock: `verifyTotp` derived every step in that table from a process's clock.
162
- purgeExpired: (nowMs: number): Promise<number> => stores.totpReplay.purgeExpired(nowMs),
163
- },
170
+ ...own(
171
+ totpReplay && {
172
+ name: 'x_totp_steps',
173
+ // The job's clock: `verifyTotp` derived every step in that table from a process's clock.
174
+ purgeExpired: (nowMs: number): Promise<number> => totpReplay.purgeExpired(nowMs),
175
+ },
176
+ ),
164
177
  ...notifyTargets(stores.inboxRetention ?? NO_INBOX_RETENTION),
165
178
  // Its own clock, and so no `nowMs`: every instant in that table is the database's.
166
179
  eventsPurgeTarget(stores.events),
@@ -8,7 +8,7 @@
8
8
 
9
9
  import type { AppConfig, PgExecutor } from '@ultimat3/core';
10
10
  import { logger, PWA_PUSH_FIX, pushWired } from '@ultimat3/core';
11
- import type { ResolvedVapidKeys } from '@ultimat3/pwa';
11
+ import type { PushSubscriptionStore, ResolvedVapidKeys } from '@ultimat3/pwa';
12
12
  import type { Env } from './runtime-bindings';
13
13
 
14
14
  /** `pwa.vapid.subject` when this app's boot owes a push runtime, else `undefined`. */
@@ -57,10 +57,14 @@ export async function selectWebPush(
57
57
  };
58
58
  }
59
59
 
60
- /** Install the runtime over the boot's executor; answers its release. */
60
+ /**
61
+ * Install the runtime over the boot's executor; answers its release. `store` is `runtime.ts`'s
62
+ * `pushSubscriptionStore` port; omitted, the Postgres store over the boot's pool.
63
+ */
61
64
  export async function installAppWebPush(
62
65
  selection: PushSelection,
63
66
  executor: PgExecutor,
67
+ store?: PushSubscriptionStore,
64
68
  ): Promise<() => void> {
65
69
  const { installWebPush, postgresPushSubscriptionStore } = await import('@ultimat3/pwa');
66
70
  if (selection.resolved.source === 'development') {
@@ -72,7 +76,7 @@ export async function installAppWebPush(
72
76
  });
73
77
  }
74
78
  return installWebPush({
75
- store: postgresPushSubscriptionStore({ executor }),
79
+ store: store ?? postgresPushSubscriptionStore({ executor }),
76
80
  keys: selection.resolved.keys,
77
81
  subject: selection.subject,
78
82
  pushHosts: selection.pushHosts,
@@ -9,10 +9,6 @@ import {
9
9
  postgresIdempotencyStore,
10
10
  postgresMeterStore,
11
11
  requestDeadlineMs,
12
- resetIdempotency,
13
- resetMeterStore,
14
- setIdempotencyStore,
15
- setMeterStore,
16
12
  } from '@ultimat3/action';
17
13
  import type { PgliteClient, PostgresClient } from '@ultimat3/db';
18
14
  import {
@@ -34,17 +30,15 @@ import {
34
30
  postgresEventBus,
35
31
  postgresJobDriver,
36
32
  postgresOutboxStore,
37
- resetEventBus,
38
- resetJobDriver,
39
33
  resetJobsFacade,
40
- setEventBus,
41
- setJobDriver,
42
34
  setJobsFacade,
43
35
  } from '@ultimat3/jobs';
44
36
  import { applyLockedSchema, ensureSchema, verifySchema } from './framework-schema-apply';
45
37
  import { appExtensions } from './migration-extensions';
46
38
  import type { DevServices } from './runtime-bindings';
47
39
  import type { RuntimeOverrides } from './runtime-overrides';
40
+ import { QUEUE_PORT_BINDINGS } from './runtime-port-bindings-queue';
41
+ import { installPorts, type PortRelease, suppliedOr } from './runtime-ports';
48
42
  import { attachReplica, type ReplicaEnv, replicaUrlFor } from './runtime-replica';
49
43
 
50
44
  /** Both embedded and external clients boot lazily and close explicitly. */
@@ -67,12 +61,13 @@ export interface RunningQueue {
67
61
  /** The `x_job_events` bus a `step.waitForEvent` resumes from. Durable, not per-process. */
68
62
  readonly events: EventBus;
69
63
  /**
70
- * The `x_idempotency` store this boot installed behind `idempotent: true`. Returned for the
71
- * reason `outbox` is: the retention sweep over that table is a ROLE's work, not the queue's,
72
- * and it has to sweep the store that was INSTALLED — a second one built beside it would purge
73
- * on the default window even where this boot had configured another.
64
+ * The `x_idempotency` store this boot BUILT behind `idempotent: true` — `undefined` when
65
+ * `runtime.ts` supplied its own, which is then the app's to expire. Returned for the reason
66
+ * `outbox` is: the retention sweep over that table is a ROLE's work, not the queue's, and it has
67
+ * to sweep the store that was INSTALLED — a second one built beside it would purge on the
68
+ * default window even where this boot had configured another.
74
69
  */
75
- readonly idempotency: PostgresIdempotencyStore;
70
+ readonly idempotency: PostgresIdempotencyStore | undefined;
76
71
  stop(): Promise<void>;
77
72
  }
78
73
 
@@ -157,18 +152,20 @@ async function applySchema(client: DevDbClient, mode: SchemaMode): Promise<void>
157
152
  * one-live-job-per-key index all behave here exactly as in production. A memory queue in dev
158
153
  * would hide every bug this driver exists to make impossible.
159
154
  *
160
- * Three ambient installs, not one, and they go in together because they are one decision:
155
+ * Five ambient installs, not one, and they go in together because they are one decision. Each is
156
+ * a port (`ADAPTER_PORTS`): `runtime.ts`'s value or the default below, installed by the
157
+ * one loop in `runtime-ports.ts` (`PORT_BINDINGS`' `queue` rows).
161
158
  *
162
- * - `setJobDriver` is what `jobDriver()` answers and what a worker claims from.
163
- * - `setJobsFacade` is what `handle.enqueue()` routes through, so an enqueue inside a request's
164
- * transaction STAGES a row that commits or vanishes with the business rows. Without it the
159
+ * - `jobs` is what `jobDriver()` answers and what a worker claims from.
160
+ * - `outboxStore`, behind the facade, is what `handle.enqueue()` routes through, so an enqueue
161
+ * inside a request's transaction STAGES a row that commits or vanishes with the business rows. Without it the
165
162
  * fallback facade publishes straight to the driver, and a job for a transaction that rolled
166
163
  * back still runs. `currentTx()` resolves the executor because a `DbTx` IS a client on the
167
164
  * transaction's own connection, while the `Tx` token `@ultimat3/entity` hands over is not that
168
165
  * object — so the token is a key and the ALS is the lookup.
169
- * - `setEventBus` makes `step.waitForEvent` durable. The memory bus this replaced forgot every
166
+ * - `eventBus` makes `step.waitForEvent` durable. The memory bus this replaced forgot every
170
167
  * pending correlation on restart, which is a job that waits forever.
171
- * - `setIdempotencyStore` makes `idempotent: true` mean it across replicas. The memory default is
168
+ * - `idempotencyStore` makes `idempotent: true` mean it across replicas. The memory default is
172
169
  * one process' worth of keys, so a client retrying `POST /api/payments/charge` after a timeout
173
170
  * lands on a replica that has never seen the key and charges the card a second time.
174
171
  *
@@ -190,46 +187,66 @@ async function startJobs(
190
187
  // Bound to `client`, never the ambient `db()`: the queue and the idempotency reservations stay
191
188
  // on the boot's pool whatever transaction is open.
192
189
  const executor = dbExecutor(() => client);
193
- const driver = overrides?.jobs ?? postgresJobDriver({ executor });
194
- setJobDriver(driver);
195
- const outbox = postgresOutboxStore({
196
- executor,
197
- // The open transaction is a client on its own connection; the `Tx` token is not that object.
198
- txExecutor: () => dbExecutor(() => currentTx() ?? client),
199
- });
200
- setJobsFacade(
201
- outboxJobsFacade({ store: outbox, driver }, () => currentTx() as unknown as Tx | undefined),
190
+ // Built only when `runtime.ts` is silent: the retention sweep expires the boot's own store and
191
+ // never one the app handed over.
192
+ const idempotency = suppliedOr(overrides?.idempotencyStore, () =>
193
+ postgresIdempotencyStore({
194
+ executor,
195
+ // `baseClient`, read per call and never `client`: a transaction's origin is the AMBIENT
196
+ // client `startDb` installed, which is the replicated pair when a standby is configured.
197
+ origin: baseClient,
198
+ // The app's own `requestTimeoutMs`, read per reservation — declared after this boot.
199
+ reclaimAfterMs: requestDeadlineMs,
200
+ }),
202
201
  );
202
+ const idempotencyStore = idempotency.value;
203
+ // Each port: `runtime.ts`'s value, else the env default — one `??`, and nothing else selects.
204
+ const jobs = overrides?.jobs ?? postgresJobDriver({ executor });
205
+ const outboxStore =
206
+ overrides?.outboxStore ??
207
+ postgresOutboxStore({
208
+ executor,
209
+ // The open transaction is a client on its own connection; the `Tx` token is not that object.
210
+ txExecutor: () => dbExecutor(() => currentTx() ?? client),
211
+ });
203
212
  // The open transaction's connection, as the outbox beside it: an answer belongs to the unit of
204
213
  // work that gave it, so a refusal that rolls back never resumes the run waiting on it.
205
214
  //
206
215
  // `wakes` only when the queue in hand is the boot's own `postgresJobDriver`: the wake is an update
207
216
  // of `x_jobs` on this database, and an override driver (Redis) keeps no rows here — its waiters
208
217
  // keep the 30 s poll. Waking, a parked wait's backstop is 15 min instead.
209
- const events = postgresEventBus({
210
- executor: dbExecutor(() => currentTx() ?? client),
211
- wakes: overrides?.jobs === undefined,
212
- });
213
- setEventBus(events);
214
- const idempotency = postgresIdempotencyStore({
215
- executor,
216
- // `baseClient`, read per call and never `client`: a transaction's origin is the AMBIENT client
217
- // `startDb` installed, which is the replicated pair when a standby is configured.
218
- origin: baseClient,
219
- // The app's own `requestTimeoutMs`, read per reservation — it is declared after this boot.
220
- reclaimAfterMs: requestDeadlineMs,
221
- });
222
- setIdempotencyStore(idempotency);
218
+ const eventBus =
219
+ overrides?.eventBus ??
220
+ postgresEventBus({
221
+ executor: dbExecutor(() => currentTx() ?? client),
222
+ wakes: overrides?.jobs === undefined,
223
+ });
223
224
  // `meter:` counters on the boot's pool, never the open transaction: a draw is the caller's
224
225
  // whether or not the business write commits, and one tenant's day is one row on every replica.
225
- setMeterStore(postgresMeterStore({ executor }));
226
+ const meterStore = overrides?.meterStore ?? postgresMeterStore({ executor });
227
+ const releases = await installPorts(QUEUE_PORT_BINDINGS, 'queue', {
228
+ jobs,
229
+ eventBus,
230
+ idempotencyStore,
231
+ meterStore,
232
+ });
233
+ // The outbox port is read here, not installed by the loop: the facade `handle.enqueue()` routes
234
+ // through needs BOTH it and the queue, so an enqueue inside a request's transaction STAGES a row
235
+ // that commits or vanishes with the business rows. The `Tx` token is a key; the ALS holds the client.
236
+ setJobsFacade(
237
+ outboxJobsFacade(
238
+ { store: outboxStore, driver: jobs },
239
+ () => currentTx() as unknown as Tx | undefined,
240
+ ),
241
+ );
242
+ releases.push(resetJobsFacade);
226
243
  return {
227
244
  db: client,
228
- jobs: driver,
229
- outbox,
230
- events,
231
- idempotency,
232
- stop: () => releaseQueue(client, driver, replica),
245
+ jobs,
246
+ outbox: outboxStore,
247
+ events: eventBus,
248
+ idempotency: idempotency.own,
249
+ stop: () => releaseQueue(client, jobs, replica, releases),
233
250
  };
234
251
  }
235
252
 
@@ -247,14 +264,12 @@ async function releaseQueue(
247
264
  db: DevDbClient,
248
265
  jobs: JobDriver | undefined,
249
266
  replica?: PostgresClient,
267
+ releases: readonly PortRelease[] = [],
250
268
  ): Promise<void> {
251
- // The idempotency store goes back to the memory default for the same reason the facade does: it
252
- // holds this client, and the next command in this process would reserve keys over a closed one.
253
- resetIdempotency();
254
- resetMeterStore();
255
- resetJobsFacade();
256
- resetEventBus();
257
- resetJobDriver();
269
+ // Every queue port back to its package default, newest first — the idempotency store, the
270
+ // facade and the bus all hold this client, and the next command in this process would otherwise
271
+ // reserve keys, stage rows or publish over a closed one.
272
+ for (const release of [...releases].reverse()) await release();
258
273
  setDbClient(undefined);
259
274
  await jobs?.close?.();
260
275
  await db.close();
@@ -1,21 +1,21 @@
1
1
  // The `realtime` section for the boot, out of the config `startServices` loads once
2
- // (`app-config-load.ts`). Until 22.0.0 no boot read `enabled`, `transport` or `urlEnv` and
3
- // `NATS_URL` alone decided the bus; the two per-actor caps are read by the `sync` role.
2
+ // (`app-config-load.ts`). `enabled` decides the realtime roles; the two per-actor caps are read by
3
+ // the `sync` role, `maxQueued` by `page-sync.ts` (the page outbox's ceiling, on every document).
4
+ // The bus is not here: `NATS_URL`, or `transport` in `apps/<app>/runtime.ts` (v31).
4
5
 
5
6
  import type { AppConfig, RealtimeConfig } from '@ultimat3/core';
6
7
 
7
8
  /** Core's `defaults()` for the section — the answer for a root with no `app.config.ts`. */
8
9
  export const REALTIME_DEFAULTS: RealtimeConfig = Object.freeze({
9
10
  enabled: true,
10
- transport: 'memory',
11
- urlEnv: undefined,
12
11
  maxSubscriptionsPerActor: undefined,
13
12
  maxSocketsPerActor: undefined,
13
+ maxQueued: undefined,
14
14
  });
15
15
 
16
16
  /**
17
17
  * The section as the boot obeys it — `defineConfig`'s per-key merge, so the boot and the app's own
18
- * config object agree, and a transport nothing builds is core's `X_CONFIG_INVALID`.
18
+ * config object agree.
19
19
  */
20
20
  export const realtimeConfigOf = (config: AppConfig | undefined): RealtimeConfig =>
21
21
  config?.realtime ?? REALTIME_DEFAULTS;