@ultimat3/core 31.23.0 → 31.25.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.
package/CLAUDE.md CHANGED
@@ -59,6 +59,7 @@ top-level `UltimateError` use in `error-codes.ts`.
59
59
  | 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 |
60
60
  | the ONE keyed hash | `hmac.ts` (`hmac(alg, key, data, encoding?)`) | `bun run keyed-hasher` (`X_KEYED_HASHER`) † |
61
61
  | this process's job | `roles.ts` (`ROLE`) | |
62
+ | a role-scoped boot line | `boot-warning.ts` (`bootWarning`) | `once: 'build'` asks the store the boot installs (`installBootWarnings`, `./adapter`); none installed is once per process |
62
63
  | `allowHosts` | `host-rules.ts` | a wildcard admits no inward literal, no `localhost`/`*.localhost`; exact rules do |
63
64
  | 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`) |
64
65
  | 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 |
@@ -74,7 +75,7 @@ top-level `UltimateError` use in `error-codes.ts`.
74
75
  | 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 |
75
76
  | a lazy boot or load, once per process | `retry-memo.ts` (`retryMemo`) | a rejection is never the memo's answer; never `x ??= start()` for a promise |
76
77
  | how many at once | `flight-gate.ts` | hand-over on release, refusal past `maxQueued`, injectable `overflow:` refusal |
77
- | a fan-out with a bound | `map-bounded.ts` (`mapBounded`) | `width` REQUIRED, no default; input order; first rejection aborts the rest via the signal. Never a hand-rolled worker pool |
78
+ | a fan-out with a bound | `map-bounded.ts` (`mapBounded`) | `width` REQUIRED, no default; input order; first rejection aborts the rest via the signal, or `settle: 'all'` for every outcome. Never a hand-rolled worker pool |
78
79
  | whether an answer still applies | `generation-fence.ts` | `X_SUPERSEDED` / `isSuperseded` |
79
80
  | which HTTP statuses are worth repeating | `retryable-status.ts` | `>= 500` plus 408, 409, 425, 429 |
80
81
  | how long this request has left | `request-budget.ts` (`Ctx.deadlineAt`) | http's `startDeadline` writes the instant, `traceHeaders()` the header † |
@@ -88,8 +89,10 @@ top-level `UltimateError` use in `error-codes.ts`.
88
89
  | the audit record + one sink | `audit.ts` | `action` + `query` read `getAuditSink()`; the boot installs (`installAuditSink`, `./adapter`); `AUDIT_RECORD_FIELDS` pins both |
89
90
  | 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 |
90
91
  | is this `unknown` a keyed record? | `json-object.ts` (`isJsonObject`) | narrows a shape; does not certify provenance |
91
- | 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 |
92
+ | may a caller read this 5xx `cause`? | `public-cause.ts` (`hasPublicCause`) | one table for http, mcp, ai. written by `defineError({ publicCause })` and http's `registerProblemMeta` — `registerPublicCause` is never an app's door |
93
+ | which `meta` keys a document carries | `problem-meta-declared.ts` | the app table + `metaKeyRefusal`; on `./page` through `defineError` |
92
94
  | is this field a credential? | `logger-redact.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; verdict memoised per key, 4,096, cleared by `redactKeys` |
95
+ | is this VALUE a credential? | `redact-values.ts` (`redactedValue`) | the app's `redactValues()` matchers, screened at registration (`X_REDACT_PATTERN_UNSAFE`); `serialise` and `captureValue` apply it to every string leaf, the logger to `msg`, Sentry to the exception value, a span to its exception event and status. Ships no pattern |
93
96
  | a value that must not be printed | `secret.ts` | redacted by VALUE; `revealSecret()` is the one, greppable, way out |
94
97
  | 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 † |
95
98
  | 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 |
package/README.md CHANGED
@@ -72,10 +72,14 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
72
72
  | the closed route vocabulary every renderer names | `route-vocabulary.ts` |
73
73
  | which of two route patterns wins a pathname (`routeRank`) | `route-rank.ts` |
74
74
  | runtime roles + `ROLE` resolution | `roles.ts` |
75
+ | an app's role-scoped boot line — `bootWarning({ code, roles, once?, message, fields })`, said only where a booting role can act on it, `once: 'process'` or `'build'` (the boot installs the per-build store with `installBootWarnings`, on `@ultimat3/core/adapter`) | `boot-warning.ts` |
75
76
  | `Clock` — the only source of "now" | `clock.ts` |
76
77
  | UUIDv7, nanoid, branded ids | `ids.ts` |
