@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
@@ -1,10 +1,111 @@
1
1
  # Observability
2
2
 
3
- Metrics, spans, and structured logs — all in `@ultimat3/core`, all dependency-free.
3
+ One instrumentation bus, OpenTelemetry semantic conventions, and OTLP spans, logs and metrics — all in `@ultimat3/core`, all dependency-free.
4
4
 
5
- `As of 2026-08`. Stable API — semver from here ([Upgrading](Upgrading)).
5
+ `As of 2026-11` (31.0). Stable API — semver from here ([Upgrading](Upgrading)).
6
6
 
7
- Counter, gauge and histogram sit on the OpenTelemetry data model, aggregate in process, and are read through one `collectMetrics()`. The wire format is a **driver**: `MetricExporter` is the seam, the default is a no-op, and `metricsText()` renders the Prometheus/OpenMetrics scrape body. An **OTLP client ships** `As of 2026-08`: `otlpMetricExporter()` and `otlpSpanExporter()` speak OTLP/HTTP JSON over `fetch` and read `OTEL_EXPORTER_OTLP_ENDPOINT` (and the `_METRICS_`/`_TRACES_ENDPOINT`, `_HEADERS`, `_PROTOCOL` variants), with no new dependency. Two limits: **gRPC on `:4317` is refused** with `X_OTLP_PROTOCOL_UNSUPPORTED` and will stay refused — HTTP/2 plus protobuf is a dependency and a second wire format, so point the collector's HTTP receiver at `:4318` — and there is **no logs signal**. Scraping `metricsText()` with an agent remains equally supported.
7
+ Every observer — the OTLP exporters, the semconv histograms, `x dev`'s recorder, the `/_x` panels, an app's own code — is a **subscriber on one bus**. No package keeps a `set*Observer`, `set*Sink`, single-exporter slot or `recent*()` ring buffer of its own: the `boundaries` step refuses one (`X_INSTRUMENT_SLOT_FORBIDDEN`).
8
+
9
+ ## The instrumentation bus
10
+
11
+ ```ts
12
+ import { logger, subscribe } from '@ultimat3/core';
13
+
14
+ // Every slow statement, sampled trace or not — the "subscribe to every slow query" recipe.
15
+ const off = subscribe('db.statement', ({ payload }) => {
16
+ if (payload.durationMs > 250) logger.warn('db.slow', { sql: payload.text, ms: payload.durationMs });
17
+ });
18
+ off(); // the unsubscribe; calling it twice is a no-op
19
+ ```
20
+
21
+ | Call | What it does |
22
+ |---|---|
23
+ | `subscribe(pattern, handler)` | hear an exact name (`'db.statement'`), a dot-SEGMENT prefix (`'entity'` hears `entity.row`, `entity.bulk`, `entity.cross_tenant`; `'ent'` does not compile) or `'*'`. Returns the unsubscribe |
24
+ | `subscribed(name)` | whether anything hears `name` — an emitter asks before building a costly payload |
25
+ | `instrument(name, payload)` | publish one event |
26
+ | `subscriberCount()` / `resetInstrumentation()` | a test's leak check / backstop |
27
+
28
+ | Rule | |
29
+ |---|---|
30
+ | Order | handlers run synchronously, on the emitter's stack, in registration order — `tryUseContext()` and `currentSpanContext()` inside one answer for the emitter |
31
+ | Sampling | every occurrence is emitted, BEFORE and regardless of trace sampling: a counter sees unsampled traffic. Only `span.end` is sampled spans alone |
32
+ | A throwing handler | CONTAINED: the other handlers still run and the emitter never sees it — a subscriber can never break the work it observes (a `mail.deliver` one cannot make a sent message retry; a `policy.decision` one cannot deny). An `async` handler's rejection is contained too. Logged once per handler and event as `instrument.subscriber_failed`; `subscriberFailures()` counts every one |
33
+ | Re-entry | a handler may emit other names; one re-emitting its OWN name is not re-delivered (the loop a logging `'*'` subscriber would spin) |
34
+ | Cost | no subscriber: one map read per event, no allocation |
35
+ | Not on the bus | durable ports — `AuditSink`, `FailureStore` — the error-reporter chain, jobs' internal wake, and `publishEvent`: a domain event is durable data an app consumes, an instrumentation event is a fact about the process that nobody has to hear |
36
+
37
+ ### The events
38
+
39
+ `INSTRUMENT_EVENTS` is the table as a value. Payload types are exported from `@ultimat3/core`; every timed event carries `durationMs`, and `error` on failure (the value the caller receives). An emitter reports a failed operation too.
40
+
41
+ | Event | Payload | Span (kind) | Emitted by |
42
+ |---|---|---|---|
43
+ | `http.request` | `method`, `route` (pattern), `status` | `GET /posts/:id` (server) | `@ultimat3/http` |
44
+ | `db.statement` | `text` (parameterised), `values`, `rows`, `attribution?`, `expected?` | `db.<verb>` (client) | `@ultimat3/db` |
45
+ | `entity.row` · `entity.bulk` · `entity.cross_tenant` | the row change · the bulk count · the reason | — | `@ultimat3/entity` |
46
+ | `policy.decision` | `label`, `allowed`, `code`, `reason`, actor, `surface` | — | `@ultimat3/policy` |
47
+ | `action.invoke` · `query.read` | `action` · `query` | `action.<name>` · `query.<name>` (internal) | `@ultimat3/action` · `@ultimat3/query` |
48
+ | `job.enqueue` · `job.perform` | `job`, `queue`, `id` (+ `attempt`) | producer · consumer | `@ultimat3/jobs` |
49
+ | `ai.llm` | `provider`, `model`, `inputTokens`, `outputTokens`, `cacheHit` | `ai.llm` (client) | `@ultimat3/ai` |
50
+ | `render.page` · `render.hole` · `render.isr.regenerate` | `route` (pattern) · + `hole` id · + `path` | internal, `http.route` set | `@ultimat3/render` |
51
+ | `outbound.request` | `vendor`, `method`, `host`, `status?` (absent when no answer came) | `outbound.<vendor>` (client) | `outbound()`, `@ultimat3/core/outbound` |
52
+ | `mail.deliver` | `transport`, `recipients` (a COUNT — no address rides an event) | client | `@ultimat3/mail` |
53
+ | `storage.put` `.get` `.stat` `.copy` `.delete` `.list` | `disk`, `key`, `bytes?` | client | every disk `defineStorage` resolves |
54
+ | `cache.hit` · `cache.miss` · `cache.invalidate` · `cache.tier_failure` | tier + key · tags, busted, errors · the failure | `cache.invalidate` (internal) | `@ultimat3/cache` |
55
+ | `span.end` | a `ReadableSpan` — SAMPLED spans only | — | core's tracer |
56
+ | `log.record` | `at`, `level`, `message`, `fields` — after redaction | — | core's process logger |
57
+
58
+ One `render.isr.regenerate` per generation, never per request that joined it. One `outbound.request` per call, retries inside it. A `storage.*` call a driver makes on itself is not counted twice; a driver held directly, never resolved through `defineStorage`, reports nothing.
59
+
60
+ ### Semantic-convention names
61
+
62
+ Span attribute keys come from `SEMCONV` (no string literal), metric names from `SEMCONV_METRICS`. The legacy `http.method`, `http.status_code`, `http.target`, `db.statement` and `llm.*` attributes are gone (`As of 31.0`). Framework-specific attributes are `ultimate.*`.
63
+
64
+ | Span | Attributes |
65
+ |---|---|
66
+ | HTTP server | `http.request.method`, `http.response.status_code`, `http.route`, `url.path`, `url.scheme`, `server.address`, `ultimate.request_id` |
67
+ | Database client | `db.system.name` = `postgresql`, `db.query.text` (parameterised, never values), `db.operation.name` |
68
+ | Jobs | `messaging.system` = `ultimate`, `messaging.operation.type` (`create` / `process`), `messaging.destination.name` |
69
+ | LLM | `gen_ai.provider.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` |
70
+ | Outbound | `server.address`, `server.port`, `http.request.method`, `http.response.status_code` — never the path or the query |
71
+ | Render | `http.route` |
72
+
73
+ ### An app's own events
74
+
75
+ Augment the map, then emit with the same `instrument()` — one bus, typed end to end:
76
+
77
+ ```ts
78
+ import { counter, instrument, subscribe } from '@ultimat3/core';
79
+ import type { Money } from '@ultimat3/money';
80
+
81
+ declare module '@ultimat3/core' {
82
+ interface InstrumentEventMap {
83
+ 'billing.charged': { readonly orgId: string; readonly amount: Money };
84
+ }
85
+ }
86
+
87
+ const charges = counter('billing_charges_total', { unit: '{charge}' });
88
+ subscribe('billing', ({ payload }) => charges.add(1, { currency: payload.amount.currency }));
89
+ instrument('billing.charged', { orgId: 'org_1', amount: { minor: 1200, currency: 'EUR' } });
90
+ ```
91
+
92
+ A name is lowercase dot-segments; the framework's first segments (`INSTRUMENT_EVENTS`) are taken.
93
+
94
+ ## Exporting: OTLP spans, logs and metrics
95
+
96
+ The container boot (`startOtlpExport`) installs one exporter per signal an endpoint names, each a bus subscriber with its own `close`-phase flush, and releases them on stop:
97
+
98
+ | Signal | Variable | Subscriber |
99
+ |---|---|---|
100
+ | traces | `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, else `OTEL_EXPORTER_OTLP_ENDPOINT` + `/v1/traces` | `subscribe('span.end', (e) => otlpSpanExporter().export(e.payload))` |
101
+ | logs | `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`, else `…_ENDPOINT` + `/v1/logs` | `subscribe('log.record', (e) => otlpLogExporter().export(e.payload))` — the process logger's lines, redacted, joined to the active trace |
102
+ | metrics | `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`, else `…_ENDPOINT` + `/v1/metrics` | `subscribe('metric.export', (e) => otlpMetricExporter().export(e.payload))`, pushed every 60 s |
103
+
104
+ Every boot, collector or not, also subscribes `subscribeSemconvMetrics()`: `db_client_operation_duration_seconds` (from `db.statement`), `job_duration_seconds` (from `job.perform`) and `gen_ai_client_token_usage` (from `ai.llm`) — on `/metrics` and over OTLP alike. OTLP/HTTP JSON over `fetch`, no dependency; `_HEADERS` and `_PROTOCOL` are read too. **gRPC on `:4317` is refused** with `X_OTLP_PROTOCOL_UNSUPPORTED` and will stay refused — HTTP/2 plus protobuf is a dependency and a second wire format, so point the collector's HTTP receiver at `:4318`. Scraping `metricsText()` remains equally supported.
105
+
106
+ Proof, `As of 2026-11-09`: `packages/cli/src/otlp-export.live.test.ts` sends one request through an action that queries Postgres and reads, off the collector's wire, an HTTP server span with the `db.select` client span beneath it in one trace, semconv names only.
107
+
108
+ **Span cost.** An unsampled span costs 3.3 µs (root) / 2.0 µs (child), against a 1 µs target (`scripts/bench/results/span-overhead.json`, `As of 2026-11-09`): ids and clock reads are still paid before the sampling decision is known. Known gap, pinned by `scripts/bench/span-overhead.bench.test.ts`.
8
109
 
9
110
  ## Instruments
10
111
 
@@ -46,12 +147,15 @@ Dotted OTel names survive OTLP but not a Prometheus scrape, and the autoscaler r
46
147
  ## Reading them
47
148
 
48
149
  ```ts
