@ultimat3/core 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 (67) hide show
  1. package/CLAUDE.md +54 -58
  2. package/README.md +70 -27
  3. package/package.json +3 -2
  4. package/src/adapter-slot.ts +42 -0
  5. package/src/adapter.ts +24 -0
  6. package/src/audit.ts +31 -14
  7. package/src/aws-sigv4.ts +9 -3
  8. package/src/cache-vocabulary.ts +1 -1
  9. package/src/client-problem.ts +10 -3
  10. package/src/clock.ts +68 -14
  11. package/src/config-defaults.ts +4 -4
  12. package/src/config-keys.ts +1 -1
  13. package/src/config-removed.ts +11 -1
  14. package/src/config.ts +16 -20
  15. package/src/context.ts +2 -2
  16. package/src/cursor.ts +3 -11
  17. package/src/der.ts +65 -0
  18. package/src/error-render.ts +27 -1
  19. package/src/error-reporter-chain.ts +1 -1
  20. package/src/error-reporter-sentry-hooks.ts +85 -0
  21. package/src/error-reporter-sentry.ts +99 -7
  22. package/src/error-reporter.ts +39 -11
  23. package/src/errors.ts +3 -1
  24. package/src/exports/error-contract.ts +4 -14
  25. package/src/exports/observability.ts +57 -17
  26. package/src/exports/secrets.ts +4 -18
  27. package/src/failure-capture.ts +22 -13
  28. package/src/gate-shapes.ts +88 -0
  29. package/src/host-rules.ts +13 -1
  30. package/src/html-escape.ts +7 -1
  31. package/src/ids.ts +59 -10
  32. package/src/image/png-pixels.ts +14 -8
  33. package/src/index.ts +123 -136
  34. package/src/instrument-events.ts +272 -0
  35. package/src/instrument-semconv.ts +65 -0
  36. package/src/instrument-stacks.ts +38 -0
  37. package/src/instrument.ts +194 -0
  38. package/src/keyed-fingerprint.ts +7 -11
  39. package/src/lifecycle-signals.ts +5 -3
  40. package/src/lifecycle.ts +27 -0
  41. package/src/logger-record.ts +35 -0
  42. package/src/logger.ts +24 -16
  43. package/src/mcp-exposure.ts +17 -0
  44. package/src/metrics-semconv.ts +124 -0
  45. package/src/metrics.ts +19 -16
  46. package/src/otlp-batch.ts +78 -0
  47. package/src/otlp-log-exporter.ts +180 -0
  48. package/src/otlp-metric-exporter.ts +2 -1
  49. package/src/otlp-post.ts +22 -2
  50. package/src/otlp-span-exporter.ts +10 -59
  51. package/src/otlp.ts +27 -9
  52. package/src/outbound-instrument.ts +82 -0
  53. package/src/outbound.ts +5 -4
  54. package/src/page-meta.ts +6 -0
  55. package/src/page.ts +23 -5
  56. package/src/registrar.ts +269 -0
  57. package/src/route-vocabulary.ts +11 -2
  58. package/src/safe-url.ts +10 -8
  59. package/src/seal-errors.ts +14 -4
  60. package/src/seal-keys.ts +11 -7
  61. package/src/secret-source.ts +125 -0
  62. package/src/secrets-errors.ts +32 -12
  63. package/src/secrets-store.ts +30 -26
  64. package/src/sleep-clock.ts +70 -0
  65. package/src/telemetry.ts +90 -31
  66. package/src/type-pins.ts +19 -16
  67. package/src/log-tee.ts +0 -73
package/CLAUDE.md CHANGED
@@ -2,24 +2,25 @@
2
2
 
3
3
  Tier 0. **Imports no `@ultimat3/*` package except `@ultimat3/schema`** (the declared `core → schema`
4
4
  edge; `schema → core` stays forbidden). Everything else depends on this, so a change here is a
5
- change to every package.
5
+ change to every package. A row or rule marked `†` has its full text in
6
+ [`docs/history/core-rules.md`](../../docs/history/core-rules.md).
6
7
 
7
8
  | Rule | |
8
9
  |---|---|
9
10
  | Deps | `@ultimat3/schema` only (`bun-types`: types) |