77
78
  | 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` |
79
+ | a condition that KEEPS failing, said rarely: `outageLog({ event, level })` → `failed()` writes on failures 1, 2, 4, 8, …, `recovered()` one `<event> recovered` line with `after`; `failureStreak({ event, recoveredEvent, level?, fields? })` → `failed(error, fields?)` writes once per CAUSE (code, or uncoded message; a new one carries `previous`), `passed()` one `recoveredEvent` line with `failures`, `reset()` for a restarted loop; `failureFields(error)` — the `error`/`code`/`cause`/`fix` a failure line carries | `outage-log.ts` |
78
80
  | `teeLogLines(tee)` → its release: a COPY of every process-logger line (redacted, as written) handed to `tee(line, level)` beside the streams, never instead of them. A set: each release removes only its own tee; a tee that throws loses only its copy. `x dev`'s `dev.log` is the caller | `logger.ts` |
81
+ | `redactValues([{ pattern, replace }])` — redaction by VALUE: every match of each `g` pattern becomes `replace` in a log line's message and field strings and in the Sentry envelope's exception value, `fix`, `stack`, extras and `meta`, a span's exception event and status, and failure bundles. Bumps the same generation as `redactKeys`, so a logger bound before it re-redacts. A sticky pattern, an empty match or a repeated group holding a repeating quantifier (`(a+)+`, `(a+){2,40}`) is refused at registration — `RedactPatternUnsafeError` (`X_REDACT_PATTERN_UNSAFE`) — and the list with it. Ships no pattern; `RedactValueMatcher` is the type | `logger-redact.ts`, `redact-values.ts` |
82
+ | `framework_version` — `frameworkVersion()` stamped on every Sentry event's tags, `target_info`'s labels, the OTLP resource (`framework.version`) and the `ultimate started` boot line. One reader: `version-reader.test.ts` refuses a second | `version.ts` |
79
83
  | 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` |
80
84
  | the event vocabulary: `INSTRUMENT_EVENTS`, every payload type, `InstrumentEventMap` (augmentable — an app's own names ride the same bus) | `instrument-events.ts` |
81
85
  | semconv names: `SEMCONV` (span attribute keys), `SEMCONV_VALUES`, `SEMCONV_METRICS` | `instrument-semconv.ts` |
@@ -88,6 +92,7 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
88
92
  | `MetricExporter` on the wire | `otlp-metric-exporter.ts` |
89
93
  | `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` |
90
94
  | `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` |
95
+ | which `meta` keys an app code's problem document carries — the app table `defineError({ problemMeta })` and `@ultimat3/http`'s `registerProblemMeta` both write, and the key rule (`metaKeyRefusal`) | `problem-meta-declared.ts` |
91
96
  | 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` |
92
97
  | `reportError` + the `ErrorReporter` seam, no-op by default | `error-reporter.ts` |
93
98
  | that seam on the wire, Sentry's envelope and DSN | `error-reporter-sentry.ts` |
@@ -192,6 +197,9 @@ export const PostNotFound = defineError<{ readonly ref: string }>({
192
197
  status: 404, // or offSocket: true, for a code no response carries — exactly one of the two
193
198
  cause: (p) => `no post ${p.ref} in the actor's organisation`,
194
199
  fix: 'x queries list --json, then pass an id the post read returns',
200
+ meta: (p) => ({ ref: p.ref }),
201
+ problemMeta: ['ref'], // optional: the meta keys the problem document carries
202
+ // publicCause: true — optional, a 5xx only: its cause may be shown to the caller
195
203
  });
196
204
 
197
205
  const error = new PostNotFound({ ref: 'hello' }, { sourceError: undefined });
@@ -200,7 +208,11 @@ PostNotFound.is(error); // the brand plus the code, never `instanceof`
200
208
 
201
209
  The one call registers the title (`registerErrorCodes`), the status (read by `@ultimat3/http`'s
202
210
  `statusFor`, framework table first, so no app declaration moves a framework code) and, when given,