49
- import { collectMetrics, configureMetrics, exportMetrics, startMetricExport } from '@ultimat3/core';
150
+ import type { MetricExporter } from '@ultimat3/core';
151
+ import { collectMetrics, exportMetrics, startMetricExport, subscribe } from '@ultimat3/core';
152
+
153
+ declare const myExporter: MetricExporter;
50
154
 
51
- collectMetrics(); // a MetricCollection: { at, resource, metrics }
52
- configureMetrics({ exporter: myExporter }); // install the seam
53
- exportMetrics(); // collect + hand to the exporter, once
54
- const stop = startMetricExport(60_000); // periodic; the timer is unref'd. Default 60s
155
+ collectMetrics(); // a MetricCollection: { at, resource, metrics }
156
+ const release = subscribe('metric.export', (event) => myExporter.export(event.payload)); // the seam
157
+ exportMetrics(); // one `metric.export` tick; nothing is collected while nobody subscribes
158
+ const stop = startMetricExport(60_000); // periodic; the timer is unref'd. Default 60s
55
159
  ```
56
160
 
57
161
  | Type | Shape |
@@ -63,7 +167,7 @@ const stop = startMetricExport(60_000); // periodic; the timer is unref'd.
63
167
  | `MetricPoint` | `{ attributes, value }` |
64
168
  | `HistogramPoint` | adds `count`, `min`, `max`, `bounds`, `buckets` — `buckets` is one longer than `bounds`, the last being the `+Inf` overflow |
65
169
 
66
- Temporality is **cumulative**. Shipped exporters: `noopMetricExporter` (the default) and `memoryMetricExporter()` for tests. `resetMetrics()` restores the defaults and clears the series while keeping declarations — test-only.
170
+ Temporality is **cumulative**. An exporter is a `metric.export` subscriber on the instrumentation bus, like the span and log exporters, released by its own unsubscribe; `configureMetrics({ clock, enabled })` is configuration only — its `exporter` option left in 31.0.0 ([Upgrading](Upgrading)). `memoryMetricExporter()` is the test double. `resetMetrics()` restores the defaults and clears the series while keeping declarations — test-only.
67
171
 
68
172
  ## The Prometheus body
69
173
 
@@ -157,11 +261,11 @@ CPU autoscaling is wrong for `sync` and `worker`: a node holding 80k idle socket
157
261
 
158
262
  `x db diagnostics --json` (`As of 2026-11`) answers what the series cannot: who blocks whom (`data.blockers.rows[].blockedBy`), what each session is doing, the slowest statements (`pg_stat_statements`, when an operator installed it), unused and invalid indexes, `NOT VALID` constraints, dead tuples and the last autovacuum. Facts only, exit 0; `/readyz` stays the one-`select 1` probe. Read-only, 2 s per statement, no user table read, literals printed as `?`; whoever runs it sees the redacted SQL of every session on the app's database role → [CLI reference](CLI-Reference#x-db). The same report is `dbDiagnostics()` from `@ultimat3/db`.
159
263
 
160
- ## Spans and logs
264
+ ## Spans and logs, in detail
161
265
 
162
266
  | Concern | Where |
163
267
  |---|---|
164
- | Tracing | always on, not a flag. `otel.endpoint` absent means spans are still recorded and exported nowhere → [Configuration](Configuration) |
268
+ | Tracing | always on, not a flag. No `span.end` subscriber means a span is still opened, propagated and sampled, and built into no record → [Configuration](Configuration) |
165
269
  | Head sampling | `otel.sampling`, default `0.1`; errors are always sampled |
166
270
  | OTLP delivery | a 429, 502, 503, 504 or a transport failure is retried, 3 attempts with full jitter and `Retry-After` honoured, inside the exporter's `timeoutMs` (default 10 s, the whole export); any other status is one POST. One `otlp export rejected`/`failed` line per batch, with `attempts`. A collector that accepted and then answered 503 receives that batch twice; span ids dedupe it |
167
271
  | Error grouping | `errorFingerprint(report)`: 16 hex over `code`, `source`, `scope.operation`, plus the top application frame (function and root-relative path, no line) for `X_INTERNAL`. Never the cause or an id, so two throws differing in a row id are one group, and a deploy is not a new one. The Sentry envelope sends it as `fingerprint` |
@@ -206,8 +310,9 @@ CPU autoscaling is wrong for `sync` and `worker`: a node holding 80k idle socket
206
310
  `errorGroupsSink` (`@ultimat3/admin/error-groups`, `As of 2026-11`) is an `ErrorReporter` that folds every report into its `errorFingerprint` group in `x_error_groups` — first seen, last seen, count, a redacted sample — and `/admin/errors` lists them (`errorGroupsPages`, permission `errors:read`).
207
311
 
208
312
  ```ts
