@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
package/src/cmd-verify.ts CHANGED
@@ -2,7 +2,8 @@
2
2
  // same list in the terminal and in --json, and a non-zero exit if any step fails. Green means
3
3
  // shippable (axiom 5): one step list, no second checklist, no CI-only step.
4
4
  //
5
- // `--only <step>[,<step>…]` is the ONE narrowing, decided as D6, and it does not weaken that: the
5
+ // `--only <step>[,<step>…]` is the ONE narrowing, decided as D6 — `--changed` is the same narrowing
6
+ // with the list derived from the diff (`verify-changed.ts`) — and it does not weaken that: the
6
7
  // GATE is the no-flag run, and a narrowed run says `NOT A GATE RUN` in the summary and in `--json` so no
7
8
  // reader of either can take it for one. `--skip` stays refused — it would let a caller drop the
8
9
  // step that was going to fail and still read the output as a whole-tree verdict.
@@ -19,6 +20,7 @@ import type { CommandResult, JsonValue } from './output';
19
20
  import type { ParsedArgs } from './parse';
20
21
  import { flagBool, flagString } from './parse';
21
22
  import { WORKER_CEILING, WORKER_FLOOR } from './test-workers';
23
+ import { changedScope, readChangedRun, withChangedData } from './verify-changed-scope';
22
24
  import { VERIFY_STEPS } from './verify-checks';
23
25
  import { readVerifyFloor } from './verify-floor';
24
26
  import type { VerifyPart } from './verify-merge';
@@ -46,8 +48,14 @@ export const verifyCommand: CliCommand = {
46
48
  // Every reader before the run: an unrunnable flag must be refused in milliseconds, not after
47
49
  // `tsc -b` has spent fourteen seconds on a run the caller cannot use.
48
50
  const workers = readWorkers(ctx.args);
49
- const only = readOnlySteps(ctx.args);
50
- const shard = await readShard(ctx.args, only);
51
+ const onlyFlag = readOnlySteps(ctx.args);
52
+ // `--changed` is `--only` with the list derived from the diff — the same banner, the same
53
+ // `notAGateRun`, and the plan in `data.changed` so a reader sees why each step was chosen.
54
+ const changed = readChangedRun(ctx.args, onlyFlag)
55
+ ? await changedScope({ runner: ctx.runner, root, args: ctx.args })
56
+ : undefined;
57
+ const only = changed === undefined ? onlyFlag : changed.plan.steps.map((step) => step.name);
58
+ const shard = await readShard(ctx.args, onlyFlag);
51
59
  const isolate = flagBool(ctx.args, 'isolate') ? true : undefined;
52
60
  // Either render prints its verdict only when the run ends; the progress on stderr — a line per
53
61
  // finished step, a heartbeat while one runs — is what a cancelled job's log ends on (#589) and
@@ -62,10 +70,14 @@ export const verifyCommand: CliCommand = {
62
70
  ...(only === undefined ? {} : { only }),
63
71
  ...(shard === undefined ? {} : { shard }),
64
72
  ...(isolate === undefined ? {} : { isolate }),
73
+ ...(changed?.tests === undefined
74
+ ? {}
75
+ : { tests: { scope: changed.tests.scope, whole: changed.tests.whole } }),
65
76
  ...progress,
66
77
  }),
67
78
  );
68
- return shard === undefined ? result : withShardData(result, shard);
79
+ const sharded = shard === undefined ? result : withShardData(result, shard);
80
+ return changed === undefined ? sharded : withChangedData(sharded, changed);
69
81
  },
70
82
  };
71
83
 
@@ -36,7 +36,10 @@ function endOfTypeAlias(text: string, from: number): number {
36
36
  for (let i = from; i < text.length; i += 1) {
37
37
  const ch = text[i];
38
38
  if (ch === '{' || ch === '[' || ch === '(' || ch === '<') depth += 1;
39
- else if (ch === '}' || ch === ']' || ch === ')' || ch === '>') depth -= 1;
39
+ // The `>` of `=>` closes nothing: counted, an arrow type drove depth below zero and the alias
40
+ // "ended" at a `;` inside its own braces, leaving the rest to read as code.
41
+ else if (ch === '}' || ch === ']' || ch === ')' || (ch === '>' && text[i - 1] !== '='))
42
+ depth -= 1;
40
43
  else if (ch === ';' && depth <= 0) return i + 1;
41
44
  }
42
45
  return text.length;
@@ -59,6 +59,9 @@ export function renderDiagnostics(report: DbDiagnostics): readonly string[] {
59
59
  });