203
- `retry` (`registerErrorRetry`). The same declaration twice is a no-op — a module re-evaluated
211
+ `retry` (`registerErrorRetry`), and the problem-document half `@ultimat3/http`'s
212
+ `registerProblemMeta` declares beside a hand-written class: `problemMeta` (the `meta` keys a
213
+ document carries) and `publicCause: true` (a 5xx's cause shown). Keys need a `status`, a public
214
+ cause a 5xx; a bad key, an empty list or a list disagreeing with an earlier one refuses the whole
215
+ declaration (`X_ERROR_DECLARATION_INVALID`) before anything is written. The same declaration twice is a no-op — a module re-evaluated
204
216
  under `x dev`; a different title or status is `X_ERROR_CODE_DUPLICATE`. A malformed one — both or
205
217
  neither of `status`/`offSocket`, a status outside 100-599, a code that is not `X_SCREAMING_SNAKE` —
206
218
  is `X_ERROR_DECLARATION_INVALID`. A code some package already registered — a framework code,
@@ -857,7 +869,7 @@ nothing consulted it before deciding to try again. `As of 2026-08-23`.
857
869
  | `singleFlight({ deadlineMs?, schedule?, signal?, released? })` → `run(key, work, join?)`, `size`, `keys()`, `evict(key)` | N callers on one key are ONE run | who pays for a miss. With `signal`, a live joiner re-leads when its leader was aborted, rather than sharing that rejection. `released(key)` fires each time a key stops being held. Eviction is identity-checked, so a load that settles late never drops the load that replaced it; `deadlineMs` frees the KEY a wedged load would hold forever — it never cancels the work and never rejects a joiner. `evict(key)` does the same on demand, for a caller that learns the load in flight began before a write its result must reflect |
858
870
  | `retryMemo(start)` → `get()`, `started()` | one lazy attempt, shared — a REJECTED one not kept | a boot or a load made once per process. `x ??= start()` keeps a rejection as the answer forever; here the clearing handler is attached at creation, so it runs ahead of every caller's `await` and the next `get()` really starts again. `started()` answers the attempt without making one, so a `close()` never boots what it stops. `@ultimat3/cli`'s `x mcp serve` and the docs site's corpus take it |
859
871
  | `flightGate({ maxConcurrent, maxQueued }, { subject?, overflow? })` | one bound, one queue, one refusal | how many at once. Past the queue the answer is `X_FLIGHT_GATE_OVERLOADED` (503) and never a longer queue; the slot is HANDED to a waiter, never released and re-acquired. Both limits are screened at construction (`finiteCount`, 0 allowed); a width of 0 refuses every caller rather than queueing for a slot that never frees. `run(work, signal?)`: an abort while QUEUED removes the waiter and rejects with the abort's reason |
860
- | `mapBounded(items, fn, { width, signal? })` | `Promise.all(items.map(fn))` with at most `width` in flight | a fan-out with a bound. Results in INPUT order. `width` is required with no default — the caller knows the vendor's limit — and screened by `finiteCount` (≥ 1, else `X_INVARIANT`). `fn(item, index, signal)`: the signal aborts on the first rejection (its reason IS that rejection) or when `signal` aborts; nothing new starts after either. Rejects at once with the first failure, as `Promise.all` does; the caller's abort is `X_ABORTED` naming how many finished |
872
+ | `mapBounded(items, fn, { width, signal?, settle? })` | `Promise.all(items.map(fn))` with at most `width` in flight | a fan-out with a bound. Results in INPUT order. `width` is required with no default — the caller knows the vendor's limit — and screened by `finiteCount` (≥ 1, else `X_INVARIANT`). `fn(item, index, signal)`: the signal aborts on the first rejection (its reason IS that rejection) or when `signal` aborts; nothing new starts after either. Rejects at once with the first failure, as `Promise.all` does; the caller's abort is `X_ABORTED` naming how many finished. `settle: 'all'` answers `PromiseSettledResult<R>[]` in input order, as `Promise.allSettled`: a rejection is recorded and frees its slot for the next item, `fn`'s signal aborts only with `signal`, which still rejects the map with `X_ABORTED` |
861
873
  | `generationFence(subject)` → `generation()`, `bump()`, `guard(issued)` | whether an answer still applies | `X_SUPERSEDED` (499) and `isSuperseded(error)` — the piece nothing in the tree had. `guard` compares `!==`, never `<` |
862
874
  | `isRetryableStatus(status)`, `RETRYABLE_STATUSES` | `>= 500`, plus 408, 409, 425, 429 | which HTTP answers are worth repeating |
863
875
  | `jitterStatedDelay(waitMs, capMs, random?)` | the ONE rule for a delay a responder named | the stated wait as a FLOOR plus a spread in `[0, min(wait / 2, cap))`, so a burst told `Retry-After: 1` does not replay in lockstep. `retryDecision`'s `retry-after` path (floor clamped to `max`; `jitter: 'none'` gets the bare floor) and `@ultimat3/jobs`' rate-limit deferral and webhook throttle all take it |
@@ -886,7 +898,7 @@ Server-only, on its own subpath: `import { outbound, screenDial } from '@ultimat
886
898
 
887
899
  | Export | The one answer | The question it settles |
888
900
  |---|---|---|
889
- | `outbound({ url, vendor, dial, deadlineMs, method?, headers?, body?, idleMs?, maxBytes?, redirect?, retry?, idempotent?, read?, breaker? }, deps?)` | a vendor call | a whole-call deadline clamped by the ambient request, `ctx.signal` (its reason unchanged), core's `retry()` for safe methods only (`X_OUTBOUND_RETRY_UNSAFE`), `Retry-After`, an idle watchdog and a byte cap on the body, `redirect: 'error'` by default, and ten `X_OUTBOUND_*` codes whose causes carry no query and no header. `deps` injects `fetch`, `resolve`, `sleep`, `now`, `random`, `timer`, `env` |
901
+ | `outbound({ url, vendor, dial, deadlineMs, method?, headers?, body?, idleMs?, maxBytes?, redirect?, retry?, idempotent?, read?, breaker?, proxy? }, deps?)` | a vendor call | a whole-call deadline clamped by the ambient request, `ctx.signal` (its reason unchanged), core's `retry()` for safe methods only (`X_OUTBOUND_RETRY_UNSAFE`), `Retry-After`, an idle watchdog and a byte cap on the body, `redirect: 'error'` by default, and eleven `X_OUTBOUND_*` codes whose causes carry no query and no header. `dial: 'public'` is the SSRF screen for a user-supplied URL (resolve, classify every address, pin, re-screen each hop): never a hand-written guard. `proxy` (a URL, `{ url, headers }`, or a per-hop resolver `(target) => … \| undefined`, types `OutboundProxy`, `OutboundProxyTarget`, `OutboundProxyInit`) is chosen AFTER the screen, so a public dial is tunnelled to the approved address with `tls.serverName` intact; its credential is never logged; a bad one is `X_OUTBOUND_PROXY_INVALID`. Inventory and rotation are app code. `deps` injects `fetch`, `resolve`, `sleep`, `now`, `random`, `timer`, `env` |
890
902
  | `screenDial(url, { resolve?, allowPrivate? })` → `{ pin } \| { refused } \| { unresolved }` | where a dial may land | every resolved address classified by `classifyAddress`, the connection pinned with `tls.serverName`. The framework's one `Bun.dns.lookup` (`resolveDialHost`); `@ultimat3/jobs`' webhook target and `@ultimat3/scraping` call it and keep their own codes |
891
903
  | `deadlineSignal(ms, outer?, timer?)` | one attempt's signal | a deadline plus the caller's signal, undone on dispose (no listener left on `outer`, no timer armed) |
892
904
  | `breaker({ name, failures, cooldownMs, classify?, clock? })` → `admit`, `succeeded`, `failed`, `released`, `state`, `failures`, `judge`, `refusal`, `run` | is a dependency down | one state machine, the trigger stays the caller's. One probe in `half-open`, lapsing after `cooldownMs`; `X_BREAKER_OPEN` names `retryAfterSeconds`; `breaker_transitions_total{name,to}`. Per process |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/core",
3
- "version": "31.23.0",
3
+ "version": "31.25.0",
4
4
  "description": "Ultimate's foundation: errors, context, env, config, clock, ids, logging, telemetry, lifecycle",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -54,6 +54,6 @@
54
54
  "test": "bun test"
55
55
  },
56
56
  "dependencies": {
57
- "@ultimat3/schema": "31.23.0"
57
+ "@ultimat3/schema": "31.25.0"
58
58
  }
59
59
  }
package/src/adapter.ts CHANGED
@@ -7,6 +7,8 @@ export type { AdapterSlot } from './adapter-slot';
7
7
  export { adapterSlot } from './adapter-slot';
8
8
  export type { AuditRecord, AuditSink } from './audit';
9
9
  export { installAuditSink, resetAuditSink } from './audit';
10
+ /** The boot's context for `bootWarning`: its roles and per-build store. cli's `startRoles` alone. */
11
+ export { installBootWarnings } from './boot-warning';
10
12
  export type { Clock, FrozenClock, SleepClock } from './clock';
11
13
 
12
14
  export type { ErrorReport, ErrorReporter } from './error-reporter';
@@ -0,0 +1,142 @@
1
+ // Single responsibility: `bootWarning` — the ONE boot line an app or the framework says where a
2
+ // booting role can act on it, once per process or once per build. Production said every warning
3
+ // in all five roles on every boot; a line a role cannot act on is noise that buries the one it can.
4
+ // The per-build memory is a slot the boot fills (cli's storage marker): core cannot reach a disk.
5
+
6
+ import { adapterSlot } from './adapter-slot';
7
+ import { assertCoded } from './assert';
8
+ import { renderCauseValue } from './error-render';
9
+ import { logger } from './logger';
10
+ import type { Role } from './roles';
11
+ import { isRole, resolveRole } from './roles';
12
+
13
+ /** Absent: every call says it. `process`: once per process. `build`: once per build id per role. */
14
+ export type BootWarningOnce = 'process' | 'build';
15
+
16
+ export interface BootWarningSpec {
17
+ /** `X_SCREAMING_SNAKE`: the field an operator's alert matches on. */
18
+ readonly code: string;
19
+ /** The roles that can act on the line. Every other role booting says nothing. */
20
+ readonly roles: readonly Role[];
21
+ readonly once?: BootWarningOnce | undefined;
22
+ readonly message: string;
23
+ readonly fields?: Readonly<Record<string, unknown>> | undefined;
24
+ }
25
+
26
+ /**
27
+ * The per-build memory: calls `say` unless a process of this build and `claim.role` already said
28
+ * `claim.code`. Fails open — a store that cannot answer says the line rather than losing it.
29
+ */
30
+ export type BuildOnceStore = (
31
+ claim: { readonly code: string; readonly role: Role },
32
+ say: () => void,
33
+ ) => Promise<void>;
34
+
35
+ export interface BootWarningLog {
36
+ warn(message: string, fields: Readonly<Record<string, unknown>>): void;
37
+ }
38
+
39
+ /** Who is booting, where `build` remembers, where lines go. Each falls back field by field. */
40
+ export interface BootWarningContext {
41
+ /** `x dev` runs several roles in one process. Default: `[resolveRole()]`. */
42
+ readonly roles?: readonly Role[] | undefined;
43
+ /** Unset: `once: 'build'` degrades to once per process. */
44
+ readonly buildOnce?: BuildOnceStore | undefined;
45
+ readonly log?: BootWarningLog | undefined;
46
+ }
47
+
48
+ const ONCE: ReadonlySet<unknown> = new Set(['process', 'build']);
49
+ const SCREAMING_SNAKE = /^X(?:_[A-Z0-9]+)+$/;
50
+
51
+ /** A stack of frames, each removed by its own release: boots may stop in any order. */
52
+ const installed = adapterSlot<BootWarningContext>(() => ({}));
53
+ /** Codes said under `once: 'process'` (or `build` with no store) by this process. */
54
+ const SAID = new Set<string>();
55
+
56
+ /** The boot's half: the booting roles and the build store. Returns the release of THIS frame. */
57
+ export function installBootWarnings(context: BootWarningContext): () => void {
58
+ return installed.install(context);
59
+ }
60
+
61
+ /** Whether any booting role is one the warning names. */
62
+ export const bootRolesConcerned = (declared: readonly Role[], booting: readonly Role[]): boolean =>
63
+ booting.some((role) => declared.includes(role));
64
+
65
+ function check(spec: BootWarningSpec): void {
66
+ const fix = `bootWarning({ code: 'X_<NAME>', roles: ['web'], once: 'process', message: '…' }) # edit the call that declares ${renderCauseValue(spec.code)}`;
67
+ assertCoded(
68
+ typeof spec.code === 'string' && SCREAMING_SNAKE.test(spec.code),
69
+ 'X_INVARIANT',
70
+ `bootWarning code ${renderCauseValue(spec.code)} is not X_SCREAMING_SNAKE`,
71
+ fix,
72
+ );
73
+ assertCoded(
74
+ Array.isArray(spec.roles) && spec.roles.length > 0 && spec.roles.every(isRole),
75
+ 'X_INVARIANT',
76
+ `bootWarning ${spec.code} names roles ${renderCauseValue(spec.roles)}: a non-empty list of web, sync, worker, scheduler, migrate, replicator`,
77
+ fix,
78
+ );
79
+ assertCoded(
80
+ typeof spec.message === 'string' && spec.message.length > 0,
81
+ 'X_INVARIANT',
82
+ `bootWarning ${spec.code} has no message`,
83
+ fix,
84
+ );
85
+ assertCoded(
86
+ spec.once === undefined || ONCE.has(spec.once),
87
+ 'X_INVARIANT',
88
+ `bootWarning ${spec.code} gives once ${renderCauseValue(spec.once)}: 'process', 'build' or omitted`,
89
+ fix,
90
+ );
91
+ }
92
+
93
+ /**
94
+ * Say `spec.message` as a `warn` line carrying `{ code, ...fields }` when a booting role is one of
95
+ * `spec.roles`, at most as often as `once` allows. Answers whether it was said.
96
+ *
97
+ * ```ts
98
+ * await bootWarning({
99
+ * code: 'X_APP_SEARCH_INDEX_LOCAL',
100
+ * roles: ['web'],
101
+ * once: 'build',
102
+ * message: 'search reads an in-process index: each web pod answers from its own copy',
103
+ * fields: { driver: 'memory' },
104
+ * });
105
+ * ```
106
+ */
107
+ export async function bootWarning(
108
+ spec: BootWarningSpec,
109
+ context?: BootWarningContext,
110
+ ): Promise<boolean> {
111
+ check(spec);
112
+ const frame = installed.current();
113
+ const booting = context?.roles ?? frame.roles ?? [resolveRole()];
114
+ const role = booting.find((candidate) => spec.roles.includes(candidate));
115
+ if (role === undefined) return false;
116
+ const log = context?.log ?? frame.log ?? logger;
117
+ const fields: Record<string, unknown> = { code: spec.code };
118
+ for (const [key, value] of Object.entries(spec.fields ?? {})) {
119
+ if (key !== 'code') fields[key] = value;
120
+ }
121
+ let said = false;
122
+ const say = (): void => {
123
+ said = true;
124
+ log.warn(spec.message, fields);
125
+ };
126
+ const store = context?.buildOnce ?? frame.buildOnce;
127
+ if (spec.once === 'build' && store !== undefined) {
128
+ await store({ code: spec.code, role }, say);
129
+ return said;
130
+ }
131
+ if (spec.once !== undefined) {
132
+ if (SAID.has(spec.code)) return false;
133
+ SAID.add(spec.code);
134
+ }
135
+ say();
136
+ return said;
137
+ }
138
+
139
+ /** Test seam: forget what this process said. Production never forgets. */
140
+ export const resetBootWarnings = (): void => {
141
+ SAID.clear();
142
+ };
@@ -92,6 +92,8 @@ const CORE_CODE_TITLES = {
92
92
  X_CONTRACT_EXERCISE_ENVIRONMENT: 'a contract exercise was asked to run in a deployed environment',
93
93
  X_CONTRACT_EXERCISE_UNSCOPED: 'a contract exercise could not roll back its writes',
94
94
  X_IMAGE_RASTER_BUDGET: 'a synchronous raster transform is over the web role pixel budget',
95
+ X_REDACT_PATTERN_UNSAFE: 'a redactValues() pattern is refused at registration',
96
+ X_OUTBOUND_PROXY_INVALID: 'an outbound HTTP call was given a proxy it cannot use',
95
97
  } as const;