10
- | Errors | never `throw new Error`. A FRAMEWORK code: `bun run new-error-code` (a class, `CORE_CODE_TITLES` or the package's `errors.ts`, a `--status`/`--off-socket` decision, a wiki row). An APP code: `defineError()` (`define-error.ts`), which registers title, status and retry in one call and needs no wiki row; its own module, so an `UltimateError`-only chunk never retains it (`define-error-bytes.test.ts`) |
11
+ | Errors | never `throw new Error`. Framework code: `bun run new-error-code`; app code: `defineError()` (`define-error.ts`) † |
11
12
  | Values in a message | `renderCauseValue()` / `renderFixLiteral()`; never raw `JSON.stringify`, `String()` or `${…}` on an `unknown` |
12
13
  | A value in a `fix:` a shell READS | `renderFixShellArg(value, placeholder)` — `renderFixLiteral`'s double quotes leave `$(…)`, `` ` `` and `${…}` live. An ordinary path or URL passes through; anything a shell would read becomes the placeholder |
13
- | Whether that value TRAVELS | `isFixShellSafe(value)`, the predicate `renderFixShellArg` is built on. A placeholder is not a runnable command, so a `fix:` whose value sits mid-command asks this first and emits PROSE when the answer is no (`@ultimat3/auth`'s `jwks.ts`, `@ultimat3/scraping`'s `profileLocked`) |
14
+ | Whether that value TRAVELS | `isFixShellSafe(value)`; a value that does not travel makes the `fix:` prose, never a placeholder mid-command † |
14
15
  | Rendering the 3-line format | nothing to remember — `UltimateError`'s CONSTRUCTOR escapes `code`, `title`, `cause`, `fix` and `docs` with `singleLine()`. Call it yourself only for a shape this class never built (a `Finding`) |
15
16
  | A value a CALLER supplied | `describeValue()` — shape, never content. `renderCauseValue` is safe against throwing, not against leaking |
16
17
  | Reading a caught value | `renderThrowable()` / `isThrownError()` / `stringField()` / `failureStack()`; never `error.message`, `instanceof Error` or `typeof error.code === 'string'` |
17
18
  | New code | add to `CORE_CODE_TITLES` in `core-error-codes.ts` — a side-effect anchor the barrel bare-imports, so `UltimateError` alone never carries the table |
18
19
  | Where an error points | `ERROR_DOCS_URL` — one constant, never a per-code URL. `docs:` is omitted at construction and resolved from the registry |
19
- | Time | take a `Clock`; `Date.now()` / `new Date()` only inside `clock.ts` |
20
+ | Time | take a `Clock` (a `SleepClock` to wait); `Date.now()` / `new Date()` only in `clock.ts`; a waiting timer only in `sleep-clock.ts` |
20
21
  | Context | never thread `ctx` as a parameter — `useContext()` |
21
22
  | A value ambient across an `await` | `asyncContext<T>(subject)` from `async-context.ts`, in **every** package — never `new AsyncLocalStorage` |
22
- | Exports | explicit in `src/index.ts`; no `export *`. FIVE public subpaths (`./page`, `./outbound`, `./redis`, `./render-node`, `./render-nodes`), one INTERNAL (`./internal/error-status`); nothing that constructs an error joins `./page` (`page-bundle.test.ts`, 1.5 kB). Full rule: `docs/history/core.md` |
23
+ | Exports | explicit in `src/index.ts`; no `export *`. Six public subpaths (`./adapter`, `./page`, `./outbound`, `./redis`, `./render-node`, `./render-nodes`), one internal (`./internal/error-status`); nothing that constructs an error joins `./page` (`page-bundle.test.ts`) † |
23
24
  | Files | < 200 LOC, 500 hard ceiling, one responsibility, `kebab-case.ts`, test beside source |
24
25
  | Type claims | `type-pins.ts`, never a `.test.ts` — `tsconfig.json` excludes tests |
25
26
 
@@ -28,75 +29,71 @@ top-level `UltimateError` use in `error-codes.ts`.
28
29
 
29
30
  ## Invariants
30
31
 
31
- - **`async-context.ts` is the framework's ONE `AsyncLocalStorage`.** Construction is deferred to
32
- the first `get()`/`run()`, so a browser bundle can evaluate the module; reads degrade to
33
- `undefined`, writes throw `X_ASYNC_CONTEXT_UNAVAILABLE`. `scripts/async-context-guard.ts` refuses a
34
- `new AsyncLocalStorage` or an import of the class anywhere else; `scripts/browser-barrel.test.ts`
35
- covers `await import('node:async_hooks')`.
32
+ - **`async-context.ts` is the framework's ONE `AsyncLocalStorage`** (`scripts/async-context-guard.ts`). †
36
33
  - **`error-render.ts` imports nothing** except schema's re-exports (`describeValue`, `charCount`) —
37
34
  an error factory that dies formatting its own message is the failure it exists to prevent.
38
35
  `scripts/error-render.ts` (`X_ERROR_RENDER_UNSAFE`) cannot see a value laundered through a local
39
36
  helper.
40
- - **`singleLine` keeps the 3-line contract to three lines, applied in the CONSTRUCTOR** so every
41
- door (`format()`, `.message`, `.cause`, `toJSON()`) is covered once. It touches only C0 controls
42
- and DEL — a cause keeps its quotes and backslashes. `@ultimat3/schema` carries a deliberate
43
- duplicate, pinned by `single-line-pin.test.ts` HERE, with `ERROR_DOCS_URL`. The brand symbol is
44
- NOT a copy: `ULTIMATE_ERROR_BRAND` is schema's one declaration, imported by `errors.ts`.
37
+ - **`singleLine` keeps the 3-line contract to three lines, applied in the CONSTRUCTOR.** †
45
38
  - **`core → schema` is declared: import a schema value, never copy it.** Bundle cost:
46
39
  `docs/architecture/01-package-map.md`; it depends on `@ultimat3/schema` keeping `sideEffects: false`.
47
40
  - **A string's length is CODE POINTS** — `validators.ts` rejects in that unit and
48
41
  `json-schema.ts` publishes `minLength` in it. `parseId`/`uuidTimestamp` describe a rejected id and
49
42
  never echo it: a value baked into a message has no log field key to redact.
50
- - **A test never patches `process.stdout` to read a log line**: `setLogSink(sink)` is the seam, and the
51
- test preloads install one that drops every line (`LOG_LEVEL` named = not installed). It decides
52
- WHERE a line goes, never whether — the level is untouched.
43
+ - **A test never patches `process.stdout` to read a log line**: `installLogSink(sink)` is the seam
44
+ — on the `.` barrel, a test seam and not a port (`scripts/lib/adapter-port-pins.ts`); a stack,
45
+ `finally` releases; preloads install one that drops lines (`LOG_LEVEL` named = none).
46
+ WHERE a line goes, never whether: the level is untouched.
53
47
  - `logger.ts` must not import `context.ts` (`context.ts` injects ids via `setLoggerContextFields()`).
54
48
  It imports `secret.ts` one way only: `secret.ts` owns `REDACTED`, `logger.ts` re-exports it.
55
49
  - **`ActorFacts` is the app's extension point on `Actor`** (module augmentation). Core never declares
56
50
  a fact; every fact reads `T | undefined` through `actorFact()` so an unresolved fact denies.
57
- `type-pins.ts` pins the shape against a local sample.
51
+ `type-pins.ts` pins the shape.
58
52
 
59
53
  | Concept | Owner | Note |
60
54
  |---|---|---|
61
55
  | which deploy this is | `environment.ts` (`ULTIMATE_ENV`) | the twin of `ROLE`; never a second env var |
62
- | one-home helpers | `store-mode` `html-escape` `cookie` `fnv1a` `pg-executor` `deprecation` `aws-sigv4` | never copied (`X_HELPER_COPY`). Full rule: `docs/history/core.md` |
63
- | the ONE keyed hash | `hmac.ts` (`hmac(alg, key, data, encoding?)`) | `node:crypto`'s `createHmac`: a keyed `Bun.CryptoHasher` throws a stale failed-EC-import error (Bun 1.4.4). `bun run keyed-hasher` (`X_KEYED_HASHER`). Full rule: `docs/history/core.md` |
64
- | what this process does | `roles.ts` (`ROLE`) | |
65
- | how a route renders, caches offline and hydrates | `route-vocabulary.ts` (`RENDER_MODES`, `OFFLINE_STRATEGIES`, `HYDRATE_STRATEGIES`) | every union is `(typeof ARRAY)[number]`, pinned in `type-pins.ts`; `scripts/render-modes.test.ts` refuses a second declaration. Re-export it, never restate it |
66
- | which of two route patterns wins a pathname | `route-rank.ts` (`routeRank`) | the request router's order as one integer: segment by segment, literal 3 > `:param` 2 > `*catch-all` 1, ENDED 4, packed base 5 over 22 segments. Full rule: `docs/history/core.md` |
56
+ | one-home helpers | `store-mode` `html-escape` `cookie` `fnv1a` `pg-executor` `deprecation` `aws-sigv4` `der` | never copied (`X_HELPER_COPY`). Rows here: `docs/history/core.md` |
57
+ | an X.509 certificate's public key | `der.ts` (`x509Spki(der)`) | the ONE DER walk to the `subjectPublicKeyInfo` Web Crypto imports: auth's SAML key and mail's SNS key both read it; trailing bytes refused |
58
+ | the ONE keyed hash | `hmac.ts` (`hmac(alg, key, data, encoding?)`) | `bun run keyed-hasher` (`X_KEYED_HASHER`) † |
59
+ | this process's job | `roles.ts` (`ROLE`) | |
60
+ | `allowHosts` | `host-rules.ts` | a wildcard admits no inward literal, no `localhost`/`*.localhost`; exact rules do |
61
+ | which surface a route lives on, how it renders, caches offline and hydrates | `route-vocabulary.ts` (`SURFACES`, `RENDER_MODES`, `OFFLINE_STRATEGIES`, `HYDRATE_STRATEGIES`) | every union is `(typeof ARRAY)[number]`, pinned in `type-pins.ts`; `scripts/render-modes.test.ts` refuses a second declaration. Re-export it, never restate it; `@ultimat3/render` re-exports the `Surface` type only, never `SURFACES` (`X_HELPER_COPY`) |
62
+ | which of two route patterns wins a pathname | `route-rank.ts` (`routeRank`) | the request router's order as one integer: segment by segment, literal 3 > `:param` 2 > `*catch-all` 1, ENDED 4, packed base 5 over 22 segments |
67
63
  | an `http.path` template (`/orders/:id`) | `route-path-template.ts` (pure, also on `./page`) + `route-path-merge.ts` (`mergePathParams`, `X_HTTP_PATH_INPUT_CONFLICT`) | `action` and `query` both pin one and share a tier; never a copy in either |
68
64
  | `errors:` | `declared-errors.ts`, `-openapi.ts`, `-scan.ts` | ONE copy for `action` and `query`. The HTTP status is passed in (`ErrorStatusOf`): http is above core. The scan is test-time only |
69
- | a session's loss, an island's poll | `session-lost.ts` (`noteRefusal`, called by `client-dispatch.ts`; a cell on the page handle, cleared by `rescope()`), `visible-interval.ts` (the ONE poll an island takes) | both on `./page`, pinned by `page-bundle.test.ts` |
65
+ | a session's loss, an island's poll | `session-lost.ts`, `visible-interval.ts` | the ONE poll an island takes; both on `./page` † |
70
66
  | which rungs a cache ladder has | `cache-vocabulary.ts` (`CACHE_TIERS`) | `@ultimat3/cache`'s read order, imported (no `TIER_ORDER` alias). `isr` is a `RenderMode`, never a tier |
71
67
  | which build of the APP this is | `app-version.ts` (`APP_VERSION`) | one reader, `dev` by default |
72
68
  | the values | `env.ts` | `checkEnv().values` holds REAL secrets — printing goes through `maskedEnvValues()` |
73
69
  | `.env.example` | `env-example.ts` | a projection of the schema, never hand-maintained |
74
70
  | loading `.env` | **Bun**, not us | `envFileCandidates()` documents the measured order; there is no `.env.staging` |
75
- | how long to wait, and whether to wait at all | `backoff.ts` + `retry-loop.ts` + `retry.ts` | one curve, one loop (no context, for `client-flight.ts`), one executor over it that reads the ambient signal and deadline: the ONE place a loop meets its caller's lifetime, `runToCompletion` the one way out; `jitter` is REQUIRED on a retry policy and defaults to `none` on the arithmetic. `attempt` is 1-based |
71
+ | how long to wait, and whether to wait at all | `backoff.ts` + `retry-loop.ts` + `retry.ts` | one curve, one loop, one executor that meets the caller's signal and deadline; `jitter` REQUIRED on a retry policy; `attempt` is 1-based † |
76
72
  | N callers on one key | `single-flight.ts` | identity-checked eviction, optional injected deadline, optional injected `signal`: a live joiner re-leads after its leader's abort. Reads no context |
77
73
  | how many at once | `flight-gate.ts` | hand-over on release, refusal past `maxQueued`, injectable `overflow:` refusal |
78
74
  | whether an answer still applies | `generation-fence.ts` | `X_SUPERSEDED` / `isSuperseded` |
79
75
  | which HTTP statuses are worth repeating | `retryable-status.ts` | `>= 500` plus 408, 409, 425, 429 |
80
- | how long this request has left | `request-budget.ts` (`Ctx.deadlineAt`, `REQUEST_TIMEOUT_HEADER`) | `@ultimat3/http`'s `startDeadline` is the one writer of the instant; `traceHeaders()` the one writer of the header. A spent budget sends nothing, never `0` |
81
- | the above, composed into one typed-client call | `client-flight.ts` + `client-wire.ts` | shared by `@ultimat3/action` and `@ultimat3/query` (both tier 3), re-exported by both. Declares no code of its own. A gate slot per ATTEMPT; the wait holds none, ends on `bump()` or the caller's abort |
82
- | a stream-declaring action, read in the browser | `client-stream.ts` | `clientStream`: `POST` with `accept: text/event-stream` through `client-dispatch.ts`'s `dispatchStream` (the ONE browser `fetch`; body handed back unread), never `EventSource` (cannot POST, skips the credentials rule); `clientTransport`'s credentials, headers, caller's signal, session fence and problem decode; a `chunk` frame yields, `done` returns, `error` throws its problem at its own status. A JSON answer is `clientTransport`'s `settleAnswer` (envelope, records, dates), so `stream()` and `call()` agree. Never retried |
83
- | the browser's one HTTP function, records envelope, per-tab handle and principal fence | `client-transport.ts`, `client-dispatch.ts`, `client-problem.ts`, `client-retry-after.ts`, `client-paths.ts`, `record-envelope.ts`, `record-sink.ts`, `client-scope.ts` | `pageClient()` is the ONE `globalThis` write (`Symbol.for('ultimate.client')`); `clientTransport` never value-imports `clientFlight` or `traceHeaders()` (the OUTBOUND SLOT, `outbound-headers.ts`). A write never dedupes. Full rule: `docs/history/core.md` |
84
- | a write's public name | `write-digest.ts` (`writeDigest`, `isWriteDigest`, also on `./page`) + `write-origin.ts` (`withWriteOrigin`, `currentWriteOrigin`, `WRITE_ORIGIN_WAL_PREFIX`, server-only) | SHA-256 of an idempotency key, 32 hex; carried action → entity → WAL → realtime `records` frame. A malformed value runs the work unnamed: a label, never a gate |
76
+ | how long this request has left | `request-budget.ts` (`Ctx.deadlineAt`) | http's `startDeadline` writes the instant, `traceHeaders()` the header † |
77
+ | the above, composed into one typed-client call | `client-flight.ts` + `client-wire.ts` | shared by `action` and `query`, re-exported by both; a gate slot per ATTEMPT † |
78
+ | a stream-declaring action, read in the browser | `client-stream.ts` | `clientStream`: `POST` + `accept: text/event-stream`, never `EventSource`. Full rule: `docs/history/core-moved-2026-11-09.md` |
79
+ | the browser's one HTTP function and per-tab handle | `client-transport.ts`, `client-dispatch.ts`, `client-*.ts`, `record-envelope.ts`, `record-sink.ts` | `pageClient()` is the ONE `globalThis` write. A write never dedupes † |
80
+ | a write's public name | `write-digest.ts` + `write-origin.ts` (server-only) | SHA-256 of an idempotency key: a label, never a gate † |
85
81
  | which row survives a conflict | `conflict-policy.ts` (`ConflictPolicy`, `resolveConflict`, `Row`) | read by `action`'s mutator and `realtime`'s rebase |
86
- | where a visitor's light/dark choice is stored | `theme-storage.ts` (`THEME_STORAGE_KEY`, also on `./page`) | render's boot script reads it, ui's toggle writes it — both tier 4, so the one literal lives here. Persisted in browsers: never respelled |
82
+ | where a visitor's light/dark choice is stored | `theme-storage.ts` (`THEME_STORAGE_KEY`, on `./page`) | persisted in browsers: never respelled † |
87
83
  | the four shapes of an async region | `async-state.ts` (`AsyncState`) | `realtime` returns it, `ui` renders it. `bun run render-modes` refuses a second status union sharing three members |
88
- | the audit record + one sink | `audit.ts` | `action` + `query`; `AUDIT_RECORD_FIELDS` pins both |
84
+ | the audit record + one sink | `audit.ts` | `action` + `query` read `getAuditSink()`; the boot installs (`installAuditSink`, `./adapter`); `AUDIT_RECORD_FIELDS` pins both |
85
+ | gate shapes | `gate-shapes.ts` | shared by `action` and `query`: the audit outcome, the rate-limit subject/scope/limit. One copy, never one per primitive |
89
86
  | is this `unknown` a keyed record? | `json-object.ts` (`isJsonObject`) | narrows a shape; does not certify provenance |
90
87
  | may a caller read this 5xx `cause`? | `public-cause.ts` (`hasPublicCause`) | one table for http, mcp, ai. `registerPublicCause` is `@ultimat3/http`'s `registerProblemMeta` writing it — never an app's door |
91
88
  | is this field a credential? | `logger.ts` (`isRedactedKey`) | exact keys + `CREDENTIAL_NAME`; a bare `token` suffix is NOT one (`idempotencyToken`, `maxTokens`). Log line, monitor envelope and `action`'s audit ask it |
92
89
  | a value that must not be printed | `secret.ts` | redacted by VALUE; `revealSecret()` is the one, greppable, way out |
93
- | an `Intl` formatter cache, and the screen in front of it | `intl-cache.ts` (`cachedFormatter`, `canonicalLocale`, `assertLocale`, `MAX_CACHED_FORMATTERS`, `MAX_LOCALE_EXCERPT`) | a locale arrives from a header: refuse a non-tag (`X_LOCALE_INVALID`), key canonically AND bound the cache — never a copy of any of the three. |
90
+ | an `Intl` formatter cache, and the screen in front of it | `intl-cache.ts` | refuse a non-tag (`X_LOCALE_INVALID`), key canonically, bound the cache — one file † |
94
91
  | the text direction of a locale | `locale-direction.ts` (`directionOf`, `isRtl`, `Direction`) | import from here, never `@ultimat3/i18n`; here so `@ultimat3/ui` skips the i18n barrel |
95
92
  | the committed encrypted values | `secrets.ts` (envelope) + `secrets-store.ts` (files, `installSecrets`) | plaintext is a flat map of ENV NAMES; there is no `secrets.get()` |
96
- | ONE sealed value | `seal.ts` (`seal`, `open`, `openText`, `sealAll`) + `seal-keys.ts` (the ring) + `seal-errors.ts` | the framework's one AES call above the envelope: `entity`'s sealed column and `scraping`'s stored session call it, never WebCrypto. `purpose` is required and is AAD |
97
- | one outbound HTTP call | `outbound.ts` + `outbound-attempt.ts` / `-hops.ts` / `-read.ts` / `-dial.ts` / `-errors.ts` / `-types.ts`, entry `outbound-subpath.ts` | never on the barrel (`outbound-subpath.test.ts`). `retry()` owns the clamp to `ctx`, so no second clamp. Its ten codes register their retry class in `outbound-errors.ts`, NOT `error-retry.ts`'s table, which rides every page. `screenDial` holds the framework's one `Bun.dns.lookup` |
93
+ | ONE sealed value | `seal.ts` + `seal-keys.ts` + `seal-errors.ts` | the framework's one AES call above the envelope; `purpose` is required and is AAD † |
94
+ | one outbound HTTP call | `outbound*.ts`, entry `outbound-subpath.ts` | never on the barrel; `screenDial` holds the one `Bun.dns.lookup` † |
98
95
  | is a dependency down | `breaker.ts` | the machine only; the trigger is `classify` or a hand-called `failed()`. Every settle takes the `admit()` ticket. `X_BREAKER_OPEN` registers its class here |
99
- | what an element carries, for a test | `render-nodes.ts` (`renderNodes`, `nodesOf`, selectors) + `render-node.ts` (`JSX_NODE`, `ISLAND_NODE`, `HOLE_NODE`) | the one walker: `ui`, `admin` and apps import the subpath, never a copy. Islands and holes are branded ARRAYS, tested before `Array.isArray`; a hole is walked as `fallback` and `error`, never its deferred `children` |
96
+ | what an element carries, for a test | `render-nodes.ts` + `render-node.ts` | the one walker, imported from the subpath, never copied † |
100
97
 
101
98
  - **`installSecrets()` is the ONLY path from `secrets.enc.json` to an app value**, landing in
102
99
  `process.env` before `defineEnv` reads it. The real environment always wins.
@@ -108,30 +105,24 @@ top-level `UltimateError` use in `error-codes.ts`.
108
105
  - **`schema-error-codes.ts` registers `@ultimat3/schema`'s codes** (schema cannot call core), and
109
106
  derives their retry classification from the same set. It is a `SIDE_EFFECTS_ANCHORS` entry.
110
107
  - **`canonical-json.ts`: `canonicalJson` is INJECTIVE and `fingerprint` is SHA-256/16 of it** — the
111
- hash every in-memory sharing key is taken over (`query`'s `queryHash`, `realtime`'s `qid`).
112
- `NaN`, `±Infinity` and `-0` are bare tokens; `Date`, `Map` and `Set` are TAGGED. Never a
113
- fourth copy, never parseable (`@ultimat3/action`'s `stableStringify` is the document form).
108
+ hash form; `@ultimat3/action`'s `stableStringify` is the document form. †
114
109
  - **A PERSISTED fingerprint is `keyedFingerprint`** (`keyed-fingerprint.ts`: HMAC under a per-purpose
115
110
  key derived from the cursor secret, `h1:` versioned) — `action`'s idempotency `requestHash`. An
116
111
  unkeyed prefix in a table is an offline oracle for a short account number in the input.
117
112
  - **`decimal-order.ts`'s `compareDecimalText` answers `undefined` for a non-decimal**, and only a
118
113
  caller that knows the column's kind may ask (`@ultimat3/entity`'s `compareByKind`) — never
119
114
  `@ultimat3/query`, whose `OrderKey` has no kind.
120
- - **The flight layer** (`backoff.ts`, `retry-loop.ts`, `retry.ts`, `single-flight.ts`, `flight-gate.ts`,
121
- `generation-fence.ts`, `retryable-status.ts`, `client-flight.ts`, `client-wire.ts`) imports
122
- nothing but this package, runs nothing at import, and injects every source of non-determinism
123
- (roll, sleep, clock, timer). `classifyThrown` / `statedDelayMs` live beside `error-retry.ts`'s table.
124
- - **`finiteOption` / `finiteCount` (`finite-option.ts`) are the framework's ONE screen for a numeric
125
- option.** `finiteCount(subject, option, value, min)` takes `min: 0 | 1` because only the caller
126
- knows what zero means. `bun run finite-bounds` recognises a repair by the call's shape, so a
127
- package screen carries `Finite` in its name.
128
- - **`mcp-exposure.ts`'s `isMcpExposed` is the ONE answer to "did this opt into MCP?"**, read by
129
- `action`, `query`, `mcp`, `ai`, `manifest`. `@ultimat3/cli`'s `mcp-exposure-pin.test.ts` checks
130
- it; `@ultimat3/admin`'s own catalog is the one opt-OUT exception (`mcp-tools.ts`).
115
+ - **The flight layer** imports nothing but this package, runs nothing at import, injects every
116
+ source of non-determinism. †
117
+ - **`finiteOption` / `finiteCount` (`finite-option.ts`) are the framework's ONE screen for a numeric option.** Full rule: `docs/history/core.md`.
118
+ - **`mcp-exposure.ts`'s `isMcpExposed` is the ONE answer to "did this opt into MCP?"** †
131
119
 
132
120
  ## Metrics, tracing, reporting
133
121
 
134
- `metrics.ts`: counters (spans are `telemetry.ts`), always on, no-op exporter by default.
122
+ `metrics.ts`: counters (spans: `telemetry.ts`), always on. **There is no exporter until something
123
+ subscribes to `metric.export`**: `exportMetrics()` returns at once with no subscriber (no
124
+ `noopMetricExporter`, deleted in 31.0.0); the OTLP boot's `subscribe` is the install, its release
125
+ the uninstall.
135
126
  `runtime-metrics.ts` alone names a series the chart reads (`http_requests_total`, `connections`,
136
127
  `queue_depth`), keyed by `ScalingSignal` in `SCALING_METRICS`. `process-metrics.ts`: `process_*`
137
128
  (resident memory, heap, external, CPU seconds, event-loop lag, start time, `process_info{role}`);
@@ -146,9 +137,9 @@ server-only, never on `page.ts`. One call site per recorder; a second is the bug
146
137
  | `recordLeaseLost` | `@ultimat3/jobs` `heartbeat.ts`, once per lapsed lease |
147
138
  | `recordBreakerTransition` | `breaker.ts`, on every state change |
148
139
 
149
- - Tracing is three files: `telemetry.ts` builds spans, `sampler.ts` decides, `otlp*.ts` exports.
150
- `span.end()` returns early when `traceFlags & 1` is 0. The default sampler reads
151
- `OTEL_TRACES_SAMPLER*` at the first span, never at module scope. `resetTelemetry()` drops both.
140
+ - **One bus, `instrument.ts`**: every observer is a `subscribe()` — OTLP spans (`span.end`, sampled
141
+ only), logs (`log.record`), metrics. No `set*Observer`/`set*Sink`/`recent*()` slot
142
+ (`X_INSTRUMENT_SLOT_FORBIDDEN`). Sampler reads `OTEL_TRACES_SAMPLER*` at the first span.
152
143
  - **An empty `spanId` means "no inbound decision"** — `startSpan` narrows through
153
144
  `inboundParent()`, carrying the trace id and never the synthesised sampling bit.
154
145
  - The OTLP exporters are built, not wrapped ([`docs/idea/18-build-vs-wrap.md`](../../docs/idea/18-build-vs-wrap.md)).
@@ -168,7 +159,8 @@ server-only, never on `page.ts`. One call site per recorder; a second is the bug
168
159
  `maxBytes` 64 KiB — past one, stored `truncated`. A refused save is a log line, never awaited.
169
160
  - **Three OTLP variables, three codes** — `X_OTLP_ENDPOINT_INVALID`, `X_OTLP_HEADERS_INVALID`,
170
161
  `X_OTLP_PROTOCOL_UNSUPPORTED`. A header KEY is in the cause/fix/meta; its VALUE never is.
171
- - `error-reporter.ts`: `ErrorReporter`, no-op default, memory reporter for tests, Sentry transport (`error-reporter-sentry.ts`, optional export). Full rule: `docs/history/core.md`. `'browser'`: only cli's `client-errors-routes.ts`, one `X_CLIENT_ERROR` per report.
162
+ - **A cause is cut at 4 KiB in the constructor** (`boundedCause`); schema's copy is pinned by `single-line-pin.test.ts`.
163
+ - `error-reporter.ts`: `ErrorReporter`, an `adapterSlot` (`installErrorReporter` on `./adapter`; `configureErrorReporting` keeps clock/release/environment/enabled only), no-op default, memory reporter for tests, Sentry transport (`error-reporter-sentry.ts`, optional export). Full rule: `docs/history/core.md`. `'browser'`: only cli's `client-errors-routes.ts`, one `X_CLIENT_ERROR` per report.
172
164
  - `METRICS_PATH` is served by `@ultimat3/cli`'s `metrics-endpoint.ts` on `METRICS_PORT` (9090), never
173
165
  the role's HTTP port; every role opens it.
174
166
 
@@ -178,6 +170,7 @@ server-only, never on `page.ts`. One call site per recorder; a second is the bug
178
170
  - **`drain()`'s memo is published BEFORE the first hook runs** — a hook may re-enter `drain()`
179
171
  (`@ultimat3/http`'s `handle.stop()`), and `settleWithin` invokes hooks synchronously.
180
172
  - **The drain deadline is enforced** (`lifecycle-deadline.ts`): a hook overrunning the whole drain's budget is abandoned and logged (`X_SHUTDOWN_TIMEOUT`); real monotonic time, never the injected `clock`. Full rule: `docs/history/core.md`.
173
+ - **An exit after a drain is `drainExitCode()`** — 70 when work was abandoned (`X_SHUTDOWN_TIMEOUT`), else 0. Never a literal `process.exit(0)`.
181
174
  - **`close` hooks run last-registered first; the other phases as registered** (`runPhase`). No fourth phase.
182
175
  - **Who a health endpoint tells what is ONE rule, here** (`health-disclosure.ts`): `healthBody` +
183
176
  `healthPeerListed`, called by http and by realtime's sync listener. Never a second copy.
@@ -192,9 +185,12 @@ server-only, never on `page.ts`. One call site per recorder; a second is the bug
192
185
  - Every `UltimateError` carries `retry` (`terminal | retryable | retry-after`), **defaulting to `terminal`**. Full rule: `docs/history/core.md`.
193
186
  - `PRIMITIVE_KINDS` is the executable eight-primitive rule; `PrimitiveKind` derives from it and
194
187
  `registrar.test.ts` fails on a ninth. `PRIMITIVE_FACTORIES` lists the factories.
188
+ - **`ADAPTER_PORTS` (`registrar.ts`) is every swappable backend**; `registrar.test.ts` pins each row
189
+ and checks each interface is exported by its package. A port's installer lives on that package's
190
+ `./adapter` subpath (core's: `adapter.ts`), returns its release, and is never on the barrel.
195
191
 
196
192
  ```bash
197
- bun test packages/core/src # from the REPO ROOT, never from packages/core
193
+ bun test ./packages/core/src/ # from the REPO ROOT, never from packages/core; the ./ matters
198
194
  bun run typecheck
199
195
  ```
200
196
 
@@ -203,5 +199,5 @@ matchers) from the cwd.
203
199
 
204
200
  Gotchas (`exactOptionalPropertyTypes`, `Ctx`'s index signature, registry resets, `onShutdown`'s unregister, cursor-secret restore): [`docs/history/core.md`](../../docs/history/core.md#moved-out-2026-11-03-plan-101-wave-3-the-claudemd-ceiling).
205
201
 
206
- Why each rule above is shaped the way it is: [`docs/history/core.md`](../../docs/history/core.md).
202
+ Why each rule is shaped so: [`docs/history/core.md`](../../docs/history/core.md).
207
203
  - `drain-deadline.ts` also owns `WORKER_RETIRE_DEFAULT_MS` and `workerRetireIssue`.
package/README.md CHANGED
@@ -45,7 +45,7 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
45
45
  | a poll a hidden tab and a lost session stop — `visibleInterval(run, ms, { maxMs? })`: no call while hidden, one when shown, a failed run doubling the wait up to `maxMs` (jittered) and a success resetting it, an idempotent disposer; on `./page` (6,045 B alone, `page-bundle.test.ts`) | `visible-interval.ts` |
46
46
  | which row survives a conflict — `server-wins`, `last-write-wins`, `custom` | `conflict-policy.ts` |
47
47
  | the four shapes an async region can be in | `async-state.ts` |
48
- | the audit seam `action` and `query` share — `AuditRecord` (`name`, `primitive`, `surface`, `outcome`, the parsed `input`; `action` is a deprecated alias of `name` until 25.0.0), `AuditSink`, the ONE installed sink (`setAuditSink` / `getAuditSink` / `resetAuditSink`, re-exported by `@ultimat3/action`), and `AUDIT_RECORD_FIELDS`, the field list both primitives' tests pin their records to | `audit.ts` |
48
+ | the audit seam `action` and `query` share — `AuditRecord` (`name`, `primitive`, `surface`, `outcome`, the parsed `input`; `action` is a deprecated alias of `name` until 25.0.0), `AuditSink<TRecord = AuditRecord>` (the framework's one sink interface — `@ultimat3/admin` writes `AuditSink<AuditEntry>`), the ONE installed sink (`getAuditSink()` reads it; the boot installs `runtime.ts`'s `auditSink` through `installAuditSink` on `@ultimat3/core/adapter`, 31.0), and `AUDIT_RECORD_FIELDS`, the field list both primitives' tests pin their records to | `audit.ts` |
49
49
  | is this `unknown` a keyed record? | `json-object.ts` |
50
50
  | typed env validated at boot | `env.ts` |
51
51
  | `.env.example` rendered from that schema, and its drift check | `env-example.ts` |
@@ -64,21 +64,26 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
64
64
  | the shape screens that run before any rule reads a value — section, list, boolean, closed set, path | `config-shape.ts` |
65
65
  | the keys a major deleted (`locales`, `defaultLocale`, `defaultTimeZone`, `defaultCurrency`, `theme.tokens` in 25.0.0; `jobs.driver`, deleted in 5.0.0 and refused since 25.0.0) — each REFUSED by name with `X_CONFIG_INVALID` and its replacement, never ignored | `config-removed.ts` |
66
66
  | the `pwa` block — what an install needs, and the boot refusal when it is not there | `config-pwa.ts` |
67
- | the `assets` block — `retain: { disk, builds }`, earlier builds' hashed files kept across a deploy (`AssetsConfig`, `AssetsRetainConfig`, `AssetsSection`, `AssetsSectionInput`) | `config-assets.ts` |
67
+ | the `assets` block — `retain: { disk, builds }`, earlier builds' hashed files kept across a deploy (`AssetsConfig`, `AssetsRetainConfig`, `AssetsSectionInput`) | `config-assets.ts` |
68
68
  | `isSameOriginPath(value)` — a path on THIS origin as a browser resolves it: refuses `//host`, `/\host`, a C0 control or DEL (`/\t/evil.example` parses to `//evil.example`) and a dot segment leaving a `//` pathname. The one predicate for every URL precached as an offline answer, `@ultimat3/pwa`'s build included | `config-pwa.ts` |
69
69
  | the closed route vocabulary every renderer names | `route-vocabulary.ts` |
70
70
  | which of two route patterns wins a pathname (`routeRank`) | `route-rank.ts` |
71
71
  | runtime roles + `ROLE` resolution | `roles.ts` |
72
72
  | `Clock` — the only source of "now" | `clock.ts` |
73
73
  | UUIDv7, nanoid, branded ids | `ids.ts` |
74
- | structured JSON logging + redaction; `setLogSink(sink)` — the test seam that sends every default-writer line to a sink instead of the process's streams (a test preload drops them; a test asserting on the process logger collects them) | `logger.ts` |
75
- | `addLogSink(sink)` — the supported tee: every default-writer line, after redaction, to `sink` **beside** the streams (or a `setLogSink` seam), never instead; returns the unsubscribe. A sink that throws is skipped and reported once (`log.sink_failed`); a line a sink logs is not teed back | `log-tee.ts` |
76
- | OTel-shaped spans, always on, no-op by default | `telemetry.ts` |
74
+ | structured JSON logging + redaction; `installLogSink(sink)` — the test seam that sends every default-writer line to a sink instead of the process's streams until the release it returns runs (a stack: releases in any order; `undefined` is the streams) (a test preload drops them; a test asserting on the process logger collects them). The tee is the bus: every such line, redacted, is the `log.record` event — `subscribe('log.record', handler)` | `logger.ts` |
75
+ | the ONE instrumentation bus: `subscribe(pattern, handler)` → unsubscribe (exact name, dot-segment prefix, `'*'`), `subscribed(name)`, `instrument(name, payload)`; synchronous, registration order, fired before sampling, a throwing handler reaches the emitter. `subscriberCount()` / `resetInstrumentation()` for tests | `instrument.ts` |
76
+ | the event vocabulary: `INSTRUMENT_EVENTS`, every payload type, `InstrumentEventMap` (augmentable — an app's own names ride the same bus) | `instrument-events.ts` |
77
+ | semconv names: `SEMCONV` (span attribute keys), `SEMCONV_VALUES`, `SEMCONV_METRICS` | `instrument-semconv.ts` |
78
+ | `subscribeSemconvMetrics()` — the semconv histograms (`db_client_operation_duration_seconds`, `job_duration_seconds`, `gen_ai_client_token_usage`) as one bus subscriber; boot calls it once | `metrics-semconv.ts` |
79
+ | OTel-shaped spans, always on; a SAMPLED span goes out as `span.end` on the bus. `configureTelemetry({ exporter })` and `noopExporter` are gone (31.0): `subscribe('span.end', (e) => exporter.export(e.payload))` | `telemetry.ts` |
77
80
  | the sampling decision, and `OTEL_TRACES_SAMPLER*` | `sampler.ts` |
78
81
  | OTLP/HTTP JSON: endpoint, headers, value encoding | `otlp.ts` |
79
82
  | one OTLP POST, retried on the specification's transient answers | `otlp-post.ts` |
80
83
  | `SpanExporter` on the wire, batched | `otlp-span-exporter.ts` |
81
84
  | `MetricExporter` on the wire | `otlp-metric-exporter.ts` |
85
+ | `otlpLogExporter()` — OTLP logs (`/v1/logs`, `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`), installed as `subscribe('log.record', (e) => logs.export(e.payload))`; `log.record` is every process-logger line after redaction, joined to the active trace | `otlp-log-exporter.ts` |
86
+ | `outbound()` on the bus: one `outbound.request` event and one `outbound.<vendor>` client span per call (retries inside), `server.address` / `http.request.method` / `http.response.status_code`, never the path or query | `outbound-instrument.ts` |
82
87
  | may a caller read this 5xx code's `cause`? `hasPublicCause(code)` — one predicate for the HTTP problem document, MCP error data and an agent `tool_result` | `public-cause.ts` |
83
88
  | `reportError` + the `ErrorReporter` seam, no-op by default | `error-reporter.ts` |
84
89
  | that seam on the wire, Sentry's envelope and DSN | `error-reporter-sentry.ts` |
@@ -86,19 +91,19 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
86
91
  | OTel-shaped counter / gauge / histogram, same seam | `metrics.ts` |
87
92
  | the `/metrics` scrape body | `metrics-text.ts` |
88
93
  | the series every process emits, incl. what the chart scales on | `runtime-metrics.ts` |
89
- | what the process itself costs: `process_resident_memory_bytes`, `process_heap_used_bytes`, `process_heap_total_bytes`, `process_external_memory_bytes`, `process_cpu_seconds_total`, `process_event_loop_lag_seconds`, `process_start_time_seconds`, `process_info{role}` — **server-only**, never on `@ultimat3/core/page` | `process-metrics.ts` (`startProcessMetrics`, `readProcess`) |
94
+ | what the process itself costs: `process_resident_memory_bytes`, `process_heap_used_bytes`, `process_heap_total_bytes`, `process_external_memory_bytes`, `process_cpu_seconds_total`, `process_event_loop_lag_seconds`, `process_start_time_seconds`, `process_info{role}` — **server-only**, never on `@ultimat3/core/page` | `process-metrics.ts` (`startProcessMetrics`) |
90
95
  | graceful drain, `/healthz`, `/readyz` | `lifecycle.ts` |
91
96
  | what a health endpoint tells whom — `healthBody(report, role, detailed)`, `healthPeerListed(peers, address)`, `DEFAULT_HEALTH_DETAIL_PEERS`; the one rule `@ultimat3/http` and the sync node's own listener both call | `health-disclosure.ts` |
92
97
  | the readiness grace between `/readyz` → 503 and the listener closing (`drain.readinessGraceMs`) | `lifecycle-grace.ts` |
93
98
  | the drain budget's default and domain (`drain.deadlineMs`, 25 s, 1–3600000 ms; the worker's optional `drain.workerDeadlineMs`, 1–86400000 ms; its `drain.workerRetireMs`, an hour, 0–86400000 ms) — `DRAIN_DEADLINE_DEFAULT_MS`, `DRAIN_DEADLINE_MAX_MS`, `WORKER_DRAIN_DEADLINE_MAX_MS`, `WORKER_RETIRE_DEFAULT_MS` | `drain-deadline.ts` |
94
99
  | `jobs.concurrency`'s default and domain — one slot count for every queue a worker serves, or a table per queue (`{ banks: 4, 'banks-long': 2 }`; a queue the table does not name runs at the default). `JOBS_CONCURRENCY_DEFAULT` (8), `type JobsConcurrency` | `config-jobs.ts` |
95
- | SIGTERM/SIGINT → the one drain; on Windows also SIGHUP (console close) and SIGBREAK (Ctrl-Break) — `drainSignals(platform)` | `lifecycle-signals.ts` |
100
+ | SIGTERM/SIGINT → the one drain; on Windows also SIGHUP (console close) and SIGBREAK (Ctrl-Break) — `drainSignals(platform)`. With `exit: true` the process exits `drainExitCode()`: `0`, or `DRAIN_TIMEOUT_EXIT_CODE` (70, `EX_SOFTWARE`) when work was abandoned at the deadline (`X_SHUTDOWN_TIMEOUT`) | `lifecycle-signals.ts` |
96
101
  | is this directory inside a `bun build --compile` binary? `isCompiledBundle(import.meta.dir)` — `/$bunfs/` and Windows' `B:\~BUN\` | `bunfs.ts` |
97
102
  | which network an IP literal belongs to — `classifyAddress`, for SSRF screens; `peerAddressClass`, for a check that trusts a caller or a local name | `address-class.ts` |
98
103
  | the network a caller's address keys a per-caller budget on — `addressNetwork`: IPv4 exact, IPv4-mapped as IPv4, IPv6 as its /64 | `address-class.ts` |
99
104
  | the sockets this process opened, so a self-request is not egress | `listeners.ts` |
100
105
  | `defineService('orgs', …)` → `ctx.orgs`, rebuilt per actor | `service.ts` |
101
- | the registrar table one same-tier package reaches another through | `registrar.ts` |
106
+ | the registrar table one same-tier package reaches another through; `PRIMITIVE_FACTORIES`; `ADAPTER_PORTS` / `ADAPTER_PORT_NAMES` / `AdapterPortName` — every swappable backend, one row each (port = `runtime.ts` field, owning package, interface, env default, conformance suite) | `registrar.ts` |
102
107
  | decode → resize → encode, the one image pipeline (over `Bun.Image`) | `image/` |
103
108
  | `assertNever`, `assertCoded`, `assert` | `assert.ts` |
104
109
  | the one HTML character table — `escapeHtml`, text and attributes alike (`& < > " '`) | `html-escape.ts` |
@@ -223,6 +228,7 @@ throw new UltimateError({
223
228
  | Helper | For | Degrades to |
224
229
  |---|---|---|
225
230
  | `renderCauseValue(value)` | a `cause`, which only has to describe | `a object that cannot be rendered` |
231
+ | `boundedCause(text)` | a whole cause, cut at `MAX_CAUSE_LENGTH` (4096) with `... (N more characters)`. The `UltimateError` constructor applies it — you never call it for one | the first 4 KiB |
226
232
  | `renderFixLiteral(value, placeholder)` | a `fix`, which has to parse and run | the placeholder you name |
227
233
  | `renderThrowable(value)` | a caught value: an `Error`'s own words, anything else rendered | `renderCauseValue(value)` |
228
234
  | `isThrownError(value)` | `value instanceof Error` where the test itself may throw | `false` |
@@ -374,7 +380,7 @@ export const env = defineEnv({
374
380
  ```
375
381
 
376
382
  Every missing or malformed key is listed in one `X_ENV_MISSING`. `secret: true` keys are
377
- redacted in logs and masked in `checkEnv()` output; `describeEnv()` emits declarations only,
383
+ redacted in logs and masked in `checkEnv()` output; the env summary (`describeEnv()`, internal) emits declarations only,
378
384
  safe for `x.manifest.json`. Omit `required` for required — `required: false` is the only
379
385
  loosening. Never declare an env var for *which deploy this is* — that is `ULTIMATE_ENV`, below.
380
386
 
@@ -472,6 +478,13 @@ only writer.
472
478
  | AAD | `v`, `alg` and `kid`, so a downgraded header fails the tag rather than changing how the body is read |
473
479
  | `kid` | a domain-separated, truncated SHA-256 of the master key. Safe to commit, and what makes *wrong key* (`X_SECRETS_KEY_MISMATCH`) a different code from *edited file* (`X_SECRETS_TAMPERED`) |
474
480
 
481
+ **Where the key comes from is the `secretSource` adapter port.** The default asks
482
+ `envSecretSource` then `fileSecretSource`; a KMS or Vault lookup is an app-written `SecretSource`
483
+ (`{ name, masterKey({ root, env }) }`, async allowed) set as `secretSource` in
484
+ `apps/<app>/runtime.ts`. `installSecrets()` and the seal ring both ask the installed source;
485
+ `findMasterKey` / `requireMasterKey` are the built-in lookup `x secrets` and `x doctor` read.
486
+ `MasterKeyRef.source` is the source's `name` (31.0.0 removed the closed `MasterKeySource` union).
487
+
475
488
  A missing file is not an error — an app may declare no secrets. A file with **no key to open it**
476
489
  is `X_SECRETS_KEY_MISSING` and fatal: a process that booted past its secrets authenticates against
477
490
  nothing and still reports healthy.
@@ -529,9 +542,18 @@ match with `sealAll()`; uniqueness cannot be held across keys.
529
542
  ## Time, ids, telemetry, drain
530
543
 
531
544
  - Never call `Date.now()`. Take a `Clock`; tests pass `frozenClock('2026-07-26T10:00:00Z')`.
545
+ - `liveClock` is the clock to default to when none is passed: the `clock` port's now/monotonic at
546
+ each call (`installClock`, `runtime.ts`'s `clock`), else the system's. `ctxOf()` and the logger
547
+ default to it; never copy it into a package.
548
+ - Never arm a timer to wait: take a `SleepClock` (`sleep(ms, signal?)`, rejecting with the signal's
549
+ reason verbatim). `ambientClock()` is the process's — the system clock with `sleep` unless the
550
+ `clock` port swapped it through `installClock` on `@ultimat3/core/adapter` (returns the release);
551
+ `frozenClock()` advances on `sleep`; `noWaitClock` is real time with one loop turn per sleep. The
552
+ barrel's and `./page`'s `systemClock` is a plain `Clock` — browser code reads it and nothing there
553
+ waits; the sleeping one is `./adapter`'s `systemClock` (`sleep-clock.ts`, server-only).
532
554
  - `uuidV7()` is UUIDv7: time-prefixed, monotonic within a millisecond, never backwards on clock
533
555
  skew. `typedId<'post'>()` brands it so a post id cannot be passed where a user id is wanted.
534
- - `withSpan('action.publishPost', fn)` is free until `configureTelemetry({ exporter })`.
556
+ - `withSpan('action.publishPost', fn)` builds no record until something subscribes to `span.end`.
535
557
  Traces cross process boundaries via `traceparent()` / `parseTraceparent()`, whose ids come from
536
558
  `traceId()` / `spanId()` — **never `uuidV7()`**, whose dashed 36 characters every collector
537
559
  rejects. `isTraceId()` / `isSpanId()` are the one definition of the valid shape.
@@ -543,15 +565,16 @@ match with `sealAll()`; uniqueness cannot be held across keys.
543
565
  trace half exported, which is orphan children under a root the collector never saw.
544
566
  - **The OTLP exporters ship**, speaking OTLP/HTTP JSON, no dependency:
545
567
  `otlpSpanExporter({ endpoint })` (batched, with `flush()` / `shutdown()`) and
546
- `otlpMetricExporter({ endpoint })`. Both default to `OTEL_EXPORTER_OTLP_ENDPOINT`;
547
- `tryOtlpEndpoint('traces')` answers `undefined` when nobody configured one, so a boot can skip
568
+ `otlpMetricExporter({ endpoint })` and `otlpLogExporter({ endpoint })`. All three default to
569
+ `OTEL_EXPORTER_OTLP_ENDPOINT`; `tryOtlpEndpoint('traces' | 'metrics' | 'logs')` answers `undefined` when nobody configured one, so a boot can skip
548
570
  the exporter instead of throwing. **gRPC (`:4317`) is out of scope** and says so with
549
571
  `X_OTLP_PROTOCOL_UNSUPPORTED`.
550
572
  - **A transient export is sent again** (`postOtlp`, `otlp-post.ts`): 429, 502, 503, 504 or a
551
573
  transport failure, `OTLP_RETRY_STATUSES`, on core's retry loop (3 attempts, full jitter,
552
574
  `Retry-After` honoured) inside `timeoutMs`, which is the whole export. One log line per batch.
553
575
  - Metrics are the same shape one signal over: `counter()`, `gauge()`, `histogram()`, aggregated
554
- in process, free until `configureMetrics({ exporter })`. See below.
576
+ in process, pushed as `metric.export` on the instrumentation bus and free until something
577
+ subscribes. See below.
555
578
  - `onShutdown(name, hook, { phase })` with phases `accept → inflight → close` under one
556
579
  deadline, `close` running last-registered first; `readyzPayload()` flips to 503 the moment draining starts, `healthzPayload()` stays
557
580
  200 until stopped. It **returns an unregister**, and a caller that starts and stops more than
@@ -608,7 +631,7 @@ collectMetrics(); // the same numbers as data, for a MetricExporter
608
631
  | Attributes | `string \| number \| boolean` only — each distinct set is a stored series, so a user id here is an outage |
609
632
  | Cardinality | enforced, not advised: `maxSeries` per instrument (default `DEFAULT_MAX_SERIES`), and past it every new label set folds into one `otel_metric_overflow="true"` series with `X_METRIC_CARDINALITY` logged once, naming the instrument |
610
633
  | Async gauges | an `observe()` that throws, or answers a non-finite number, costs that instrument its point and **nothing beside it** — `X_METRIC_VALUE_INVALID` logged once, naming the instrument. Unguarded it took the whole `/metrics` body down with it, and `startMetricExport`'s timer callback raised where nothing can catch it |
611
- | Driver seam | `MetricExporter`, defaulting to a no-op. `memoryMetricExporter()` for tests, `startMetricExport(ms)` for a periodic push, `otlpMetricExporter()` for a collector |
634
+ | Driver seam | a `MetricExporter` is a bus subscriber: `subscribe('metric.export', (event) => exporter.export(event.payload))`, released by its unsubscribe (`configureMetrics` takes `clock` and `enabled` only, 31.0.0). `exportMetrics()` publishes one tick, `startMetricExport(ms)` a periodic push; `memoryMetricExporter()` for tests, `otlpMetricExporter()` for a collector |
612
635
 
613
636
  `runtime-metrics.ts` holds the series every process emits, and `SCALING_METRICS` maps each
614
637
  `ScalingSignal` from `roles.ts` to the one that carries it — so the role table, the chart and the
@@ -633,24 +656,25 @@ A no-op by default, one transport on the wire, one memory double for tests — `
633
656
  `metrics.ts`' shape a third time. What a monitor receives is the framework's error contract
634
657
  verbatim, so it groups on `code` and shows `fix` to whoever is paged.
635
658
 
636
- **An Ultimate app installs nothing.** `@ultimat3/cli`'s `serve.ts` calls
637
- `configureErrorReporting` at boot from one env var — `SENTRY_DSN`, unset meaning the no-op stays
638
- and nobody is paged — and passes the build id it already computed as `release`. The call below is
639
- for a host that boots something other than `runRole`.
659
+ **An Ultimate app installs nothing.** The reporter is the `errorReporter` port: `runtime.ts`'s
660
+ `errorReporter` field, installed by the boot before `loadApp`; `@ultimat3/cli`'s `serve.ts` then
661
+ chains its `SENTRY_DSN` transport beside a local sink (unset, nobody is paged) and passes the build
662
+ id it already computed as `release`. The calls below are for a host that boots something other
663
+ than `runRole`.
640
664
 
641
665
  ```ts
642
666
  import { configureErrorReporting, reportError, sentryErrorReporter } from '@ultimat3/core';
667
+ import { installErrorReporter } from '@ultimat3/core/adapter';
643
668
 
644
669
  declare const sentryDsn: string;
645
670
  declare const buildId: string;
646
671
  declare const failure: unknown;
647
672
 
648
- configureErrorReporting({
649
- reporter: sentryErrorReporter({ dsn: sentryDsn }), // config, never a constant in this package
650
- release: buildId, // the id `x-ultimate-build` carries
651
- });
673
+ const release = installErrorReporter(sentryErrorReporter({ dsn: sentryDsn })); // its undo
674
+ configureErrorReporting({ release: buildId }); // the id `x-ultimate-build` carries
652
675
 
653
676
  reportError(failure, { source: 'http', severity: 'error', scope: { operation: 'POST /api/posts' } });
677
+ release();
654
678
  ```
655
679
 
656
680
  | | |
@@ -660,13 +684,14 @@ reportError(failure, { source: 'http', severity: 'error', scope: { operation: 'P
660
684
  | `ErrorSeverity` | `warning` `error` `fatal`. `warning` is a failure the framework already recovered from — a retry, not a dead letter |
661
685
  | `ErrorScope` | `requestId` `traceId` `spanId` `role` `operation` `actorId` `extra`. `operation` is a route **pattern** or a job name, never a concrete path or a row id |
662
686
  | `ErrorReport` | `code` `title` `cause` `fix` `docs` + `meta` `stack` `resource` `environment` `release` `scope`, and the thrown value under `error` |
663
- | `configureErrorReporting({ reporter, clock, release, environment, enabled })` | the one install point; `resetErrorReporting()` puts the no-op back |
664
- | Reporters | `noopErrorReporter` (default), `memoryErrorReporter()` (`.events`, `.reset()`), `sentryErrorReporter({ dsn, fetch?, clientName? })` |
687
+ | `configureErrorReporting({ clock, release, environment, enabled })` | the settings around the port — never the reporter (31.0: `reporter` is `never`). The reporter is `installErrorReporter(reporter)` on `./adapter`, returning its release; `resetErrorReporting()` drops every install and setting |
688
+ | Reporters | `noopErrorReporter` (default), `memoryErrorReporter()` (`.events`, `.reset()`), `sentryErrorReporter({ dsn, fetch?, clientName?, beforeSend?, ignore?, fingerprint?, sampleRate? })`; `isSentryErrorReporter(reporter)` — whether one was built by it, so the container's `SENTRY_DSN` boot skips its own transport when the app installed one (31.0) |
689
+ | Sentry hooks | `beforeSend(event)` → the event (rewritten or not) or `null` to drop — scrub by value here; a hook that throws drops the event. `ignore(code)` → `true` drops before the event is built. `fingerprint(report)` → the grouping, replacing `errorFingerprint`'s. `sampleRate` 0..1 (`X_CONFIG_INVALID` outside it). A throwing `ignore`/`fingerprint` falls back to the default |
665
690
  | Several at once | `chainErrorReporters(...reporters)` — one reporter handing each report to every member in order; a member that throws is logged and costs only itself; chains flatten, a member listed twice reports once, none is the no-op. `errorReportersOf(reporter)` reads the members back; `installedErrorReporter()` the one installed now. The container chains its `SENTRY_DSN` transport after what the app installed (`As of 2026-11`) |
666
- | Wire, testable alone | `parseSentryDsn(dsn)` → `{ publicKey, envelopeUrl, … }`, `sentryEnvelope(report, { dsn, eventId })` → the envelope body. Pure, exactly as `otlpTraceRequest` is |
691
+ | Wire, testable alone | `parseSentryDsn(dsn)` → `{ publicKey, envelopeUrl, … }`, `sentryEvent(report, { dsn, eventId, fingerprint? })` → the event, `sentryEnvelope(report, { dsn, eventId, fingerprint? })` → the envelope body. Pure, exactly as `otlpTraceRequest` is |
667
692
  | `errorReport(error, options)` | the normalisation on its own, for a transport's test or a surface that enriches before sending |
668
693
  | `errorFingerprint(report)` | 16 hex, which reports are one fault: `code`, `source`, `scope.operation`, and for `X_INTERNAL` the top application frame (function and root-relative path, no line). Never `cause`, `meta`, an id or `release`. Total; the Sentry envelope sends it as `fingerprint` |
669
- | `setFailureStore(store)` / `withFailureCapture(primitive, name, statusOf, run)` / `recordFailureFact(fact)` | the 5xx bundle `x repro` replays (`failureCapture` in `app.config.ts`). No store, no buffer. A 5xx is held on the thrown value and stored at `reportError` under its `errorFingerprint`; masked input listed in `masked` |
694
+ | `withFailureCapture(primitive, name, statusOf, run)` / `recordFailureFact(fact)` | the 5xx bundle `x repro` replays (`failureCapture` in `app.config.ts`). No store, no buffer. The store is the `failureStore` port: `runtime.ts`'s `failureStore`, installed by the boot through `installFailureStore` on `@ultimat3/core/adapter` (never the barrel). A 5xx is held on the thrown value and stored at `reportError` under its `errorFingerprint`; masked input listed in `masked` |
670
695
 
671
696
  `As of 2026-08` four packages call `reportError`, seven call sites in all: `@ultimat3/http`'s
672
697
  `stages.ts` (`status >= 500` only), `@ultimat3/jobs`' `executeJob` — the one frame still holding the
@@ -862,6 +887,7 @@ A refusal is Bun's `ERR_REDIS_CONNECTION_CLOSED`, untyped here: the job driver t
862
887
  | Export | The one answer | The question it settles |
863
888
  |---|---|---|
864
889
  | `clientTransport({ method, url, body?, rawBody?, headers?, signal?, idempotencyKey?, flight?, fresh?, retry?, responseType?, onResponse?, decodeError?, onEnvelope?, fetchImpl? })` | every browser request | `credentials: 'same-origin'`, JSON in and out, the `idempotency-key` header, a non-2xx `problem+json` back into the server's code (`meta.origin: 'remote'`) unless `decodeError` answers first, a network `TypeError` into `X_CLIENT_TRANSPORT_FAILED`. A GET is abortable on `rescope()` and deduped only when a `flight` is passed (`fresh` refuses to join); any other method is never deduped and never aborted by the fence. `rawBody` goes out verbatim with no default header and resolves `undefined` (the body as a string with `responseType: 'text'`). `responseType: 'text'` resolves a 2xx body as a string (typed `Promise<string>`), sends `accept: */*` unless `headers` names one, and adopts no envelope — for an HTML fragment or a CSV; a non-2xx is still decoded as a refusal. About 10.7 kB minified (4.6 kB gzipped) through `@ultimat3/core/page`, no titles table — pinned in `page-bundle.test.ts`. `onResponse` sees headers before the body is read. `onEnvelope` sees the decoded records envelope after adoption — the one way to learn the order of `records[type]`. `fetchImpl` defaults to `globalThis.fetch`, read at call time |
890
+ | `@ultimat3/core/page` — what a typed client reads, never the barrel: `clientTransport`, `clientStream`, `clientFlight` (+ types `ClientFlight`, `ClientFlightOptions`, `ClientRetry`, `ActionPathStyle`), `BUILD_ID_HEADER`, `IDEMPOTENCY_HEADER`, `FRAMEWORK_CODE`, `problemOf`, `remoteTitleOf`, `retryForStatus`, `withRequestId`, `withStatedDelay`, `registerErrorCodes`, `registerErrorRetry`, `hasErrorCode`, `ERROR_DOCS_URL`, `deniedCallerFix`, `renderCauseValue` beside the page handle, fence and names | the one light browser entry | no titles table, no `node:` module, no build warning (`page-bundle.test.ts`). The whole entry is 32,269 B minified; an island pays only what it imports — `@ultimat3/action`'s `rpc` 24,473 B, + `clientFlight` 32,929 B (`client-bundle.test.ts`). Every name is on the barrel too |
865
891
  | `actionPath(name)`, `actionRoute(name)`, `queryPath(name)`, `QUERY_PATH_PREFIX`, `splitWords`, `pluralize` | the one URL rule | `publishPost` → `/api/posts/publish`, `liveFeed` → `/_x/query/live-feed`. Tier 0 so `action`, `query` and `realtime` derive one URL with no sideways import |
866
892
  | `templateParams`, `fillTemplate`, `pathTemplateProblem`, `templateKeyProblem`, `toOpenApiPath` (`route-path-template.ts`; the first two also on `./page`) · `mergePathParams`, `HttpPathInputConflictError` (`route-path-merge.ts`) | the one `http.path` template rule | an action's and a query's pin (`/orders/:id/refund`): lowercase static segments and `:param`s, each a required string input key; filled with each value one encoded segment; `{id}` in OpenAPI; the URL's values merged into the input, a disagreeing key `X_HTTP_PATH_INPUT_CONFLICT` (400). Tier 0 because `action` and `query` share a tier |
867
893
  | `actionPath(name)` with no `style`, `renderedActionPathStyle()`, `CLIENT_PATH_STYLE_META` | the style nobody restates | `actionPath(name)` reads the document's `<meta name="ultimate-path-style">` stamp, so a browser caller derives under the style the server serves (`defineApi({ http: { pathStyle } })`). No document, no stamp or an unknown value is `'resource'` — a `'resource'` server writes no stamp. A named `style` is never overridden |
@@ -926,7 +952,9 @@ box it is one `Bun.Image` call, source bytes to encoded bytes. When it is not
926
952
  `padding`, a `cover` crop — the artwork comes back as PNG and `canvas.ts` composites it, because
927
953
  `Bun.Image` resamples but has no compositor and the PWA maskable safe zone is a composite.
928
954
  `png-pixels.ts` is the raw-pixel seam that hop needs, 8-bit RGBA only; anything else is
929
- `X_IMAGE_UNSUPPORTED` naming `transformImageBytes`.
955
+ `X_IMAGE_UNSUPPORTED` naming `transformImageBytes`. Its bounded inflate is `node:zlib`, resolved at the call
956
+ (`process.getBuiltinModule`), never imported: a static import made every browser build of the
957
+ barrel warn.
930
958
 
931
959
  Adding a format is an entry in `DECODABLE_FORMATS` / `ENCODABLE_FORMATS` and a branch in
932
960
  `withFormat` — never a second dispatch. An unencodable `format` is refused from the spec alone,
@@ -944,6 +972,20 @@ hand-rolled JPEG and PNG codecs is what put it there.
944
972
  `image/image-fixture.ts` is byte-exact output from Pillow and ffmpeg on purpose: a codec that only round
945
973
  trips against itself proves nothing. Never regenerate a fixture with our own encoder.
946
974
 
975
+ ## `@ultimat3/core/adapter` — core's ports, for adapter authors and the boot
976
+
977
+ Interfaces (`AuditSink`, `SleepClock`, `ErrorReporter`, `FailureStore`, `SecretSource`), the
978
+ built-ins to copy or compose (`systemClock`, `noWaitClock`, `envSecretSource`, `fileSecretSource`,
979
+ `defaultSecretSource`), the error a source raises (`SecretsKeyMissingError`), and the INSTALLERS —
980
+ `installAuditSink` (+ `resetAuditSink`), `installClock`, `installErrorReporter`,
981
+ `installFailureStore`, `installSecretSource` — and `adapterSlot(fallback)`, the one
982
+ slot every package's installer is built on. Every installer returns its release (`() => void`), which
983
+ removes ITS install alone: installers may stop in any order, and a second release is a no-op.
984
+ `ctxOf()` and the logger read the installed clock at each call, so `runtime.ts`'s `clock` reaches
985
+ every action, query and job; deadlines racing real timers, AWS signing and a bare `uuidV7()` stay
986
+ on the system clock. Their callers are the boot (reading
987
+ `apps/<app>/runtime.ts`) and `@ultimat3/testing`; the barrel exports none of them.
988
+
947
989
  ## Supporting exports
948
990
 
949
991
  `As of 2026-11-02`.
@@ -952,4 +994,5 @@ trips against itself proves nothing. Never regenerate a fixture with our own enc
952
994
  |---|---|
953
995
  | `CompletionBound` | what bounds a `runToCompletion` scope, when its caller owns a ceiling |
954
996
  | `MAX_TIMER_MS` | the longest delay a timer holds, 2,147,483,647 ms: past it `setTimeout` arms ~1 ms |
997
+ | `hostDecision(url, allowHosts)`, `hostMatches`, `ANY_HOST` | may a browser or scraper request leave. A wildcard (`'*'`, `'*.example.com'`) never admits an address inside the network nor `localhost`/`*.localhost` (loopback by name, and sent around an egress proxy by Chrome); an exact rule — `'localhost'`, `'127.0.0.1'` — does |
955
998
  | `jsonbRefusal(text)` | why `jsonb` would refuse this `JSON.stringify` output, or `undefined`. Names the class of thing, never the text |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/core",
3
- "version": "30.8.0",
3
+ "version": "31.0.0",
4
4
  "description": "Ultimate's foundation: errors, context, env, config, clock, ids, logging, telemetry, lifecycle",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -30,6 +30,7 @@
30
30
  },
31
31
  "exports": {
32
32
  ".": "./src/index.ts",
33
+ "./adapter": "./src/adapter.ts",
33
34
  "./page": "./src/page.ts",
34
35
  "./internal/error-status": "./src/error-status-declared.ts",
35
36
  "./outbound": "./src/outbound-subpath.ts",
@@ -53,6 +54,6 @@
53
54
  "test": "bun test"
54
55
  },
55
56
  "dependencies": {
56
- "@ultimat3/schema": "30.8.0"
57
+ "@ultimat3/schema": "31.0.0"
57
58
  }
58
59
  }
@@ -0,0 +1,42 @@
1
+ // Single responsibility: the ONE installed-value slot every adapter port uses. A stack of frames,
2
+ // each removed only by its own release, so installers may stop in any order: the shape
3
+ // `@ultimat3/http`'s rate-limit slot and `@ultimat3/realtime`'s channel transport proved, here once.
4
+ // Imports nothing — safe in any bundle graph.
5
+
6
+ export interface AdapterSlot<T> {
7
+ /**
8
+ * Push `value` as a new frame. Answers the release, which removes THIS frame and no other —
9
+ * idempotent, and harmless after any later install or a `reset()`.
10
+ */
11
+ install(value: T): () => void;
12
+ /** The newest installed value, or the fallback (read at this call) when nothing is installed. */
13
+ current(): T;
14
+ /** Drop every frame. A test seam: production releases what it installed. */
15
+ reset(): void;
16
+ }
17
+
18
+ /**
19
+ * `slot = previous` is what this replaces: boot A installs, boot B installs, A stops first and the
20
+ * slot reverts under B while B still serves; B's release later restores A's stopped value. A frame
21
+ * object is its own identity, so the same value installed twice is two frames.
22
+ */
23
+ export function adapterSlot<T>(fallback: () => T): AdapterSlot<T> {
24
+ const frames: { readonly value: T }[] = [];
25
+ return {
26
+ install(value: T): () => void {
27
+ const frame = { value };
28
+ frames.push(frame);
29
+ return () => {
30
+ const at = frames.indexOf(frame);
31
+ if (at !== -1) frames.splice(at, 1);
32
+ };
33
+ },
34
+ current(): T {
35
+ const top = frames.at(-1);
36
+ return top === undefined ? fallback() : top.value;
37
+ },
38
+ reset(): void {
39
+ frames.length = 0;
40
+ },
41
+ };
42
+ }