60
60
  }
61
61
 
62
+ /** The whole `x db diagnostics` budget on an embedded database, its cold boot included. */
63
+ export const EMBEDDED_DIAGNOSTICS_DEADLINE_MS = 30_000;
64
+
62
65
  /**
63
66
  * `startDb`, not `startQueue`: the queue's boot applies the framework tables, and a diagnostic
64
67
  * must write nothing. An embedded database `x dev` holds is refused rather than opened twice:
@@ -87,7 +90,11 @@ export async function runDiagnostics(ctx: CommandContext, root: string): Promise
87
90
  }
88
91
  const started = startDb(services, ctx.env);
89
92
  try {
90
- const report = await dbDiagnostics({ client: started.client, limit });
93
+ // Embedded, the probe IS the boot — a WASM compile and an initdb, 12.6 s cold under coverage —
94
+ // so the 3 s probe wait answered a healthy database X_DB_UNAVAILABLE. A server keeps the default.
95
+ const deadlineMs =
96
+ services.db.mode === 'embedded' ? EMBEDDED_DIAGNOSTICS_DEADLINE_MS : undefined;
97
+ const report = await dbDiagnostics({ client: started.client, limit, deadlineMs });
91
98
  const sections = Object.values(report);
92
99
  return {
93
100
  ok: true,
package/src/dev-boot.ts CHANGED
@@ -5,8 +5,7 @@
5
5
 
6
6
  import { devShellStyle } from '@ultimat3/admin/dev';
7
7
  import type { Role } from '@ultimat3/core';
8
- import { configureTelemetry, noopExporter } from '@ultimat3/core';
9
- import { setStatementObserver } from '@ultimat3/db';
8
+ import { subscribe, subscribeSemconvMetrics } from '@ultimat3/core';
10
9
  import type { OverlayNotice, RequestContext } from '@ultimat3/http';
11
10
  import { asCtx } from '@ultimat3/http';
12
11
  import { loadSignInPath } from './app-auth';
@@ -17,6 +16,7 @@ import { enableReloadTracking } from './app-reload-graph';
17
16
  import { loadAppRuntime } from './app-runtime';
18
17
  import type { DevDashboardInput, DevStatus } from './dev-dashboard';
19
18
  import { devPanels } from './dev-dashboard';
19
+ import { createInvalidationLog } from './dev-dashboard-invalidations';
20
20
  import { declareDevEnvironment, needsDevEnvironmentDeclaration } from './dev-environment';
21
21
  import { createStatementLedger } from './dev-n-plus-one';
22
22
  import type { DevState } from './dev-rebuild';
@@ -128,7 +128,7 @@ export async function startDev(options: StartDevOptions): Promise<DevServer> {
128
128
  true,
129
129
  );
130
130
  // The events binding the boot line reports is the bus the runtime chose, read off it.
131
- const services = withRealtimeEvents(resolved, env, runtime.realtime);
131
+ const services = withRealtimeEvents(resolved, env, appRuntime?.transport !== undefined);
132
132
  // `serve.ts`'s `releaseBoot` shape: everything acquired from here on is released, newest first,
133
133
  // if the boot throws — a failed `x dev` left PGlite holding `.x/pgdata` for the retry to meet.
134
134
  const acquired: (() => void | Promise<void>)[] = [() => runtime.stop()];
@@ -148,23 +148,36 @@ async function bootDev(
148
148
  appRuntime: RuntimeOverrides | undefined,
149
149
  ): Promise<DevServer> {
150
150
  // Installed before the app loads, so a span opened during registration is already recorded.
151
- // Tracing is always on in the framework and free until an exporter is configured; `x dev` is
152
- // what configures one, which is the whole reason `/_x/timeline` has anything to draw.
151
+ // Tracing is always on in the framework and free until something subscribes to `span.end`;
152
+ // `x dev`'s recorder is that subscriber, which is the whole reason `/_x/timeline` has anything.
153
153
  const traces = createTraceRecorder();
154
- configureTelemetry({ exporter: traces.exporter });
154
+ const unsubscribeTraces = subscribe('span.end', (event) => traces.exporter.export(event.payload));
155
155
  acquired.push(() => {
156
- configureTelemetry({ exporter: noopExporter });
156
+ unsubscribeTraces();
157
157
  traces.reset();
158
158
  });
159
- // Installed at the same moment and for the same reason: an observer is the single switch that
160
- // turns statement instrumentation on at all (`@ultimat3/db`'s `observe.ts`), so the timeline's
161
- // SQL rows and the repeat counts arrive together rather than through two toggles. `serve.ts`
162
- // installs neither — a production process pays the one `undefined` branch the seam costs
163
- // uninstalled, and nothing more (axiom 6).
159
+ // Subscribed at the same moment and for the same reason: the timeline's SQL rows and the repeat
160
+ // counts arrive together. A subscriber, never a slot — the app's own `db.statement` listeners
161
+ // hear the same events beside it. The production boot subscribes ONE: the semconv histograms
162
+ // (`subscribeSemconvMetrics`), so every statement there pays a dispatch, an event object and a
163
+ // histogram record — never this ledger, which keeps every statement's text.
164
164
  const statements = createStatementLedger();
165
- setStatementObserver(statements.observer);
165
+ const unsubscribeStatements = subscribe('db.statement', (event) =>
166
+ statements.observer.onStatement(event.payload),
167
+ );
168
+ // The semconv histograms (`db_client_operation_duration_seconds`, …) on `x dev`'s `/metrics` too,
169
+ // so a dashboard built against dev reads the series production exports.
170
+ const unsubscribeMetrics = subscribeSemconvMetrics();
171
+ // The `/_x` cache panel's history: the cache keeps no log of its own, the panel subscribes one.
172
+ const invalidations = createInvalidationLog();
173
+ const unsubscribeInvalidations = subscribe('cache.invalidate', (event) =>
174
+ invalidations.record(event.payload),
175
+ );
166
176
  acquired.push(() => {
167
- setStatementObserver(undefined);
177
+ unsubscribeInvalidations();
178
+ invalidations.reset();
179
+ unsubscribeMetrics();
180
+ unsubscribeStatements();
168
181
  statements.reset();
169
182
  });
170
183
  // ONE load at boot, the same call the rebuild below makes: the manifest and the findings are
@@ -188,7 +201,7 @@ async function bootDev(
188
201
  }),
189
202
  );
190
203
  // ON in `x dev` whatever `app.config.ts` says: a 5xx here is one `x repro <requestId>` away.
191
- acquired.push(armFailureCapture(appConfig, { force: true }));
204
+ acquired.push(armFailureCapture(appConfig, { force: true, store: runtime.failureStore }));
192
205
  // The manifest's build id is a content hash of every fact below it, so a dev document's
193
206
  // `x-ultimate-build` header names the exact shape the client was served against. Pinned at
194
207
  // boot on purpose: the header is handed to the HTTP config and the render modes once, and a
@@ -216,6 +229,7 @@ async function bootDev(
216
229
  }),
217
230
  traces,
218
231
  statements,
232
+ invalidations,
219
233
  ...envOf(options.env),
220
234
  };
221
235
  const panels = devPanels(dashboard).map((panel) => panel.key);
@@ -0,0 +1,43 @@
1
+ // The `/_x` cache panel's log: every `cache.invalidate` event this process emitted, newest first,
2
+ // bounded. A bus subscriber `x dev` installs at boot — the cache package keeps no ring buffer of
3
+ // its own (`X_INSTRUMENT_SLOT_FORBIDDEN`), so the one panel that reads the history holds it.
4
+
5
+ import type { InvalidationFact } from '@ultimat3/admin/dev';
6
+ import type { CacheInvalidateEvent, Clock } from '@ultimat3/core';
7
+ import { finiteCount, systemClock } from '@ultimat3/core';
8
+
9
+ /** The panel shows recent busts; it does not page through history. The cache's old log's figure. */
10
+ const DEFAULT_LIMIT = 100;
11
+
12
+ export interface InvalidationLog {
13
+ /** Feed it every bust: `subscribe('cache.invalidate', (e) => log.record(e.payload))`. */
14
+ record(event: CacheInvalidateEvent): void;
15
+ /** Newest first, a copy. */
16
+ facts(): readonly InvalidationFact[];
17
+ reset(): void;
18
+ }
19
+
20
+ export function createInvalidationLog(
21
+ options: { readonly limit?: number; readonly clock?: Clock } = {},
22
+ ): InvalidationLog {
23
+ const limit = finiteCount('createInvalidationLog', 'limit', options.limit ?? DEFAULT_LIMIT, 1);
24
+ const clock = options.clock ?? systemClock;
25
+ let log: InvalidationFact[] = [];
26
+ return {
27
+ record(event) {
28
+ log.unshift({
29
+ at: clock.now().toISOString(),
30
+ tags: event.tags,
31
+ busted: event.busted,
32
+ // The span active when the bust was ASKED for, stamped by the cache at the call — the
33
+ // subscriber runs inside the cache's own span, whose name would be every row's source.
34
+ source: event.source ?? 'cache',
35
+ });
36
+ if (log.length > limit) log.length = limit;
37
+ },
38
+ facts: () => [...log],
39
+ reset() {
40
+ log = [];
41
+ },
42
+ };
43
+ }
@@ -22,7 +22,6 @@ import {
22
22
  devDashboard,
23
23
  readOnlySql,
24
24
  } from '@ultimat3/admin/dev';