96
98
 
97
99
  export type CoreErrorCode = keyof typeof CORE_CODE_TITLES;
@@ -14,6 +14,8 @@ import {
14
14
  recordDefinedError,
15
15
  } from './error-status-declared';
16
16
  import { isUltimateError, UltimateError } from './errors';
17
+ import { problemMetaRefusal, recordProblemMeta } from './problem-meta-declared';
18
+ import { registerPublicCause } from './public-cause';
17
19
 
18
20
  /** A line written once, or computed from the throw's params. */
19
21
  export type ErrorText<P> = string | ((params: P) => string);
@@ -29,6 +31,13 @@ interface ErrorSpecFields<P> {
29
31
  readonly docs?: string | undefined;
30
32
  readonly retry?: ErrorRetry | undefined;
31
33
  readonly meta?: ((params: P) => Readonly<Record<string, unknown>>) | undefined;
34
+ /**
35
+ * The `meta` keys a problem document for this code carries — the `registerProblemMeta` row,
36
+ * declared here instead. Every other key stays operator-only. Needs `status`.
37
+ */
38
+ readonly problemMeta?: readonly string[] | undefined;
39
+ /** A 5xx whose `cause` a caller may read (`hasPublicCause`); hidden by default. Needs a 5xx. */
40
+ readonly publicCause?: true | undefined;
32
41
  }