313
+ // apps/web/runtime.ts
209
314
  import { errorGroupsSink, postgresErrorGroupsStore } from '@ultimat3/admin/error-groups';
210
- import { chainErrorReporters, configureErrorReporting, installedErrorReporter } from '@ultimat3/core';
315
+ import type { RuntimeOverrides } from '@ultimat3/cli/serve';
211
316
  import { job, t } from '@ultimat3/jobs';
212
317
 
213
318
  // The app's own: which tracker, which title. Enqueued once per NEW group, fleet-wide.
@@ -229,13 +334,14 @@ export const openErrorIssue = job({
229
334
  });
230
335
 
231
336
  export const errorGroups = postgresErrorGroupsStore();
232
- const sink = errorGroupsSink({ store: errorGroups, onNewGroup: openErrorIssue });
233
- configureErrorReporting({ reporter: chainErrorReporters(installedErrorReporter(), sink) });
337
+ export const runtime = {
338
+ errorReporter: errorGroupsSink({ store: errorGroups, onNewGroup: openErrorIssue }),
339
+ } satisfies RuntimeOverrides;
234
340
  ```
235
341
 
236
342
  | Concern | Rule |
237
343
  |---|---|
238
- | Composing | `chainErrorReporters(...)` from `@ultimat3/core`: every member gets every report, one that throws costs only itself, chains flatten. The container chains its `SENTRY_DSN` transport AFTER whatever the app installed — never over it |
344
+ | Composing | the reporter is the `errorReporter` adapter port — one field of `apps/web/runtime.ts` ([Adapters](Adapters#errorreporter)); `configureErrorReporting` takes no `reporter` (31.0.0). Several are `chainErrorReporters(...)` from `@ultimat3/core`: every member gets every report, one that throws costs only itself, chains flatten. The container chains its `SENTRY_DSN` transport AFTER whatever the app installed — never over it |
239
345
  | "New", once | the upsert's `xmax = 0` decides, so N replicas reporting one new fault enqueue `onNewGroup` once. Which tracker, title and assignee are the app's job |
240
346
  | Transactions | written outside the request's transaction: a rollback never erases its own error |
241
347
  | Load | `perMinute` store writes per process (default 120); past it, reports are counted and written as one later. A failed write is logged and never re-enters the reporter |
@@ -54,7 +54,7 @@ Every projection this package owns is a method on the query — `liveFeed.live(i
54
54
 
55
55
  `sql` is unreachable by design. The declaration lives in a private store inside `read.ts` and `@ultimat3/query` exports no reader for it, so `sourceFor` is the only thing that can build a source — one read path and one authz path, structurally rather than by convention. A hand-rolled object with `kind: 'query'` is `X_QUERY_FOREIGN`, never a registered read.
56
56
 
57
- `isLive` is the declared boolean; `live()` is the subscription itself. Every projection needs the name `registerQueries()` stamps on — before that, `X_QUERY_UNREGISTERED`.
57
+ `isLive` is the declared boolean; `live()` is the subscription itself. Every projection needs the name `defineApi({ queries })` stamps on at boot — before that, `X_QUERY_UNREGISTERED`.
58
58
 
59
59
  ## Five projections
60
60
 
@@ -349,7 +349,7 @@ Fifty *counts* collapse neither way — one `count()` per row is fifty different
349
349
 
350
350
  ## Audit: who saw what
351
351
 
352
- `query({ audit: true })` writes one record per call into the sink an action's `audit: true` writes to — one contract, `@ultimat3/core`'s `AuditRecord` / `AuditSink`, one installed sink (`setAuditSink` from `@ultimat3/core` — `@ultimat3/action` no longer re-exports it, `As of 25.0.0`). `As of 2026-10`.
352
+ `query({ audit: true })` writes one record per call into the sink an action's `audit: true` writes to — one contract, `@ultimat3/core`'s `AuditRecord` / `AuditSink`, one installed sink — the `auditSink` adapter port, set as `auditSink:` in `apps/<app>/runtime.ts` ([Adapters](Adapters#auditsink); 31.0.0 deleted `setAuditSink`). `As of 2026-10`.
353
353
 
354
354
  | Rule | |
355
355
  |---|---|
package/wiki/Realtime.md CHANGED
@@ -340,6 +340,9 @@ const feed = useChannel(ORG_FEED, { orgId }, { onEvent: (event) => console.debug
340
340
  `channel(name, { params, catchUp, policy, … })` in one call still exists for a channel no browser
341
341
  holds. **`policy` is required** on either form: a declaration without one is refused
342
342
  (`X_CHANNEL_DECLARATION_INVALID`), and a public channel says so with `policy: allow('public')`.
343
+ A `catchUp` passed as the query itself must decide with the channel's own `policy` object — the
344
+ read is served with the channel params as input, so a wider rule answers what the subscribe
345
+ refuses — or `channel()` throws `X_CHANNEL_CATCHUP_POLICY_MISMATCH` at load.
343
346
  The reference app's idiom is `examples/dummy/apps/web/app/posts/channel-ref.ts` beside `channels.ts`. The catch-up
344
347
  query's name is written by hand on the ref, like a `QueryRef`'s; `x build` emitting refs is
345
348
  plan-101 DX ledger #21.
@@ -356,7 +359,7 @@ plan-101 DX ledger #21.
356
359
  | records with no replicator | `recordPublisher({ transport, entities })` on `@ultimat3/realtime/server` puts an app's committed rows on the change bus, sequenced per producer; every node delivers them as `records`. Channels only — a publisher has no commit position to order a live window by. Under `x dev` a claimed entity is no longer also carried to channels by the in-process bridge, and a sync node carries each table from ONE producer kind — the first it saw — dropping the other's changes under `X_REALTIME_PRODUCER_CONFLICT` (25.0.0, #682). Rules: the package README, *Channel records with no replicator* |
357
360
  | `useChannel()` states | `joining` → `live` on the node's first answer to every channel that carries `records` or `events` (an `events` channel's is its roster, empty on a node without presence); `catching-up` while a `replay-gap` re-read runs; `offline`; `failed` with the coded refusal — a **decision** (a policy denial, an undeclared channel, a cap) and nothing else. A node whose bus is away refuses with `X_TRANSPORT_UNAVAILABLE`, which is its condition and not its verdict: the membership reads `joining` and is `live` again on the node's next answer ([a bus outage, seen from an open page](#a-bus-outage-seen-from-an-open-page)). The table is in the package README, *What `useChannel()` reports* |
358
361
  | events | on a channel declared with `events: true`; otherwise `X_CHANNEL_DECLARATION_INVALID`. **App code** — a job, an action — calls `publishChannelEvent(decl, params, event)` from `@ultimat3/realtime/server`: it publishes on the process's own bus, in every role, with no hub (27.5.0). The `sync` node's own code holds the hub and calls `hub.publishEvent(decl, params, event)`. Same frame, same subject. At-most-once, never stored, never replayed: an event says "re-read", never "here is the state". Call it **after COMMIT** — nothing here sees a transaction |
359
- | events with no replicator | a channel that lists no `records` reads no committed change, so it needs no replicator, no replication slot and no `REPLICATION` grant: `realtime: { enabled: true, transport: 'nats', urlEnv }`, a `sync` role, and the publishers. A node that serves no `live: true` query and no `records` channel boots on a real database with `live=none` and is never `X_REALTIME_TOPOLOGY` (27.5.0) |
362
+ | events with no replicator | a channel that lists no `records` reads no committed change, so it needs no replicator, no replication slot and no `REPLICATION` grant: `NATS_URL` set for every role, a `sync` role, and the publishers. A node that serves no `live: true` query and no `records` channel boots on a real database with `live=none` and is never `X_REALTIME_TOPOLOGY` (27.5.0) |
360
363
  | presence | a roster arrives as an `events` frame `{ presence: op, members, total? }`. Read it with `readPresence(frame.event)` in the channel's events handler. There is no separate presence frame |
361
364
  | an events-only island | an island whose only realtime is `useChannel` / `usePresence` / `useConnection` is never hidden and never waits for the page's restore ([above](#which-islands-wait-for-the-pages-restore)) |
362
365
  | the browser | `useChannel(decl, params, handlers?)`; `topic()` is the one way to spell a topic, and `bun run channel-literals` refuses any other |
@@ -393,7 +396,9 @@ toggles, a flash on change and a "live" dot are the app's.
393
396
 
394
397
  ## What each role needs from the bus
395
398
 
396
- Under `realtime: { transport: 'nats' }` every role holds a connection, and only two cannot work without one (`As of 2026-10`). The role decides, not the transport: a role that only **publishes** sends channel events and cache invalidations, and both mean "re-read".
399
+ The bus is the `transport` adapter port: `NATS_URL` set builds the NATS transport, unset the in-process one, and `transport:` in `apps/<app>/runtime.ts` replaces that decision with any `Transport` from `@ultimat3/realtime/adapter` — already connected, and not closed by the boot ([Adapters](Adapters#transport)). There is no `setChannelTransport` and no `realtime.transport` config key (31.0.0).
400
+
401
+ With `NATS_URL` set every role holds a connection, and only two cannot work without one (`As of 2026-10`). The role decides, not the transport: a role that only **publishes** sends channel events and cache invalidations, and both mean "re-read".
397
402
 
398
403
  | Role | Uses the bus to | At boot | NATS down while running | JetStream / the presence bucket | `transport` check |
399
404
  |---|---|---|---|---|---|
@@ -676,8 +681,8 @@ Node → device: `{ type: 'hello', heartbeatMs, maxFrameBytes }`, `{ type: 'requ
676
681
  protocol's `reconnect`.
677
682
 
678
683
  **Where it runs.** Every role attaches every declaration to its bus (`hostDeviceSockets`), so a
679
- worker's job can `request()`; only `web` holds sockets. Across replicas `realtime.transport` must be
680
- `'nats'` — on the in-process bus a device is reachable from its own process only.
684
+ worker's job can `request()`; only `web` holds sockets. Across replicas every role needs `NATS_URL`
685
+ set, or one `transport` in `apps/<app>/runtime.ts` — on the in-process bus a device is reachable from its own process only.
681
686
 
682
687
  **Where it is served.** The `web` role's own listener, beside the sync node's `/_x/sync`: the boot
683
688
  hands `httpServer` one mount per declared path beside `syncMount`, every path is checked free of a
@@ -193,6 +193,8 @@ export const config = defineRoute({
193
193
 
194
194
  **An `isr` route keys on no query unless it says so.** `As of 2026-11-02`. `/blog?x=1`, `/blog?x=2` and `/blog?utm_source=mail` are one render and one stored page, so no visitor can spend the origin's renders or push real pages out of the bounded store (it holds 1,000), and `utm_*` / `fbclid` / `gclid` do not split a page. An `isr` document is shared: what it varies on is the route's to declare.
195
195
 
196
+ **The default store is bounded twice, and keeps what is read.** `As of 2026-11-09`. `memoryIsrStore({ maxEntries, maxBytes })`: 1,000 pages (`DEFAULT_ISR_MAX_ENTRIES`) and 256 MiB of `html.length` (`DEFAULT_ISR_MAX_BYTES`), whichever is reached first. Least recently **used** goes first — a hit moves a page to the back, so a home page read on every request outlives cold pages generated after it; a stale mark keeps its place. A page larger than the whole byte cap is not stored and is rendered per request.
197
+
196
198
  **Declare every parameter the page reads.** A page that reads `?currency=` and does not list it is ONE stored document, the first visitor's, answered to every other currency. Two nets, both best-effort: `x verify` reads each `isr` route module for `query.<name>`, `query['<name>']` and `searchParams.get('<name>')` and warns for a name the declaration omits (a read made through a helper in another file is not seen); and outside production, the `query` a page component receives warns once (`isr.query.unkeyed-read`) when the page reads a parameter the route did not declare. `load` and `meta` read the narrowed `url`, where an undeclared parameter is simply absent.
197
199
 
198
200
  **Nothing is redirected.** `/blog?utm_source=mail` is answered with the `/blog` page: `load` and `meta` are given the narrowed URL, so `canonical: url` is `/blog` and a parameter outside the key cannot change the document stored under it. A declared parameter's **values** are still the visitor's — `?page=999999` is a key — so `load` answers `withStatus(404, …)` for one that names nothing, and the bounded store evicts the rest.
@@ -216,6 +218,8 @@ Order inside one bust: read tiers (farthest first) → this origin's ISR pages
216
218
 
217
219
  **A shared store must be able to refuse a write.** `runtime.isrStore` under `'purge'` needs `IsrStore.tagFence` — `sample(entities)` before a render reads its rows, `bump(entities)` on a bust, and an **atomic** `setIfCurrent(entry, entities, sampled)` (a transaction, a script, a conditional put) that refuses a write whose reading moved. The generation is per tag *entity* (`post` for `post:1`), so an unrelated row's bust costs one extra render and never a stale page. `memoryIsrStore` implements it; a store without it is refused at boot when any route purges (`X_ROUTE_MODE_INVALID`, naming the route). A bust also asks the store which keys it holds under the tags, by the route table, as well as the invalidation graph — the graph only knows the pages this process rendered. It matches on the **route's** tags: a `post:1` bust reaches every stored page of a route tagged `post`.
218
220
 
221
+ **One store for every replica: `storageIsrStore`.** `As of 2026-11-09`. `memoryIsrStore` is one cache per process — three web replicas render a page three times and hold three copies. `runtime.isrStore = storageIsrStore({ disk: disk('isr') })` keeps pages (`isr/page/…`) and tag-fence tokens (`isr/fence/…`) as objects on a `@ultimat3/storage` disk every replica reads. A bust writes a fresh token per tag entity; a write checks the reading, writes, then checks again and deletes its own page if a bust landed in between — a disk has no compare-and-put, and the bust lists the store only after its token is written, so no page outlives a bust its render predates. Bounded across replicas by `maxEntries` and `maxBytes` (the defaults above), swept every `sweepEvery` writes (32) per process, **oldest write first** — a read never writes, so it is not LRU. Every store call is awaited, so a custom store may answer with a promise (`IsrAnswer<T>`).
222
+
219
223
  **What `isr` never stores.** What it does store was rendered as nobody (above); a per-visitor answer has no place in one, so that page is `ssr`.
220
224
 
221
225
  | Render | Stored | The visitor gets |
@@ -519,3 +523,4 @@ in both.
519
523
  - A route holds no business logic. That is a service, behind an [action](Actions).
520
524
  - `prerender()` must be deterministic and bounded — it is a build input.
521
525
  - Never hand-write a canonical URL, a sitemap entry, or `sw.js`.
526
+ - A URL off data inside an island goes through `@ultimat3/ui`'s `Link`, or `safeUrl(url, 'href')` from `@ultimat3/core` at the call site. The island's server shell is screened like every page (a `javascript:` href is not emitted), but once it mounts Solid's compiled setter writes `<a href={row.url}>` as given; only the app's CSP stands between a looser policy and a live `javascript:` link. `As of 2026-11-09` there is no build check for it.
package/wiki/Scraping.md CHANGED
@@ -62,10 +62,10 @@ export const dailyOrders = scrape({
62
62
  | `onSettled` | — | how the run ended, told once: the `ScrapeReport` on `completed`, the `code` and the last attempt's `usage` otherwise — see [Usage](#usage) |
63
63
  | `recover` | — | a function — see [Recovery](#recovery) |
64
64
  | `artifacts` | — | where a failed run's HTML is written: `{ storage: () => disk('artifacts') }` — a thunk, read per write |
65
- | `driver` | — | which browser. Absent uses the process-wide `setScrapeDriver()` |
65
+ | `driver` | — | which browser. Absent uses the process's — `scrapeDriver` in `apps/<app>/runtime.ts` |
66
66
  | `watchdog` | — | `{ idleMs, graceMs }`, defaults `120000` / `5000` |
67
67
  | `retry` / `timeout` / `pageTimeout` / `queue` / `concurrency` | — | the job knobs, unchanged — `concurrency` takes the job's keyed form too ([Jobs and workflows](Jobs-And-Workflows)) |
68
- | `clock` | — | pins this definition's clock. Absent uses the process's — `setScrapeClock()`, which is what a test replaces |
68
+ | `clock` | — | pins this definition's clock. Absent uses the process's — `@ultimat3/core`'s ambient clock, which is what a test replaces |
69
69
 
70
70
  The CLI has no scrape command and no scrape generator `As of 2026-08-20` — `g` ships thirteen positionals and `scrape` is not one of them. A scrape is reached through the job CLI:
71
71
 
@@ -119,7 +119,7 @@ overlay made it worse — `page.values('#password')` read back what was typed in
119
119
  `driver-parity-frames.test.ts` pins every frame verb across all three drivers, because the parity
120
120
  suite that exists to catch a CDP/offline divergence had no frame coverage at all.
121
121
 
122
- `screenshot`/`pdf` take **no `timeout`** — `CaptureRequest.timeout` and the port's `CaptureOptions.timeoutMs` were deleted in 4.0.0 ([Upgrading](Upgrading)). No driver had ever honoured them, and a deadline enforced above the driver would have had to race `ScrapeClock.sleep`, which under `testScrapeClock` resolves on the first microtask — so every capture in every test would have timed out. The driver's own default is the honest bound.
122
+ `screenshot`/`pdf` take **no `timeout`** — `CaptureRequest.timeout` and the port's `CaptureOptions.timeoutMs` were deleted in 4.0.0 ([Upgrading](Upgrading)). No driver had ever honoured them, and a deadline enforced above the driver would have had to race the clock's `sleep`, which under a test's `frozenClock()` resolves on the first microtask — so every capture in every test would have timed out. The driver's own default is the honest bound.
123
123
 
124
124
  **`pageErrors()` is a separate stream from `console()`, and that is not tidiness.** An uncaught
125
125
  exception calls no console method, so a page whose script died can answer `console(): []` — gate on
@@ -188,7 +188,7 @@ A collapsed run is **not recorded**. Three broken runs at 2 rows would make the
188
188
  | `robots` | `'obey'` | `X_SCRAPE_ROBOTS_DISALLOWED` |
189
189
  | `rate` | 1 navigation/second | none — it paces, across both legs |
190
190
 
191
- **A wildcard admits names, then checks where they lead.** On the two legs this package dials itself — the HTTP leg and the robots read — a host admitted only by `'*'` or `'*.example.com'` is resolved, and an answer that is loopback, private, link-local or the metadata address is `X_SCRAPE_HOST_BLOCKED`; the request is then pinned to the approved address. An exact rule (`'intranet.example'`) is the decision to reach that host and is not resolved. Through a proxy the proxy resolves, so nothing is checked locally. The browser resolves its own names, and a WebSocket opened by a page is not intercepted at all — both are open → [Known gaps](Known-Gaps).
191
+ **A wildcard admits names, then checks where they lead.** It never admits `localhost` or `*.localhost` — loopback by name, and a name Chrome would send around an egress proxy; `allowHosts: ['*', 'localhost']` is the opt-in. A browser launched with an exit gets `--proxy-bypass-list=<-loopback>`, so loopback goes through the proxy too. On the two legs this package dials itself — the HTTP leg and the robots read — a host admitted only by `'*'` or `'*.example.com'` is resolved, and an answer that is loopback, private, link-local or the metadata address is `X_SCRAPE_HOST_BLOCKED`; the request is then pinned to the approved address. An exact rule (`'intranet.example'`) is the decision to reach that host and is not resolved. Through a proxy the proxy resolves, so nothing is checked locally. The browser leg screens the same way before it releases a request — the page's own and a popup's: an inward or unresolvable answer fails the request and lands in `page.network()` as `refused: 'host'`. It cannot pin, because the browser resolves again for itself, so a name that rebinds between the two is open, and a WebSocket opened by a page is not intercepted at all → [Known gaps](Known-Gaps).
192
192
 
193
193
  Ignoring robots takes a written reason: `robots: { ignore: 'contract with the operator, ticket OPS-441' }`. A bare `false` is a decision with no author.
194
194
 
@@ -339,7 +339,7 @@ export const syncAccounts = scrape({
339
339
  `eventPrompt({ timeout, pollMs? })` polls the job event bus **in process**. It is not
340
340
  `step.waitForEvent`: that suspends the run and closes the browser the site is waiting in.
341
341
 
342
- The bus must be the **stored** one (`EventBus.stored`): the answer is published by a web process and read by the worker. Outside development and test, an in-memory bus is refused when the prompt is asked — `X_DRIVER_UNAVAILABLE`, fix `setEventBus(postgresEventBus({ executor }))` — rather than timing out minutes later as `X_SCRAPE_PROMPT_UNANSWERED`.
342
+ The bus must be the **stored** one (`EventBus.stored`): the answer is published by a web process and read by the worker. Outside development and test, an in-memory bus is refused when the prompt is asked — `X_DRIVER_UNAVAILABLE`, fix `eventBus: postgresEventBus({ executor })` in `apps/<app>/runtime.ts` — rather than timing out minutes later as `X_SCRAPE_PROMPT_UNANSWERED`.
343
343
 
344
344
  | Fact | Detail |
345
345
  |---|---|
@@ -349,7 +349,7 @@ The bus must be the **stored** one (`EventBus.stored`): the answer is published
349
349
  | stale answers | only an answer published **after** the prompt was asked is consumed — the run id is the same on every attempt |
350
350
  | while it waits | the worker's heartbeat keeps the claim; one browser round trip per poll keeps the wedge watchdog and a rented browser alive |
351
351
  | it ends on | the answer · `timeout` → `X_SCRAPE_PROMPT_UNANSWERED` (terminal) · the run's `signal` · a browser that died |
352
- | the bus | must be the **stored** one (`postgresEventBus`) wherever the worker and the answering process differ. Every `x` boot installs it; a hand-written boot calls `setEventBus(postgresEventBus({ executor }))` |
352
+ | the bus | must be the **stored** one (`postgresEventBus`) wherever the worker and the answering process differ. Every `x` boot installs it; to swap it, `eventBus:` in `apps/<app>/runtime.ts` ([Adapters](Adapters#eventbus)) |
353
353
 
354
354
  Saying a prompt is pending is the app's — wrap the handler, it is a function:
355
355
 
@@ -393,16 +393,21 @@ throws is `X_JOB_ON_SETTLED_FAILED` and changes nothing. `run({ progress })` is
393
393
  ### A test's clock
394
394
 
395
395
  ```ts
396
- import { noWaitClock, resetScrapeClock, setScrapeClock } from '@ultimat3/scraping';
396
+ import { afterEach, beforeEach } from 'bun:test';
397
+ import { noWaitClock } from '@ultimat3/core';
398
+ import { installClock } from '@ultimat3/core/adapter';
397
399
 
398
- beforeEach(() => setScrapeClock(noWaitClock));
399
- afterEach(() => resetScrapeClock());
400
+ let release = (): void => {};
401
+ beforeEach(() => {
402
+ release = installClock(noWaitClock);
403
+ });
404
+ afterEach(() => release());
400
405
  ```
401
406
 
402
- | Clock | Sleeping | For |
407
+ | Clock (`@ultimat3/core`, since 31.0.0) | Sleeping | For |
403
408
  |---|---|---|
404
409
  | `noWaitClock` | one turn of the event loop; `now()` and deadlines are real | a run that waits on something the test does — an answer it publishes, a second run it starts |
405
- | `testScrapeClock()` | advances virtual time | a test OF a timeout |
410
+ | `frozenClock()` | advances virtual time | a test OF a timeout |
406
411
 
407
412
  A run waits on the process's clock unless its definition pins one, so the declaration under test
408
413
  carries no `clock:` written for the test's sake.
@@ -486,6 +491,47 @@ export const printInvoice = scrape({
486
491
  });
487
492
  ```
488
493
 
494
+ ### A route printed to PDF — `pdf()`
495
+
496
+ `pdf()` is a factory over **action** (`@ultimat3/scraping`, a `PRIMITIVE_FACTORIES` row). It renders one of the app's OWN routes through Chrome over raw CDP (`Page.printToPDF`), writes the bytes to a disk and answers `{ key, bytes, contentType: 'application/pdf' }`. Schema, policy, rate limit, meter and audit are the action's; HTTP, OpenAPI, MCP, `.job()` and `.as()` come with it. `As of 2026-11-09`.
497
+
498
+ ```ts
499
+ import { can } from '@ultimat3/policy';
500
+ import { t } from '@ultimat3/schema';
501
+ import { pdf } from '@ultimat3/scraping';
502
+ import { disk } from '@ultimat3/storage';
503
+
504
+ declare function printToken(orgId: string | undefined): string; // the app's short-lived token
505
+
506
+ export const invoicePdf = pdf({
507
+ input: t.object({ id: t.uuid }),
508
+ policy: can('invoices:read'),
509
+ route: ({ input }) => `/invoices/${input.id}/print`, // a PATH on the app's origin, never a URL
510
+ key: ({ input, ctx }) => `invoices/${ctx.actor?.orgId ?? 'none'}/${input.id}.pdf`,
511
+ storage: () => disk('documents'),
512
+ layout: { format: 'a4', marginMm: { top: 12, bottom: 12 }, printBackground: true },
513
+ headers: ({ ctx }) => ({ authorization: `Bearer ${printToken(ctx.actor?.orgId)}` }),
514
+ });
515
+ ```
516
+
517
+ | Rule | Refusal |
518
+ |---|---|
519
+ | the origin is `APP_URL`, read per call, or `origin: () => …` | none → `X_SCRAPE_PDF_ORIGIN_MISSING` (500) |
520
+ | the route is a path on that origin | else `X_SCRAPE_PDF_ROUTE_INVALID` (500) |
521
+ | the page's own status, read after `load` and `document.fonts.ready` | 4xx/5xx → `X_SCRAPE_PDF_ROUTE_FAILED` (502; 4xx terminal, 5xx and 429 retryable) |
522
+ | the layout, checked at declaration | `X_SCRAPE_PDF_OPTIONS_INVALID` |
523
+
524
+ | Bound | Detail |
525
+ |---|---|
526
+ | browsers at once | one Chrome per render, closed in a `finally`, at most `DEFAULT_PDF_MAX_CONCURRENT` (2) alive per process — `chromePdfRenderer({ maxConcurrent })` |
527
+ | a render with no slot | waits up to `queueTimeoutMs` (default: the render's own timeout), then `X_SCRAPE_PDF_BUSY` (503, retryable) |
528
+ | what the page may load | every request is paused on the page's session; one to the route's ORIGIN (scheme, host, port, compared whole) continues with `headers` added, every other is failed before it leaves — so the print token never reaches an `<img src>` a post carried, and a page cannot dial an internal host. A redirect off-origin is failed the same way |
529
+ | Chrome's sandbox | ON: a print renders pages that carry user content. A container that cannot grant it fails the launch with `X_CDP_LAUNCH_FAILED` quoting Chrome's "No usable sandbox"; opt out in one visible line, `chromePdfRenderer({ sandbox: false })` |
530
+
531
+ A test passes `renderer:` (any `PdfRenderer`); `chromePdfRenderer({ launch })` takes any `{ connection, close }`. The printing browser has no session of its own: a private route needs the app's short-lived token through `headers` ([Known gaps](Known-Gaps)).
532
+
533
+ **The CDP launcher moved.** `findChrome`, `launchChrome`, `launchFoundChrome`, `cdpConnect`, `cdpConnectOver`, the `Cdp*Error` classes and the `CHROME_*` / `LAUNCH_*` constants live in `@ultimat3/scraping/cdp` since 31.0.0 (its own entry, importing core only), and `X_CDP_*` are registered by scraping. It is their one import path: `@ultimat3/testing` no longer re-exports them, and `E2E_BROWSER_CLOSE_MS` is `LAUNCHED_CLOSE_MS` here ([Upgrading](Upgrading) #53).
534
+
489
535
  A social card for a row published at runtime is the same shape: `page.screenshot()` of the row's
490
536
  1200 x 630 card page, `disk().put()`, then `og: { image }` — [SEO](SEO#a-card-the-build-photographs-ogcapture)
491
537
  covers the cards a static build takes itself. `examples/dummy`'s `runs/jobs/print-statement.ts` is
package/wiki/Shapes.md CHANGED
@@ -42,7 +42,7 @@ scaffold's: `bunx x g --help`.
42
42
  |---|---|---|
43
43
  | `X_NEW_SHAPE_UNKNOWN` | `--shape` names no shape | `bunx @ultimat3/cli help new` lists them |
44
44
  | `X_NEW_SHAPE_CONFLICT` | `--shape` with `--no-example` | drop `--no-example`: a shape is its own example |
45
- | `X_NEW_SHAPE_GENERATE_FAILED` | a generator the shape runs in the new app (`dashboard`: `x g sign-in --password`) refused or failed | the `cd … && bunx x g … --json` it prints reproduces it; the framework's bug, so `bun test packages/cli/src/templates/shapes` |
45
+ | `X_NEW_SHAPE_GENERATE_FAILED` | a generator the shape runs in the new app (`dashboard`: `x g sign-in --password`) refused or failed | the `cd … && bunx x g … --json` it prints reproduces it; the framework's bug, so `bun test ./packages/cli/src/templates/shapes` |
46
46
 
47
47
  The first two refuse before a file is written, `--dry-run` included. A shape whose capability a
48
48
  generator owns runs that generator after its files land (`ShapeOverlay.generate`), never a copy of
@@ -52,7 +52,7 @@ its output: `--dry-run` lists those runs under `data.generate`.
52
52
 
53
53
  | Proof | Where |
54
54
  |---|---|
55
- | file set, leave-outs, no provider, every path `CLAUDE.md` names is written | `bun test packages/cli/src/templates/shapes` |
55
+ | file set, leave-outs, no provider, every path `CLAUDE.md` names is written | `bun test ./packages/cli/src/templates/shapes` |
56
56
  | each shape typechecks, lints and meets the error contract as written | the `x new --shape <shape>` variants in `packages/cli/src/scaffold-fixture.ts`, read by `emitted-contract`, `emitted-routes`, `emitted-suites` and `scaffold-typecheck.contract` |
57
57
  | `bun run setup && bun run verify` green on the first pass, then again over every generator | `scaffold-smoke` in `.github/workflows/ci.yml`, one row per shape — `scripts/ci-workflow-shape.test.ts` refuses a shape with no row |
58
58
 
package/wiki/Stability.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # Stability
2
2
 
3
- **From v30: at most one major every 90 days, the previous major gets security fixes for 6 months after its successor, and a removal is deprecated for at least one minor first.** Each rule is refused by a script, not remembered by a person — the table at the bottom names the code.
3
+ **From v31: at most one major every 90 days, the previous major gets security fixes for 6 months after its successor, and a removal is deprecated for at least one minor first.** Each rule is refused by a script, not remembered by a person — the table at the bottom names the code.
4
4
 
5
- **Next major window:** opens on `2027-02-05`, 90 days after 30.0.0 (2026-11-07). The bump that ships a major rewrites this line (`scripts/release.ts`).
5
+ **Next major window:** opens on `2027-02-08`, 90 days after 31.0.0 (2026-11-10). The bump that ships a major rewrites this line (`scripts/release.ts`).
6
6
 
7
7
  ## What is covered
8
8
 
@@ -26,7 +26,7 @@ A breaking change to any of these needs a major, and a major waits for its windo
26
26
  | `.x/` — the build cache, generated manifests, snapshots | regenerated by the CLI; never hand-edited, never read by an app |
27
27
  | the exact wording of a `cause:` or `fix:` line | the code is the contract; the text improves in any release |
28
28
  | a gate verdict getting stricter | a new `x verify` rule that reds an app waits on `next` like any break |
29
- | performance figures and budgets | measurements, re-measured each release ([Routes and render modes](Routes-And-Render-Modes#budgets)) |
29
+ | performance figures and budgets | measurements, each dated in its committed JSON under `scripts/bench/results/`, never promises. `bench.yml` is meant to re-measure the first-hour and HTTP figures weekly and on each release, as a pull request; `As of 2026-11-10` its one run measured and could not open that pull request, so the committed figures are older. Budgets: [Routes and render modes](Routes-And-Render-Modes#budgets) |
30
30
 
31
31
  Never "stable forever": a covered surface can change, in a scheduled major, with its entry in [Upgrading](Upgrading).
32
32
 
@@ -40,13 +40,15 @@ Never "stable forever": a covered surface can change, in a scheduled major, with
40
40
 
41
41
  | Release | When | Branch | npm dist-tag |
42
42
  |---|---|---|---|
43
- | major | at most once per 90 days from v30, counted from the previous major's `CHANGELOG.md` heading date | `next`, merged into `main` when the window opens | `latest` |
43
+ | major | at most once per 90 days from v31, counted from the previous major's `CHANGELOG.md` heading date | `next`, merged into `main` when the window opens | `latest` |
44
44
  | minor | weekly, when something shipped | `main` | `latest` |
45
45
  | patch to the current major | as needed | `main` | `latest` |
46
46
  | patch to the previous major | security fixes only, until 6 months after its successor shipped | `release/<major>.x` | `maint-<major>` |
47
47
  | prerelease of the next major — **planned, nothing ships one yet** | `release-tag.yml` cuts only `X.Y.Z` release commits, so no workflow publishes from `next` | `next` | `next` (`scripts/dist-tag.ts` already names it) |
48
48
 
49
- v30 is the exception that starts the clock: it carries every break queued before the promise existed, and `scripts/release.ts` does not refuse it.
49
+ **v31 is the stable line**, dated 2026-11-10 by its `CHANGELOG.md` heading. It was the exception that starts the clock: it carried every break queued before the promise bound anyone (74, [Upgrading](Upgrading#30x--3100-entry-by-entry)), and `scripts/release.ts` does not refuse it (`WINDOW_OPENS_AT_MAJOR` in `scripts/lib/major-window.ts`). From it on, a `BREAKING —` entry waits on `next` and a removal ships its deprecation minor first.
50
+
51
+ Ruling 2026-11-09: the clock moved from v30 to v31. v30 shipped 2026-11-07 while only our own apps ran Ultimate in production, so the window protected no one yet; v31 carries the breaks of plan 101-final-hardening-before-v31, and the window protects adopters from there.
50
52
 
51
53
  ## The support window
52
54
 
@@ -28,6 +28,8 @@ Swapping `local` for `s3` changes no call site, and `x dev` needs no S3 server.
28
28
  | `s3Driver` | `Bun.s3` | any S3-compatible endpoint — AWS, R2, a self-hosted gateway. The difference is `endpoint`, `region` and `forcePathStyle`. Credentials are env var **names**, never literals |
29
29
  | `memoryStorageDriver` | a `Map` in this process | a test's disk: `defineStorage({ disks: { uploads: memoryStorageDriver() } })`. Every method `localDriver` answers, the same refusals, the same signing rule; `objects()` is a copy of the stored bytes by key. Never a deployment's disk — a restart is every object gone |
30
30
 
31
+ A driver of your own is the `storage` adapter port: `StorageDriver` from `@ultimat3/storage/adapter`, `memoryStorageDriver` to copy, `behavesLike(storageDriverConformance, () => yourDriver())` to prove it — [Adapters](Adapters#storage). It is used in `defineStorage({ disks })`, or as `storage:` in `apps/<app>/runtime.ts` for the boot's one default disk.
32
+
31
33
  **A declaration holds a disk by THUNK, never by value.** `disk('sessions')` resolves through
32
34
  `defineStorage()`, which boot runs after an app's modules were evaluated — so a `scrape()` or any
33
35
  other declaration built at import time takes `() => disk('sessions')` and reads it when it is
@@ -207,7 +209,7 @@ export const storage = defineStorage({
207
209
  | | |
208
210
  |---|---|
209
211
  | `storage:read` | the `GET` requires it. An app that serves nothing through these routes leaves it out of its permission set: every read is then `401` for nobody and `403 X_FORBIDDEN` for everyone else (27.0.0). Until then an undeclared `storage:read` was a runtime `500 X_PERMISSION_UNKNOWN`, which `x verify`'s `policy` step reported |
210
- | the boot's own disk | still built. In production with no `S3_ENDPOINT`, that is a local disk and still needs `STORAGE_SIGNING_SECRET`. To skip it, export `runtime = { storage }` from `apps/<app>/runtime.ts`. `runRole` reads that file, and it replaces the env-selected disk entirely |
212
+ | the boot's own disk | still built. In production with no `S3_ENDPOINT`, that is a local disk and still needs `STORAGE_SIGNING_SECRET`. To skip it, set `storage:` in `export const runtime = { … }` (`apps/<app>/runtime.ts`) to a `StorageDriver`: the boot registers it as its one disk, under the driver's own `name`, in place of the `S3_ENDPOINT`/embedded decision. Several disks are still `defineStorage()`, which wins ([Adapters](Adapters#storage)) |
211
213
  | `definedStorage()` | the registry or `undefined`, without a throw. It is the question the routes ask |
212
214
 
213
215
  ## Who may read a stored object
@@ -306,14 +308,13 @@ nothing here answers `immutable`: `/media` once did on a shared key, and a CDN t
306
308
  strangers for a year and never refreshed it. A public image is an `asset()`, or your own route over
307
309
  `objectResponse`.
308
310
 
309
- ## Attachments, quarantine, orphans
311
+ ## Attachments and orphans
310
312
 
311
313
  An upload lands under `org/<org>/pending/…` before its row exists, and is promoted once it has one:
312
314
 
313
315
  | Call | Does |
314
316
  |---|---|
315
317
  | `promoteAttachment({ disk, key, orgId, target, policy })` | measure, copy, then delete, onto `org/<org>/<entity>/<id>/<field>/…`. **`policy` is required** — pass the one the upload was granted under: the object's size is read with `stat()` and one over `policy.maxBytes` is `X_STORAGE_TOO_LARGE` and stays pending. Only a **pending** key: another row's attached key is `X_STORAGE_NOT_PENDING`. A second call for a key an earlier call already moved is `X_STORAGE_ALREADY_PROMOTED` (409, `meta.attachedKey`) and touches nothing: answer the row that holds that key, and never delete it in your own cleanup |
316
- | `grantUpload({ …, quarantine: true })` → `releaseQuarantine({ disk, key, orgId })` | the place for your scanner: a quarantined key cannot be promoted (`X_STORAGE_QUARANTINED`) until your scan job releases it. The scanner is your app's (axiom 8) |
317
318
  | `sweepOrphans({ disk, orgId, olderThanMs })` | deletes stale `pending/` keys of one org and answers `{ deleted, failed }` — a refused delete is reported, never counted as done |
318
319
  | `deleteVariants({ disk, key })` | deletes every stored variant of one source, of every revision, and answers `{ deleted, failed }`. The source is yours to delete. A variant keeps its source's prefix, so an org-wide erasure by prefix already collects them |
319
320
 
@@ -339,7 +340,38 @@ does not pass. Bytes past the window are not sniffed on any path through promoti
339
340
  | over 4,096 bytes of leading whitespace (`MAX_LEADING_WHITESPACE`), on every path | no real file opens that way, and past the window nothing is seen |
340
341
  | a disk whose `maxGetBytes` is under the window | its own `X_STORAGE_TOO_LARGE`: the ceiling bounds the range |
341
342
 
342
- A grant with a `target` has no promotion step: [Known gaps](Known-Gaps).
343
+ A grant with a `target` has no promotion step: [Known gaps](Known-Gaps). With an `uploadScanner` installed it is refused outright, by `grantUpload` and `grantMultipart` alike (`X_STORAGE_TARGET_UNSCANNED`, 500): grant with no `target` and promote.
344
+
345
+ ## Scanning uploads — the `uploadScanner` port
346
+
347
+ Rule: an `uploadScanner` returned from `apps/<app>/runtime.ts` is asked about every upload `promoteAttachment` attaches. `As of 2026-11-09`. It scans a copy THIS call made: under `pending/scan/`, server-named — so no presigned URL can rewrite it after the scan — and its own, so a doubled confirm never scans or deletes another attempt's bytes. That copy is what is attached; one scan is final.
348
+
349
+ | Verdict | `promoteAttachment` |
350
+ |---|---|
351
+ | `{ verdict: 'clean' }` | promotes |
352
+ | `{ verdict: 'infected', signature }` | deletes the pending upload and the scan copy; `X_STORAGE_UPLOAD_INFECTED` (422, `meta.signature`) |
353
+ | `{ verdict: 'hold', reason }` | deletes the scan copy, the upload stays pending; `X_STORAGE_QUARANTINED` (409, `meta` `{ key, scanner, reason }`). A decision made elsewhere — a review queue, an async vendor scan — has not cleared it yet; the same confirm promotes once the scanner answers `clean`. No policy overrides it, and a `holds: true` scanner that cannot answer is `X_STORAGE_SCAN_UNAVAILABLE` even under `onScanUnavailable: 'accept'` |
354
+ | the scanner rejects, or the copy cannot be read for it (daemon down, timeout, a reset read) | deletes the scan copy, the upload stays pending — a retry once the scanner is back is a fresh confirm; `X_STORAGE_SCAN_UNAVAILABLE` (503). Fail closed in every environment; `uploadPolicy({ onScanUnavailable: 'accept' })` promotes unscanned instead — **except for a scanner declaring `holds: true`**, whose outage always refuses: it may be the store that knows what is held. Infected and held are refused under either |
355
+
356
+ | Fact | Detail |
357
+ |---|---|
358
+ | the port | `UploadScanner = { name, holds?, scan({ key, pendingKey, size, contentType, body }) → Promise<ScanVerdict> }` on `@ultimat3/storage/adapter`. `key` is the per-attempt scan copy, `pendingKey` the upload's own key, stable across retries — what a `hold` is decided by. "Cannot decide" is a rejection, never a verdict. A scanner that answers `hold` declares `holds: true`; a `hold` from one that did not is `X_INVARIANT`, nothing attached |
359
+ | the reference | `memoryUploadScanner()` flags the EICAR test string (`EICAR_TEST_STRING`), across chunk boundaries |
360
+ | prove yours | `behavesLike(uploadScannerConformance, () => yours)` from `@ultimat3/testing/conformance` |
361
+ | ClamAV | the app's adapter (axiom 8): stream `body` to clamd's `INSTREAM` over `Bun.connect`; `stream: OK` → clean, `stream: <sig> FOUND` → infected, anything else → reject |
362
+ | no scanner installed | nothing is scanned. The v30 `grantUpload({ quarantine: true })` + `releaseQuarantine` flow is deleted — a deferred decision is the `hold` verdict ([Upgrading](Upgrading) entry 57) |
363
+
364
+ ```ts
365
+ // apps/web/runtime.ts
366
+ import type { RuntimeOverrides } from '@ultimat3/cli/serve';
367
+ import type { UploadScanner } from '@ultimat3/storage/adapter';
368
+
369
+ declare function clamdScanner(options: { host: string; port: number }): UploadScanner;
370
+
371
+ export const runtime = {
372
+ uploadScanner: clamdScanner({ host: 'clamav', port: 3310 }),
373
+ } satisfies Partial<RuntimeOverrides>;
374
+ ```
343
375
 
344
376
  ## Images
345
377
 
@@ -361,6 +393,26 @@ encode `png`, `jpeg` and `webp`; `avif` is key and `srcset` math only. `variantK
361
393
  `srcsetDescriptors()` and `fitDimensions()` are pure, which is how [SEO](SEO) builds `srcset`
362
394
  without decoding a byte.
363
395
 
396
+ ### One kept variant — `variant()`
397
+
398
+ `variant(key, { disk, images, width, format? })` → `{ key, object, created }`. `As of 2026-11-09`. Made by the `images` driver you pass (any `@ultimat3/seo` `ImageTransformDriver` — `runtime.ts`'s `images`, `builtinImageDriver({ read })`, a CDN's), stored under `variantKey(key, { width, format, revision })`. A second call is a `stat`, never a decode; an overwritten source is a new revision, hence a new key. `format` omitted keeps a png/jpeg/webp source's encoding.
399
+
400
+ | Refusal | Code |
401
+ |---|---|
402
+ | source missing | `X_STORAGE_NOT_FOUND` |
403
+ | source not a raster image (PDF, SVG), a gif/avif source with no `format`, a driver that answered another encoding | `X_IMAGE_UNSUPPORTED` |
404
+ | source overwritten while the driver read it (nothing stored) | `X_STORAGE_OBJECT_CHANGED` |
405
+
406
+ ```ts
407
+ import { builtinImageDriver } from '@ultimat3/seo';
408
+ import { disk, variant } from '@ultimat3/storage';
409
+
410
+ declare const coverKey: string;
411
+
412
+ const images = builtinImageDriver({ read: async (src) => (await disk().get(src)).bytes });
413
+ export const thumbnail = await variant(coverKey, { disk: disk(), images, width: 640, format: 'webp' });
414
+ ```
415
+
364
416
  ### Warm the variants after the upload — `warmVariants`
365
417
 
366
418
  The first request for each width otherwise pays the decode on the request path. A job the upload