25
- import { recentInvalidations } from '@ultimat3/cache';
26
25
  import type { Role } from '@ultimat3/core';
27
26
  import type { Route, UltimateRequest } from '@ultimat3/http';
28
27
  import { jsonResponse } from '@ultimat3/http';
@@ -33,6 +32,7 @@ import type { Manifest } from '@ultimat3/manifest';
33
32
  import { appManifest, readAppManifest } from './app-manifest';
34
33
  import { appBoundaryFindings } from './boundary-findings';
35
34
  import { assertSameOrigin, hostRefusal, SQL_BODY, sqlOnGet } from './dev-dashboard-guard';
35
+ import type { InvalidationLog } from './dev-dashboard-invalidations';
36
36
  import { mailTemplateFacts } from './dev-mail-templates';
37
37
  import type { StatementLedger } from './dev-n-plus-one';
38
38
  import { devPolicyMatrix } from './dev-policy';
@@ -60,8 +60,10 @@ export interface DevDashboardInput {
60
60
  readonly env?: string | undefined;
61
61
  /** The spans this process recorded. Absent when `x dev` did not install the exporter. */
62
62
  readonly traces?: TraceRecorder | undefined;
63
- /** The statement shapes this process counted. Absent when `x dev` did not install the observer. */
63
+ /** The statement shapes this process counted. Absent when `x dev` did not subscribe a ledger. */
64
64
  readonly statements?: StatementLedger | undefined;
65
+ /** The busts this process emitted. Absent when `x dev` did not subscribe a log. */
66
+ readonly invalidations?: InvalidationLog | undefined;
65
67
  }