33
42
 
34
43
  /**
@@ -106,6 +115,26 @@ function recordSite(code: string): void {
106
115
  const text = <P>(value: ErrorText<P>, params: P): string =>
107
116
  typeof value === 'function' ? value(params) : value;
108
117
 
118
+ /** The problem-document half: keys and a public cause ride a document, so they need a status. */
119
+ function problemRefusalOf<P>(spec: DefineErrorSpec<P>): UltimateError | undefined {
120
+ const { code, problemMeta, publicCause } = spec;
121
+ if (problemMeta === undefined && publicCause === undefined) return undefined;
122
+ if (spec.status === undefined) {
123
+ return invalid(
124
+ code,
125
+ 'gives problemMeta or publicCause with offSocket: no document carries either',
126
+ );
127
+ }
128
+ if (publicCause !== undefined && (publicCause !== true || spec.status < 500)) {
129
+ return invalid(code, 'gives publicCause under status 500: only a 5xx document hides its cause');
130
+ }
131
+ if (problemMeta === undefined) return undefined;
132
+ const refusal = Array.isArray(problemMeta)
133
+ ? problemMetaRefusal(code, problemMeta)
134
+ : 'is not a key list';
135
+ return refusal === undefined ? undefined : invalid(code, `gives problemMeta that ${refusal}`);
136
+ }
137
+
109
138
  /** Every refusal, before any table is written: a refused declaration leaves no half behind. */
110
139
  function refusalOf<P>(spec: DefineErrorSpec<P>): UltimateError | undefined {
111
140
  const { code } = spec;
@@ -143,7 +172,7 @@ function refusalOf<P>(spec: DefineErrorSpec<P>): UltimateError | undefined {
143
172
  if ((defined !== undefined || status !== undefined) && status !== spec.status) {
144
173
  return duplicate(code, status === undefined ? 'off-socket' : `with the status ${status}`);
145
174
  }
146
- return undefined;
175
+ return problemRefusalOf(spec);
147
176
  }
148
177
 
149
178
  /**
@@ -158,6 +187,8 @@ function refusalOf<P>(spec: DefineErrorSpec<P>): UltimateError | undefined {
158
187
  * status: 404,
159
188
  * cause: (p) => `no post ${p.ref} in the actor's organisation`,
160
189
  * fix: 'x queries show postById --json, then pass an id it returns',
190
+ * meta: (p) => ({ ref: p.ref }),
191
+ * problemMeta: ['ref'], // optional: which meta keys the problem document carries
161
192
  * });
162
193
  * throw new PostNotFound({ ref });
163
194
  * ```
@@ -174,6 +205,8 @@ export function defineError<P = undefined>(spec: DefineErrorSpec<P>): DefinedErr
174
205
  }
175
206
  if (spec.status !== undefined) declareAppErrorStatus(code, spec.status);
176
207
  recordDefinedError(code, spec.status);
208
+ if (spec.problemMeta !== undefined) recordProblemMeta(code, spec.problemMeta);
209
+ if (spec.publicCause === true) registerPublicCause(code);
177
210
  recordSite(code);
178
211
 
179
212
  class Defined extends UltimateError {
@@ -17,7 +17,9 @@ import {
17
17
  import { type CodedErrorInit, UltimateError } from './errors';
18
18
  import { traceId } from './ids';
19
19
  import { logger, redactFields } from './logger';
20
+ import { redactedValue } from './redact-values';
20
21
  import { sentryFrames } from './sentry-frames';
22
+ import { frameworkVersion } from './version';
21
23
 
22
24
  export type { SentryReporterOptions } from './error-reporter-sentry-hooks';
23
25
 
@@ -121,6 +123,9 @@ function payloadOf(
121
123
  code: report.code,
122
124
  source: report.source,
123
125
  service_version: report.resource.serviceVersion,
126
+ // Bounded by construction: one value per deploy. `release` is the app's build, so this is
127
+ // the only field that says which framework release an event came from.
128
+ framework_version: frameworkVersion(),
124
129
  ...(report.scope.role === undefined ? {} : { role: report.scope.role }),
125
130
  },
126
131
  ...(report.scope.traceId === undefined
@@ -140,11 +145,12 @@ function payloadOf(
140
145
  ...redactFields(report.scope.extra ?? {}),
141
146
  // The whole point of reporting the framework's contract instead of a message: whoever is
142
147
  // paged reads the runnable fix next to the failure.
143
- fix: report.fix,
148
+ // A fix interpolates the failing value as often as a cause does: same value redaction.
149
+ fix: redactedValue(report.fix),
144
150
  docs: report.docs,
145
151
  ...(report.scope.requestId === undefined ? {} : { requestId: report.scope.requestId }),
146
152
  ...(report.scope.actorId === undefined ? {} : { actorId: report.scope.actorId }),
147
- ...(report.stack === undefined ? {} : { stack: report.stack }),
153
+ ...(report.stack === undefined ? {} : { stack: redactedValue(report.stack) }),
148
154
  // Under its own key, so no name an error author picks can collide with one above.
149
155
  ...(report.meta === undefined ? {} : { meta: redactFields(report.meta) }),
150
156
  },
@@ -157,7 +163,8 @@ function exceptionOf(report: ErrorReport): Record<string, unknown> {
157
163
  const frames = sentryFrames(report.stack);
158
164
  return {
159
165
  type: report.code,
160
- value: `${report.title} — ${report.cause}`,
166
+ // The cause is the string most likely to carry a value the app declared secret by shape.
167
+ value: redactedValue(`${report.title} — ${report.cause}`),
161
168
  // `extra.stack` keeps the raw string for one release beside these (31.6.0); a monitor rule
162
169
  // reading it has that long to move.
163
170
  ...(frames.length === 0 ? {} : { stacktrace: { frames } }),
@@ -103,13 +103,14 @@ export type {
103
103
  export { INSTRUMENT_EVENTS } from '../instrument-events';
104
104
  export { SEMCONV, SEMCONV_METRICS, SEMCONV_VALUES } from '../instrument-semconv';
105
105
  export { callerStack, captureStatementStacks, resetStatementStacks } from '../instrument-stacks';
106
- export type { LogFields, Logger, LoggerOptions, LogLevel } from '../logger';
106
+ export type { LogFields, Logger, LoggerOptions, LogLevel, RedactValueMatcher } from '../logger';
107
107
  export {
108
108
  isRedactedKey,
109
109
  LOG_LEVELS,
110
110
  logger,
111
111
  REDACTED,
112
112
  redactKeys,
113
+ redactValues,
113
114
  setLoggerContextFields,
114
115
  setLogStream,
115
116
  structuredLogger,
@@ -174,6 +175,7 @@ export type { OtlpMetricExporter, OtlpMetricExporterOptions } from '../otlp-metr
174
175
  export { otlpMetricExporter, otlpMetricsRequest } from '../otlp-metric-exporter';
175
176
  export type { OtlpSpanExporter, OtlpSpanExporterOptions } from '../otlp-span-exporter';
176
177
  export { otlpSpanExporter, otlpTraceRequest } from '../otlp-span-exporter';
178
+ export { RedactPatternUnsafeError } from '../redact-values';
177
179
  export type { RequestSample } from '../runtime-metrics';
178
180
  export {
179
181
  connections,
@@ -3,6 +3,7 @@
3
3
  // `REDACTED` and LISTED by path, so `x repro` can say which fields it had to invent.
4
4
 
5
5
  import { isRedactedKey } from './logger';
6
+ import { redactedValue } from './redact-values';
6
7
  import { isSecret, REDACTED } from './secret';
7
8
 
8
9
  /** Deep enough for any input that is a request and not a document; past it the subtree is cut. */
@@ -21,6 +22,8 @@ function walk(value: unknown, at: string, depth: number, masked: string[]): unkn
21
22
  masked.push(at === '' ? '(the value)' : at);
22
23
  return REDACTED;
23
24
  }