66
68
 
67
69
  /** `MailMessage.locale` is non-optional in `@ultimat3/mail`, so the panel never has to guess. */
@@ -101,18 +103,6 @@ async function manifestFact(root: string): Promise<ManifestFact> {
101
103
  return { emitted, committed: committed ?? null, diff: manifestDiff(emitted, committed) };
102
104
  }
103
105
 
104
- /**
105
- * `@ultimat3/cache` keeps the report of every `invalidateTags` fan-out; the panel reads it back
106
- * as its log. Only the shape differs — the cache owns the facts, /_x owns the rendering.
107
- */
108
- const invalidationFacts = (): readonly InvalidationFact[] =>
109
- recentInvalidations().map((event) => ({
110
- at: event.at,
111
- tags: event.tags,
112
- busted: event.busted,
113
- source: event.source,
114
- }));
115
-
116
106
  /**
117
107
  * Every source only this process can answer. It owns the SQL connection, the caught outbox, the
118
108
  * committed manifest on disk, the span exporter and the app's registries — no other host can.
@@ -126,6 +116,7 @@ const invalidationFacts = (): readonly InvalidationFact[] =>
126
116
  export function devSources(input: DevDashboardInput): DevSources {
127
117
  const traces = input.traces;
128
118
  const statements = input.statements;
119
+ const invalidations = input.invalidations;
129
120
  // Only the memory driver retains what it accepted. Once a credential selects a real transport
130
121
  // the messages are at the provider, so the hook is omitted rather than answered with `[]` —
131
122
  // an empty outbox claims nobody was mailed, which is a different and unearned answer.
@@ -145,8 +136,14 @@ export function devSources(input: DevDashboardInput): DevSources {
145
136
  mailTemplates: async (): Promise<readonly MailTemplateFact[]> =>
146
137
  mailTemplateFacts((await appLocaleSet(input.root)).locales),
147
138
  manifest: (): Promise<ManifestFact> => manifestFact(input.root),
148
- invalidations: (): Promise<readonly InvalidationFact[]> =>
149
- Promise.resolve(invalidationFacts()),
139
+ // Spread for the traces' reason below: a host that subscribed no log falls back to the
140
+ // refusal, never to an empty list that would claim nothing was ever busted.
141
+ ...(invalidations === undefined
142
+ ? {}
143
+ : {
144
+ invalidations: (): Promise<readonly InvalidationFact[]> =>
145
+ Promise.resolve(invalidations.facts()),
146
+ }),
150
147
  // Read through the app's own policies at request time, so a reload that changes a rule
151
148
  // changes the matrix without a remount.
152
149
  policyMatrix: (): Promise<readonly PolicyFact[]> => Promise.resolve(devPolicyMatrix()),
@@ -5,9 +5,8 @@
5
5
  // It counts and it warns once; what a verdict *means* — which code, which `fix:` — is
6
6
  // `statement-loop.ts`'s, so all four surfaces read one answer.
7
7
 
8
- import type { Ctx } from '@ultimat3/core';
8
+ import type { Ctx, StatementAttribution, DbStatementEvent as StatementEvent } from '@ultimat3/core';
9
9
  import { assert, tryUseContext } from '@ultimat3/core';
10
- import type { StatementAttribution, StatementEvent, StatementObserver } from '@ultimat3/db';
11
10
  import { statementFingerprint, statementKind } from '@ultimat3/db';
12
11
  import { N_PLUS_ONE_THRESHOLD } from '@ultimat3/entity';
13
12
  import { loopFacts, warnLoop } from './statement-loop';
@@ -32,8 +31,13 @@ export interface RepeatedStatement {
32
31
  readonly traceId: string;
33
32
  }
34
33
 
34
+ /** What the ledger hears: one `db.statement` payload, handed over by `x dev`'s bus subscriber. */
35
+ interface StatementObserver {
36
+ onStatement(event: StatementEvent): void;
37
+ }
38
+
35
39
  export interface StatementLedger {
36
- /** Hand this to `setStatementObserver()`. */
40
+ /** `x dev` subscribes this to `db.statement`: `subscribe('db.statement', (e) => observer.onStatement(e.payload))`. */
37
41
  readonly observer: StatementObserver;
38
42
  /** Shapes that crossed the threshold, newest first. */
39
43
  repeats(): readonly RepeatedStatement[];
@@ -81,7 +81,8 @@ export function devRebuilder(
81
81
  state.appFindings = findings;
82
82
  state.islands = islands;
83
83
  const unserved = await refreshDevices();
84
- for (const path of isr.store().paths()) isr.store().delete(path);
84
+ // Awaited one by one: a shared store answers over the network, and a dev save is rare.
85
+ for (const path of await isr.store().paths()) await isr.store().delete(path);
85
86
  state.reloads += 1;
86
87
  // Read on EVERY rebuild, so a pin one save reached is never reported against the next save.
87
88
  const pins = takeStalePins();
@@ -51,7 +51,7 @@ export interface DevRouteTableInput {
51
51
  /** A getter: the watcher tick rebuilds the islands, and a captured bundle would serve the first. */
52
52
  readonly islands: () => IslandBundle;
53
53
  /** `app.config.ts`'s `realtime`, as the boot obeyed it: off, no document names a sync node. */
54
- readonly realtime: Pick<RealtimeConfig, 'enabled'>;
54
+ readonly realtime: Pick<RealtimeConfig, 'enabled' | 'maxQueued'>;
55
55
  /** The web role's limiter store — what a bearer mount counts per-token allowances on. */
56
56
  readonly rateLimitStore?: RateLimitStore | undefined;
57
57
  /** `apps/<app>/runtime.ts`'s plain `routes`, mounted as the container mounts them. */
package/src/dev-traces.ts CHANGED
@@ -1,20 +1,21 @@
1
1
  // The `/_x` timeline panel's source: core's own spans, recorded in this process. `x dev` installs
2
- // the exporter at boot, so every `withSpan` the framework already opens — the request, the action,
2
+ // a `span.end` subscriber at boot, so every `withSpan` the framework already opens — the request, the action,
3
3
  // the query, the cache bust — arrives here and is assembled back into the tree the flame draws.
4
4
  // A tracer written here instead would be a second one, disagreeing with `x trace` by construction.
5
5
 
6
6
  import type { RequestTrace, SpanKind, TimelineSpan } from '@ultimat3/admin/dev';
7
7
  import type { ReadableSpan, SpanExporter } from '@ultimat3/core';
8
- import { finiteCount } from '@ultimat3/core';
9
- // The attribute name is `@ultimat3/db`'s to declare — this reads it rather than restating it, so
10
- // renaming it there is a compile error here instead of a panel that silently groups nothing.
11
- import { STATEMENT_ATTRIBUTE } from '@ultimat3/db';
8
+ // The attribute names are core's semconv table — read, never restated, so a rename there is a
9
+ // compile error here instead of a panel that silently groups nothing.
10
+ import { finiteCount, SEMCONV } from '@ultimat3/core';
11
+ // `@ultimat3/http`'s pipeline stamps it on the request's root span and on nothing else.
12
+ import { REQUEST_ID_ATTRIBUTE } from '@ultimat3/http';
12
13
 
13
14
  /** Traces retained. A dev panel shows recent requests; it does not page through history. */
14
15
  const DEFAULT_LIMIT = 50;
15
16
 
16
17
  export interface TraceRecorder {
17
- /** Hand this to `configureTelemetry({ exporter })`. */
18
+ /** Feed it every ended span: `subscribe('span.end', (e) => recorder.exporter.export(e.payload))`. */
18
19
  readonly exporter: SpanExporter;
19
20
  /** Complete request traces, newest first. */
20
21
  traces(): readonly RequestTrace[];
@@ -60,21 +61,21 @@ const attrNumber = (span: ReadableSpan, key: string): number | undefined => {
60
61
  };
61
62
 
62
63
  /**
63
- * The pipeline names its root span `<METHOD> <path>` and tags it with `http.*`. Reading the
64
+ * The pipeline names its root span `<METHOD> <path>` and tags it with semconv's `http.*`. Reading the
64
65
  * attributes first and the name only as a fallback keeps the panel working against a root span
65
66
  * from any host, while still preferring the facts the pipeline states outright.
66
67
  */
67
68
  function requestFacts(root: ReadableSpan): { method: string; path: string } {
68
69
  const [namedMethod = '', namedPath = ''] = root.name.split(' ');
69
70
  return {
70
- method: attrString(root, 'http.method') ?? namedMethod,
71
- path: attrString(root, 'http.route') ?? namedPath,
71
+ method: attrString(root, SEMCONV.httpRequestMethod) ?? namedMethod,
72
+ path: attrString(root, SEMCONV.httpRoute) ?? namedPath,
72
73
  };
73
74
  }
74
75
 
75
- /** `http.request_id` is stamped by the pipeline's root and by nothing else; the name is a fallback. */
76
+ /** The request id is stamped by the pipeline's root and by nothing else; the name is a fallback. */
76
77
  const isHttpRoot = (span: ReadableSpan): boolean =>
77
- span.attributes['http.request_id'] !== undefined || /^[A-Z]+ \//.test(span.name);
78
+ span.attributes[REQUEST_ID_ATTRIBUTE] !== undefined || /^[A-Z]+ \//.test(span.name);
78
79
 
79
80
  /**
80
81
  * The request's own span among a trace's. `parentSpanId === undefined` was a third CONDITION
@@ -98,10 +99,10 @@ function toTrace(root: ReadableSpan, spans: readonly ReadableSpan[]): RequestTra
98
99
  const { method, path } = requestFacts(root);
99
100
  const origin = root.startedAt;
100
101
  return {
101
- requestId: attrString(root, 'http.request_id') ?? root.context.traceId,
102
+ requestId: attrString(root, REQUEST_ID_ATTRIBUTE) ?? root.context.traceId,
102
103
  method,
103
104
  path,
104
- status: attrNumber(root, 'http.status_code') ?? 0,
105
+ status: attrNumber(root, SEMCONV.httpResponseStatusCode) ?? 0,
105
106
  startedAt: new Date(origin).toISOString(),
106
107
  totalMs: root.durationMs,
107
108
  spans: spans
@@ -116,9 +117,9 @@ function toTrace(root: ReadableSpan, spans: readonly ReadableSpan[]): RequestTra
116
117
  startMs: Math.max(0, span.startedAt - origin),
117
118
  durationMs: span.durationMs,
118
119
  // The panel counts repeats of `detail` to find the N+1. A statement states its own
119
- // identity (`STATEMENT_ATTRIBUTE`, set by `@ultimat3/db`'s funnels); for every other span
120
+ // identity (`db.query.text`, set by `@ultimat3/db`'s funnels); for every other span
120
121
  // the name is that identity — `query.feed` twice is two reads of one query.
121
- detail: attrString(span, STATEMENT_ATTRIBUTE) ?? span.name,
122
+ detail: attrString(span, SEMCONV.dbQueryText) ?? span.name,
122
123
  }),
123
124
  )
124
125
  .sort((a, b) => a.startMs - b.startMs),
@@ -12,7 +12,18 @@ import type { NavigationDocumentHead } from './page-navigation';
12
12
  * no island was built, and a page that renders one then fails by name rather than emitting a
13
13
  * `data-x-entry` nothing can import.
14
14
  */
15
- export type IslandResolver = (routeFile: string) => (src: string) => string;
15
+ export type IslandResolver = (routeFile: string) => IslandResolve;
16
+
17
+ /**
18
+ * One route file's resolver: `src` → entry URL, plus — from a real bundle — the shared chunks an
19
+ * entry URL imports (`IslandChunk.imports`), which the document preloads for the islands it
20
+ * rendered (`route-islands-preload.ts`). Optional so a resolver that is only a URL map (a test
21
+ * double) still type-checks; it then earns no preload, never a wrong one.
22
+ */
23
+ export interface IslandResolve {
24
+ (src: string): string;
25
+ readonly importsOf?: (entryUrl: string) => readonly string[];
26
+ }
16
27
 
17
28
  export interface DocumentOptions {
18
29
  readonly resolveIsland?: IslandResolver;
@@ -0,0 +1,55 @@
1
+ // Single responsibility: whether the `drift` step has a SQL schema to judge. Migrations, drift and
2
+ // `x db` describe Postgres only; an app whose rows live in a `defineDriver` store owns its schema,
3
+ // and the step skips it with the reason printed rather than demanding `x db gen "initial"`.
4
+
5
+ import type { DriverStoreKind } from '@ultimat3/entity/adapter';
6
+ import { driverStores } from '@ultimat3/entity/adapter';
7
+ import { msg } from './messages';
8
+ import { MIGRATIONS_DIR } from './migrations';
9
+ import type { Finding } from './output';
10
+ import { fromFindings, type StepOutcome } from './verify-step';
11
+
12
+ type Stores = () => Readonly<Record<DriverStoreKind, readonly string[]>>;
13
+
14
+ /** A recorded migration is proof of a SQL schema, whatever the loaded modules constructed. */
15
+ const hasMigration = (root: string): boolean => {
16
+ // Scanned from the app root, which exists, so a missing migrations directory is no match.
17
+ for (const _ of new Bun.Glob(`${MIGRATIONS_DIR}/*.hash`).scanSync({ cwd: root })) return true;
18
+ return false;
19
+ };
20
+
21
+ /**
22
+ * The reason to skip, or `undefined` to run. Read AFTER the app is loaded — the drivers its
23
+ * modules construct are what `driverStores()` records. Skips only when every noted store is a
24
+ * custom one AND no migration exists: a mixed app has migrations for its Postgres tables, so a
25
+ * Postgres driver that has not noted itself still cannot switch the step off.
26
+ */
27
+ export const nonSqlDriftSkip = (
28
+ root: string,
29
+ stores: Stores = driverStores,
30
+ ): string | undefined => {
31
+ const { sql, custom } = stores();
32
+ if (custom.length === 0 || sql.length > 0 || hasMigration(root)) return undefined;
33
+ return msg('cli.verify.driftNonSql', { stores: custom.join(', ') });
34
+ };
35
+
36
+ export interface DriftRails {
37
+ /** The migration and schema rails — the ones a store owning its own schema has nothing for. */
38
+ readonly schema: () => Promise<readonly Finding[]>;
39
+ /** The generated client against its stamp: a fact about the app's API, whatever stores rows. */
40
+ readonly client: () => Promise<readonly Finding[]>;
41
+ readonly stores?: Stores;
42
+ }
43
+
44
+ /**
45
+ * The `drift` step's outcome. A non-SQL app skips the schema rails, with the reason in `output`,
46
+ * and still runs the client rail — a stale `x client` is drift whatever the store is.
47
+ */
48
+ export const driftOutcome = async (root: string, rails: DriftRails): Promise<StepOutcome> => {
49
+ const skipped = nonSqlDriftSkip(root, rails.stores);
50
+ const findings = [
51
+ ...(skipped === undefined ? await rails.schema() : []),
52
+ ...(await rails.client()),
53
+ ];
54
+ return { ...fromFindings(findings), ...(skipped === undefined ? {} : { output: skipped }) };
55
+ };
@@ -50,14 +50,14 @@ export const CATALOG_PACKAGES = [
50
50
  * declare (`error-catalog.test.ts`), which is why `admin` is not here: `x dev` imports it and
51
51
  * `package.json` depends on it. `ui` reaches the CLI only as `admin`'s own dependency, so an
52
52
  * installer that keeps transitive packages private reports its codes `unavailable` rather than
53
- * the CLI declaring a package no command imports. `scraping` is an app's own choice since 22.0.0: `x shot` drives Chrome over raw CDP and imports nothing from it, so its codes
54
- * answer where the app installed it and are reported `unavailable` where it did not. Every other
53
+ * the CLI declaring a package no command imports. `scraping` left this list in 31.0.0: the boot
54
+ * imports its `./adapter` when `runtime.ts` supplies a `scrapeDriver`, so it is declared. Every other
55
55
  * entry above is a real runtime import and must be a declared dependency — `error-catalog.test.ts`
56
56
  * holds the list to exactly that, because an undeclared one resolves through workspace symlinks
57
57
  * here and through nothing in an installed app, where `x errors explain X_FLAG_EXPIRED` then
58
58
  * refuses a code the wiki promises.
59
59
  */
60
- export const CATALOG_OPTIONAL_HOSTS: readonly string[] = ['@ultimat3/scraping', '@ultimat3/ui'];
60
+ export const CATALOG_OPTIONAL_HOSTS: readonly string[] = ['@ultimat3/ui'];
61
61
 
62
62
  export interface ErrorCatalog {
63
63
  /** Packages whose codes are now registered. */
@@ -135,6 +135,11 @@ export async function buildErrorCatalog(
135
135
  * `@ultimat3/core` at all. Nothing schema-specific happens here any more.
136
136
  */
137
137
  async function importAll(): Promise<ErrorCatalog> {
138
+ // `@ultimat3/admin` and `@ultimat3/ui` ship `.tsx`: without the render loader Bun compiles their
139
+ // JSX itself and the import dies on `Export named 'jsxDEV' not found`. The barrel installs it as
140
+ // a side effect, so it has to finish before the catalog imports run — not race them. The test
141
+ // preload installs it for every suite, which is why only `error-catalog-process.test.ts` sees it.
142
+ await import('@ultimat3/render/server');
138
143
  return buildErrorCatalog((specifier) => import(specifier));
139
144
  }
140
145
 
@@ -0,0 +1,32 @@
1
+ // The X_* codes of the `boundaries` step's import rules — the app's surfaces, its layers, its
2
+ // packages, the adapter and loader subpaths — split out of `error-codes.ts` at its 500-line
3
+ // ceiling, as `error-codes-shot.ts` was. `@ultimat3/render` owns the surface *rule*; the CLI owns the diagnostic
4
+ // (`app-boundaries.ts` holds the one rule-to-code table). That file registers these in its one call.
5
+
6
+ /** Codes the `boundaries` step and `x fix boundary` report. */
7
+ export const CLI_BOUNDARY_ERROR_CODES = [
8
+ 'X_BOUNDARY_SITE_TO_APP',
9
+ 'X_BOUNDARY_SHARED_LEAF',
10
+ 'X_BOUNDARY_APP_TO_API',
11
+ 'X_BOUNDARY_ROUTE_TO_DB',
12
+ 'X_BOUNDARY_SERVICE_TO_HTTP',
13
+ 'X_BOUNDARY_SURFACE_IMPORT',
14
+ 'X_BOUNDARY_PACKAGE_TO_APP',
15
+ 'X_BOUNDARY_ADAPTER_IMPORT',
16
+ 'X_BOUNDARY_LOADER_IMPORT',
17
+ ] as const;
18
+
19
+ export type CliBoundaryErrorCode = (typeof CLI_BOUNDARY_ERROR_CODES)[number];
20
+
21
+ /** Their titles, typed over the list above so a code without one is a build error. */
22
+ export const CLI_BOUNDARY_ERROR_TITLES: Readonly<Record<CliBoundaryErrorCode, string>> = {
23
+ X_BOUNDARY_SITE_TO_APP: 'site/ imported app/',
24
+ X_BOUNDARY_SHARED_LEAF: 'shared/ imported a surface',
25
+ X_BOUNDARY_APP_TO_API: 'app/ imported api/ at runtime',
26
+ X_BOUNDARY_ROUTE_TO_DB: 'a route touched the database',
27
+ X_BOUNDARY_SERVICE_TO_HTTP: 'a service imported HTTP',
28
+ X_BOUNDARY_SURFACE_IMPORT: 'a surface imports one SURFACE_SPECS does not allow',
29
+ X_BOUNDARY_PACKAGE_TO_APP: 'packages/ imported apps/ at runtime',
30
+ X_BOUNDARY_ADAPTER_IMPORT: 'an app module imports an adapter installer',
31
+ X_BOUNDARY_LOADER_IMPORT: 'an app module imports a registration loader',
32
+ };