25
+ // A bundle is replayed by `x repro` and shown in the dashboard: the app's value patterns apply.
26
+ if (typeof value === 'string') return redactedValue(value);
24
27
  if (value === null || typeof value !== 'object') return value;
25
28
  if (value instanceof Date) return value.toISOString();
26
29
  if (depth >= MAX_DEPTH) return '[depth-limit]';
package/src/index.ts CHANGED
@@ -84,6 +84,18 @@ export {
84
84
  } from './aws-sigv4';
85
85
  export type { BackoffCurve, BackoffOptions, JitterMode, Random } from './backoff';
86
86
  export { backoffDelay, jitterStatedDelay } from './backoff';
87
+ export type {
88
+ BootWarningContext,
89
+ BootWarningLog,
90
+ BootWarningOnce,
91
+ BootWarningSpec,
92
+ BuildOnceStore,
93
+ } from './boot-warning';
94
+ export {
95
+ bootRolesConcerned,
96
+ bootWarning,
97
+ resetBootWarnings,
98
+ } from './boot-warning';
87
99
  export type {
88
100
  Breaker,
89
101
  BreakerOptions,
@@ -501,6 +513,7 @@ export type {
501
513
  QueryReadEvent,
502
514
  ReadableMetric,
503
515
  ReadableSpan,
516
+ RedactValueMatcher,
504
517
  RenderHoleEvent,
505
518
  RenderPageEvent,
506
519
  ReportErrorOptions,
@@ -592,6 +605,7 @@ export {
592
605
  parseTraceparent,
593
606
  queueDepth,
594
607
  REDACTED,
608
+ RedactPatternUnsafeError,
595
609
  recordConnection,
596
610
  recordFailureFact,
597
611
  recordFailureInput,
@@ -600,6 +614,7 @@ export {
600
614
  recordQueueDepth,
601
615
  recordRequest,
602
616
  redactKeys,
617
+ redactValues,
603
618
  reportError,
604
619
  requestDuration,
605
620
  requests,
@@ -851,9 +866,14 @@ export {
851
866
  resetMeasurementActor,
852
867
  } from './measurement-actor';
853
868
  export { nearestName } from './nearest-name';
854
- // An outage said on failures 1, 2, 4, 8, … and once when it ends.
855
- export type { OutageLog, OutageLogOptions } from './outage-log';
856
- export { isOutageMilestone, outageLog } from './outage-log';
869
+ // An outage said on failures 1, 2, 4, 8, … — or once per cause, a streak — and once when it ends.
870
+ export type {
871
+ FailureStreak,
872
+ FailureStreakOptions,
873
+ OutageLog,
874
+ OutageLogOptions,
875
+ } from './outage-log';
876
+ export { failureFields, failureStreak, isOutageMilestone, outageLog } from './outage-log';
857
877
  /** The message pwa's `sw.js` posts and realtime's outbox listens for. */
858
878
  export { OUTBOX_DRAIN_MESSAGE } from './outbox-drain';
859
879
  /** The `<meta name>`s render writes and the page client, realtime and pwa read. */
@@ -879,6 +899,13 @@ export type { ProbeDatabaseEntropy } from './probe-database';
879
899
  export { probeDatabaseName } from './probe-database';
880
900
  export type { ProbeDatabaseSweepOptions } from './probe-database-sweep';
881
901
  export { sweepProbeDatabases, sweepStaleProbeDatabases } from './probe-database-sweep';
902
+ export {
903
+ declaredProblemMeta,
904
+ metaKeyRefusal,
905
+ problemMetaRefusal,
906
+ recordProblemMeta,
907
+ resetDeclaredProblemMeta,
908
+ } from './problem-meta-declared';
882
909
  export type { ProcessMetricsOptions, ProcessReading } from './process-metrics';
883
910
  export { startProcessMetrics } from './process-metrics';
884
911
  export { hasPublicCause, registerPublicCause, resetPublicCauses } from './public-cause';
@@ -4,6 +4,12 @@
4
4
 
5
5
  import { renderCauseValue } from './error-render';
6
6
  import { isUltimateError } from './errors';
7
+ import {
8
+ addValueMatchers,
9
+ type RedactValueMatcher,
10
+ redactedStrings,
11
+ redactedValue,
12
+ } from './redact-values';
7
13
  import { isSecret, REDACTED } from './secret';
8
14
 
9
15
  /** What a `Date` this file cannot render says instead — the line survives, the value is named. */
@@ -116,7 +122,20 @@ export function redactKeys(keys: Iterable<string>): void {
116
122
  generation += 1;
117
123
  }
118
124
 
119
- /** Bumped by every `redactKeys` call. A snapshot redacted at an older generation is stale. */
125
+ /**
126
+ * Mark VALUES as secret everywhere: every match of each `pattern` becomes its `replace`, in every
127
+ * string a log line, the monitor envelope or an error's rendering carries. The key list cannot see
128
+ * an account number inside a message; this can. Each pattern needs `g`; one repeating a group
129
+ * that holds a repeating quantifier, `y`, or an empty match is refused (`X_REDACT_PATTERN_UNSAFE`)
130
+ * and the whole list with it. Call once at boot, beside `defineEnv`. The framework registers none.
131
+ */
132
+ export function redactValues(list: readonly RedactValueMatcher[]): void {
133
+ addValueMatchers(list);
134
+ // Same reason as `redactKeys`: a logger's fields bound before this call must be walked again.
135
+ generation += 1;
136
+ }
137
+
138
+ /** Bumped by every `redactKeys` / `redactValues` call. A snapshot redacted at an older generation is stale. */
120
139
  let generation = 0;
121
140
 
122
141
  /** The current redaction generation: one integer compare is the whole cost of staying current. */
@@ -167,6 +186,7 @@ function serialiseValue(value: unknown, depth: number): unknown {
167
186
  function serialise(value: unknown, depth: number): unknown {
168
187
  // `JSON.stringify` raises a `TypeError` on a bigint, so the whole line died for one field.
169
188
  if (typeof value === 'bigint') return renderCauseValue(value);
189
+ if (typeof value === 'string') return redactedValue(value);
170
190
  if (value === null || typeof value !== 'object') return value;
171
191
  // Before every other branch: a `Secret` is redacted by VALUE, so it stays redacted under a key
172
192
  // nobody listed — `{ dsn: secret(url) }` is the leak key-name redaction cannot see.
@@ -176,8 +196,8 @@ function serialise(value: unknown, depth: number): unknown {
176
196
  if (value instanceof Date) {
177
197
  return Number.isNaN(value.getTime()) ? INVALID_DATE : value.toISOString();
178
198
  }
179
- if (isUltimateError(value)) return value.toJSON();
180
- if (value instanceof Error) return { name: value.name, message: value.message };
199
+ if (isUltimateError(value)) return redactedStrings(value.toJSON());
200
+ if (value instanceof Error) return { name: value.name, message: redactedValue(value.message) };
181
201
  if (depth >= 6) return '[depth-limit]';
182
202
  if (Array.isArray(value)) return value.map((item) => serialiseValue(item, depth + 1));
183
203
  const source = value as Record<string, unknown>;
package/src/logger.ts CHANGED
@@ -9,10 +9,12 @@ import { renderCauseValue } from './error-render';
9
9
  import { subscribed } from './instrument';
10
10
  import { publishRecord } from './logger-record';
11
11
  import { INVALID_DATE, type LogFields, redactFields, redactionGeneration } from './logger-redact';
12
+ import { redactedValue } from './redact-values';
12
13
 
13
14
  // The redaction half lives in `logger-redact.ts`; every caller keeps importing it from here.
14
15
  export type { LogFields } from './logger-redact';
15
- export { isRedactedKey, redactFields, redactKeys } from './logger-redact';
16
+ export { isRedactedKey, redactFields, redactKeys, redactValues } from './logger-redact';
17
+ export type { RedactValueMatcher } from './redact-values';
16
18
  // Re-exported, not redefined: `secret.ts` owns the placeholder because a `Secret` has to render
17
19
  // it without importing the logger, and two constants spelled the same is one rename from a leak.
18
20
  export { REDACTED } from './secret';
@@ -325,8 +327,10 @@ function current(bound: Bound): Readonly<Record<string, unknown>> {
325
327
  function derive(level: LogLevel, bound: Bound, clock: Clock, writer: LogSink): Logger {
326
328
  const threshold = LEVEL_WEIGHT[level];
327
329
 
328
- function emit(lineLevel: LogLevel, message: string, fields?: LogFields): void {
330
+ function emit(lineLevel: LogLevel, raw: string, fields?: LogFields): void {
329
331
  if (LEVEL_WEIGHT[lineLevel] < threshold) return;
332
+ // The message is a string a caller interpolated: the one leaf `redactFields` never sees.
333
+ const message = redactedValue(raw);
330
334
  const context = contextFields();
331
335
  const caller = {
332
336
  ...current(bound),