@ultimat3/core 31.6.0 → 31.7.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
@@ -44,6 +44,7 @@ top-level `UltimateError` use in `error-codes.ts`.
44
44
  — on the `.` barrel, a test seam and not a port (`scripts/lib/adapter-port-pins.ts`); a stack,
45
45
  `finally` releases; preloads install one that drops lines (`LOG_LEVEL` named = none).
46
46
  WHERE a line goes, never whether: the level is untouched.
47
+ - `teeLogLines(tee)` adds a COPY of every process-logger line beside the streams (a set, each release its own; a throwing tee loses only its copy) — `x dev`'s `dev.log`.
47
48
  - `logger.ts` must not import `context.ts` (`context.ts` injects ids via `setLoggerContextFields()`).
48
49
  It imports `secret.ts` one way only: `secret.ts` owns `REDACTED`, `logger.ts` re-exports it.
49
50
  - **`ActorFacts` is the app's extension point on `Actor`** (module augmentation). Core never declares
@@ -71,6 +72,7 @@ top-level `UltimateError` use in `error-codes.ts`.
71
72
  | 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 † |
72
73
  | 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 |
73
74
  | how many at once | `flight-gate.ts` | hand-over on release, refusal past `maxQueued`, injectable `overflow:` refusal |
75
+ | 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 |
74
76
  | whether an answer still applies | `generation-fence.ts` | `X_SUPERSEDED` / `isSuperseded` |
75
77
  | which HTTP statuses are worth repeating | `retryable-status.ts` | `>= 500` plus 408, 409, 425, 429 |
76
78
  | how long this request has left | `request-budget.ts` (`Ctx.deadlineAt`) | http's `startDeadline` writes the instant, `traceHeaders()` the header † |
@@ -85,14 +87,16 @@ top-level `UltimateError` use in `error-codes.ts`.
85
87
  | 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 |
86
88
  | is this `unknown` a keyed record? | `json-object.ts` (`isJsonObject`) | narrows a shape; does not certify provenance |
87
89
  | 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 |
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 |
90
+ | 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` |
89
91
  | a value that must not be printed | `secret.ts` | redacted by VALUE; `revealSecret()` is the one, greppable, way out |
90
92
  | 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 † |
91
93
  | 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 |
92
94
  | 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()` |
93
95
  | 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
96
  | one outbound HTTP call | `outbound*.ts`, entry `outbound-subpath.ts` | never on the barrel; `screenDial` holds the one `Bun.dns.lookup` † |
97
+ | retries as a share of calls | `breaker-retry-budget.ts` (`retryBudgetOf`) | per breaker key: a call earns 1, a retry costs 5 (≤ 20%), burst 10; a refused retry answers the last error |
95
98
  | 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
+ | where a raster transform runs | `image/raster-pool.ts` + `raster-worker.ts` + `raster-wire.ts` | one lazy Worker; inline only where none starts (one warn), the web role then held to `RASTER_SYNC_PIXELS` (`X_IMAGE_RASTER_BUDGET`). A compile that bundles core adds `rasterWorkerBundle()` (`raster-worker-bundle.ts`). Never `transformInline` on a request path |
96
100
  | what an element carries, for a test | `render-nodes.ts` + `render-node.ts` | the one walker, imported from the subpath, never copied † |
97
101
 
98
102
  - **`installSecrets()` is the ONLY path from `secrets.enc.json` to an app value**, landing in
@@ -148,7 +152,7 @@ server-only, never on `page.ts`. One call site per recorder; a second is the bug
148
152
  - **`postOtlp` (`otlp-post.ts`) retries `OTLP_RETRY_STATUSES` and a transport failure only**, never `isRetryableStatus`. Full rule: `docs/history/core.md`.
149
153
  - **`errorFingerprint` (`error-fingerprint.ts`) is a function, never an `ErrorReport` field**:
150
154
  `code`, `source`, `scope.operation`, plus the top app frame for `X_INTERNAL` only. Never `cause`,
151
- `meta`, ids or `release`. Total over hostile getters; the Sentry envelope's `fingerprint`.
155
+ `meta`, ids or `release`. Total over hostile getters; the LOCAL group; the monitor's is `monitorFingerprint` (`[code]`; `X_INTERNAL` + app frame; `X_CLIENT_ERROR` + operation).
152
156
  - **Failure capture is OFF by default** (`config-failure-capture.ts`, `failureCapture.enabled`;
153
157
  `x dev` forces it on): with no `FailureStore` installed nothing allocates. The OUTER
154
158
  `invoke`/`runQuery` opens one buffer (`withFailureCapture`, `failure-capture.ts`); seams record
package/README.md CHANGED
@@ -33,6 +33,7 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
33
33
  | which HTTP statuses are worth repeating | `retryable-status.ts` |
34
34
  | N callers on one key are ONE run | `single-flight.ts` |
35
35
  | how many may run at once, and how many may wait | `flight-gate.ts` |
36
+ | a concurrent map with a stated width — input order kept, the first rejection aborts the rest | `map-bounded.ts` |
36
37
  | whether an answer still applies — `X_SUPERSEDED` | `generation-fence.ts` |
37
38
  | the five composed into one typed-client call — dedup, fence, retry, deadline, ceiling | `client-flight.ts` |
38
39
  | what a typed client puts on the wire and reads back off it | `client-wire.ts` |
@@ -72,6 +73,7 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
72
73
  | `Clock` — the only source of "now" | `clock.ts` |
73
74
  | UUIDv7, nanoid, branded ids | `ids.ts` |
74
75
  | 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` |
76
+ | `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` |
75
77
  | 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
78
  | the event vocabulary: `INSTRUMENT_EVENTS`, every payload type, `InstrumentEventMap` (augmentable — an app's own names ride the same bus) | `instrument-events.ts` |
77
79
  | semconv names: `SEMCONV` (span attribute keys), `SEMCONV_VALUES`, `SEMCONV_METRICS` | `instrument-semconv.ts` |
@@ -87,7 +89,8 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
87
89
  | 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` |
88
90
  | `reportError` + the `ErrorReporter` seam, no-op by default | `error-reporter.ts` |
89
91
  | that seam on the wire, Sentry's envelope and DSN | `error-reporter-sentry.ts` |
90
- | which reports are one fault (`errorFingerprint`) | `error-fingerprint.ts` |
92
+ | which reports are one fault (`errorFingerprint`), and the monitor's grouping (`monitorFingerprint`) | `error-fingerprint.ts` |
93
+ | a V8 stack as frames, for the monitor and the fingerprint | `sentry-frames.ts` |
91
94
  | OTel-shaped counter / gauge / histogram, same seam | `metrics.ts` |
92
95
  | the `/metrics` scrape body | `metrics-text.ts` |
93
96
  | the series every process emits, incl. what the chart scales on | `runtime-metrics.ts` |
@@ -272,6 +275,7 @@ a job boundary the class is gone and the `code` is what survives — match on th
272
275
  | `EnvMissingError` | `X_ENV_MISSING` | `src/errors.ts` |
273
276
  | `ErrorReporterDsnInvalidError` | `X_ERROR_REPORTER_DSN_INVALID` | `src/error-reporter-sentry.ts` |
274
277
  | `ImageDecodeFailedError` | `X_IMAGE_DECODE_FAILED` | `src/image/errors.ts` |
278
+ | `ImageRasterBudgetError` | `X_IMAGE_RASTER_BUDGET` | `src/image/errors.ts` |
275
279
  | `ImageTooLargeError` | `X_IMAGE_TOO_LARGE` | `src/image/errors.ts` |
276
280
  | `ImageUnsupportedError` | `X_IMAGE_UNSUPPORTED` | `src/image/errors.ts` |
277
281
  | `InternalError` | `X_INTERNAL` | `src/errors.ts` |
@@ -694,7 +698,8 @@ release();
694
698
  | 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`) |
695
699
  | 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 |
696
700
  | `errorReport(error, options)` | the normalisation on its own, for a transport's test or a surface that enriches before sending |
697
- | `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` |
701
+ | `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 LOCAL group (failure capture keys on it), never the monitor's |
702
+ | `monitorFingerprint(report)` | the monitor's grouping, sent as the Sentry envelope's `fingerprint`: `[code]`; `X_INTERNAL` adds the top app frame, `X_CLIENT_ERROR` the operation. A `fingerprint` hook on `sentryErrorReporter` replaces it |
698
703
  | `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` |
699
704
 
700
705
  `As of 2026-08` four packages call `reportError`, seven call sites in all: `@ultimat3/http`'s
@@ -837,6 +842,7 @@ nothing consulted it before deciding to try again. `As of 2026-08-23`.
837
842
  | `backoffDelay({ attempt, base, max, factor?, curve?, jitter?, random? })` | one curve — `exponential \| linear \| fixed`, `full \| equal \| none` — 1-based `attempt`, clamped to `max` **before** jitter, rounded, and `0` rather than `NaN` | how long to wait. `random` is injectable, so a schedule is a unit test rather than a range |
838
843
  | `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 |
839
844
  | `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 |
845
+ | `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 |
840
846
  | `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 `<` |
841
847
  | `isRetryableStatus(status)`, `RETRYABLE_STATUSES` | `>= 500`, plus 408, 409, 425, 429 | which HTTP answers are worth repeating |
842
848
  | `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 |
@@ -869,6 +875,7 @@ Server-only, on its own subpath: `import { outbound, screenDial } from '@ultimat
869
875
  | `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 |
870
876
  | `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) |
871
877
  | `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 |
878
+ | `retryBudgetOf(breaker)` → `called()`, `spend()` | retries as a share of calls, per breaker key | whether one more retry may go out during a partial outage the breaker cannot see: a call earns 1 token, a retry costs 5 (retries ≤ 20% of calls), a quiet key starts with a burst of 10 retries. Keyed by breaker identity, per process; `outbound` consults it, and a refused retry answers the last error |
872
879
 
873
880
  ## One Redis client
874
881
 
@@ -960,6 +967,25 @@ box it is one `Bun.Image` call, source bytes to encoded bytes. When it is not
960
967
  (`process.getBuiltinModule`), never imported: a static import made every browser build of the
961
968
  barrel warn.
962
969
 
970
+ **`transformImageBytes` runs in a Worker** (`raster-worker.ts`, one per process, started at the
971
+ first transform, `unref`'d while idle) — its inflate and deflate are synchronous, and inline on a
972
+ 4096² source they blocked the event loop 98-1,945 ms (measured 2026-11-11); through the Worker the
973
+ worst gap is 1-41 ms, the 41 being the copy of a 42 MB source. The Worker runs `transformInline`
974
+ (`transform-inline.ts`), so the bytes are the inline bytes (`raster-pool.test.ts`, byte for byte);
975
+ a coded refusal crosses as its own class (`raster-wire.ts`). Where no Worker can start — a compiled
976
+ executable compiled without the worker, or a worker file that never loads — the transform runs
977
+ inline, says so once at warn (`image.raster_worker_unavailable`, with the reason), and on the web role
978
+ (`ROLE`) a crop or composite whose hops would inflate plus deflate more than `RASTER_SYNC_PIXELS`
979
+ (409,600) is `X_IMAGE_RASTER_BUDGET` (503): warm the variants in a job instead
980
+ (`warmVariants`, `@ultimat3/storage`'s `image-warm.ts`). A plain resize is never budgeted —
981
+ `Bun.Image` already resamples off the loop.
982
+
983
+ A compile that BUNDLES core adds the worker itself: Bun detects no `new Worker(…)` target. Pass
984
+ `rasterWorkerBundle([entry])`'s `entrypoint` beside the entry and merge its `define`
985
+ (`RASTER_WORKER_DEFINE`, the worker's path under `/$bunfs/root/`); `raster-worker-compile.e2e.test.ts`
986
+ compiles and runs both shapes. An app's `x build --target binary` needs neither: it keeps
987
+ `@ultimat3/*` external, so core — and its worker file — load from `node_modules`.
988
+
963
989
  Adding a format is an entry in `DECODABLE_FORMATS` / `ENCODABLE_FORMATS` and a branch in
964
990
  `withFormat` — never a second dispatch. An unencodable `format` is refused from the spec alone,
965
991
  before the source is decoded, so a request nothing can write never expands 64 megapixels first.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/core",
3
- "version": "31.6.0",
3
+ "version": "31.7.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.6.0"
57
+ "@ultimat3/schema": "31.7.0"
58
58
  }
59
59
  }
@@ -0,0 +1,48 @@
1
+ // Single responsibility: the retry token ratio per breaker key — retries at most a fifth of calls,
2
+ // so a fleet retrying a partially failing vendor cannot multiply its load by the attempt count.
3
+ // The breaker cannot see that outage (no run of CONSECUTIVE failures); the attempt clamp is per call.
4
+
5
+ import type { Breaker } from './breaker';
6
+
7
+ /** Whole units, never a fractional token: a call earns 1, a retry costs 5 — the 20% ratio. */
8
+ const CALL_CREDIT = 1;
9
+ const RETRY_COST = 5;
10
+
11
+ /** Retries a quiet key may spend before calls earn any back: a low-traffic caller still retries. */
12
+ export const RETRY_BURST = 10;
13
+ const BANK_CAP = RETRY_BURST * RETRY_COST;
14
+
15
+ export interface RetryBudget {
16
+ /** One call went out: earns a fifth of a retry, up to the burst. */
17
+ called(): void;
18
+ /** May one more retry go out: spends it when yes. */
19
+ spend(): boolean;
20
+ }
21
+
22
+ /**
23
+ * By breaker identity: the breaker IS the key (`name` is a label two breakers may share), and a
24
+ * breaker dropped by its owner takes its budget with it. Per process, as the breaker is.
25
+ */
26
+ const budgets = new WeakMap<Breaker, RetryBudget>();
27
+
28
+ function retryBudget(): RetryBudget {
29
+ let bank = BANK_CAP;
30
+ return {
31
+ called() {
32
+ bank = Math.min(BANK_CAP, bank + CALL_CREDIT);
33
+ },
34
+ spend() {
35
+ if (bank < RETRY_COST) return false;
36
+ bank -= RETRY_COST;
37
+ return true;
38
+ },
39
+ };
40
+ }
41
+
42
+ export function retryBudgetOf(gate: Breaker): RetryBudget {
43
+ const known = budgets.get(gate);
44
+ if (known !== undefined) return known;
45
+ const made = retryBudget();
46
+ budgets.set(gate, made);
47
+ return made;
48
+ }
@@ -0,0 +1,30 @@
1
+ // Single responsibility: the boot screen for `cache.tiers` — every entry a rung the ladder can
2
+ // build, and at least one. Split from `config.ts` so the validator stays under its line ceiling.
3
+
4
+ import { CACHE_TIERS } from './cache-vocabulary';
5
+ import { renderCauseValue } from './error-render';
6
+
7
+ /**
8
+ * A rung the ladder cannot build is the defect this key had: `sortTiers` places a name by its
9
+ * index in `CACHE_TIERS`, and a name missing from it sorts to `-1` — AHEAD of the request memo.
10
+ * So an unknown tier is refused at boot rather than silently ignored or silently placed first.
11
+ * An EMPTY ladder is refused with the unknown rung: it builds no tier at all, so every read
12
+ * misses and nothing says the cache was configured away.
13
+ *
14
+ * `renderCauseValue`, never `${tier}`: an untyped config file can say a Symbol or a null-prototype
15
+ * object here, and interpolating either throws a bare `TypeError` where the coded refusal belongs.
16
+ *
17
+ * Answers whether a tier NAME failed, so the caller appends the rename remedy only then.
18
+ */
19
+ export function cacheTierIssues(tiers: readonly unknown[], issues: string[]): boolean {
20
+ if (tiers.length === 0) issues.push('cache.tiers must list at least one tier');
21
+ let unknownTier = false;
22
+ for (const tier of tiers) {
23
+ if ((CACHE_TIERS as readonly unknown[]).includes(tier)) continue;
24
+ issues.push(
25
+ `cache.tiers contains ${renderCauseValue(tier)}, which is not one of ${CACHE_TIERS.join(', ')}`,
26
+ );
27
+ unknownTier = true;
28
+ }
29
+ return unknownTier;
30
+ }
package/src/config.ts CHANGED
@@ -5,9 +5,10 @@
5
5
  // Same rule for the same reason: `app.config.ts` CONSUMES the cache tier names, it does not own
6
6
  // them. Declaring them here is what let `cache.tiers` and the ladder `@ultimat3/cache` orders by
7
7
  // drift into two vocabularies with no map between them (issue #293).
8
- import { CACHE_TIERS, type CacheTierName } from './cache-vocabulary';
8
+ import type { CacheTierName } from './cache-vocabulary';
9
9
  import type { AiConfig, AiConfigInput } from './config-ai';
10
10
  import * as assetsSection from './config-assets';
11
+ import { cacheTierIssues } from './config-cache';
11
12
  import * as clientErrors from './config-client-errors';
12
13
  import { countIssue } from './config-count';
13
14
  import { configDefaults } from './config-defaults';
@@ -349,17 +350,7 @@ function validate(config: AppConfig): void {
349
350
  failureCapture.failureCaptureIssues(config, issues);
350
351
  timeSection.timeIssues(config, issues);
351
352
 
352
- // A rung the ladder cannot build is the defect this key had: `sortTiers` places a name by its
353
- // index in `CACHE_TIERS`, and a name missing from it sorts to `-1` — AHEAD of the request memo.
354
- // So an unknown tier is refused at boot rather than silently ignored or silently placed first.
355
- // An EMPTY ladder is refused with the unknown rung: it builds no tier at all, so every read
356
- // misses and nothing says the cache was configured away.
357
- if (config.cache.tiers.length === 0) issues.push('cache.tiers must list at least one tier');
358
- for (const tier of config.cache.tiers) {
359
- if (CACHE_TIERS.includes(tier)) continue;
360
- issues.push(`cache.tiers contains "${tier}", which is not one of ${CACHE_TIERS.join(', ')}`);
361
- if (tierFix.length === 0) tierFix.push(CACHE_TIER_FIX);
362
- }
353
+ if (cacheTierIssues(config.cache.tiers, issues)) tierFix.push(CACHE_TIER_FIX);
363
354
 
364
355
  if (issues.length > 0) {
365
356
  throw new ConfigInvalidError({
@@ -91,6 +91,7 @@ const CORE_CODE_TITLES = {
91
91
  X_ACTION_ERRORS_INVALID: 'an errors: list names a code that cannot be declared there',
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
+ X_IMAGE_RASTER_BUDGET: 'a synchronous raster transform is over the web role pixel budget',
94
95
  } as const;
95
96
 
96
97
  export type CoreErrorCode = keyof typeof CORE_CODE_TITLES;
@@ -5,18 +5,13 @@
5
5
  import { fingerprint } from './canonical-json';
6
6
  import { stringField } from './error-render';
7
7
  import type { ErrorReport } from './error-reporter';
8
+ import { stackFrames } from './sentry-frames';
8
9
 
9
10
  /** `errorReport()`'s code for a throw nobody classified: the one code too wide to group on. */
10
11
  const UNCLASSIFIED = 'X_INTERNAL';
11
12
 
12
- /** ` at fn (path:1:2)`, ` at async fn (path:1:2)`, ` at path:1:2`. */
13
- const FRAME = /^\s*at\s+(?:async\s+)?(?:(.*?)\s+\((.*)\)|(.*))$/;
14
-
15
- /** A line and a column, or a line alone: an edit above the throw moves both. */
16
- const POSITION = /(?::\d+){1,2}$/;
17
-
18
- /** Library frames: the first frame that is the APP's names the fault, not the library under it. */
19
- const LIBRARY = /(?:^|\/)(?:node_modules|@ultimat3)\//;
13
+ /** `@ultimat3/cli`'s one code for every browser fault: its `operation` (pattern + island) is the fault. */
14
+ const BROWSER = 'X_CLIENT_ERROR';
20
15
 
21
16
  /** Reads that cannot throw: this runs on the path that reports a failure, and adds none. */
22
17
  function read<T>(get: () => T): T | undefined {
@@ -27,53 +22,33 @@ function read<T>(get: () => T): T | undefined {
27
22
  }
28
23
  }
29
24
 
30
- function workingDirectory(): string | undefined {
31
- const cwd = read(() => process.cwd());
32
- return cwd === undefined ? undefined : `${cwd.replaceAll('\\', '/').replace(/\/$/, '')}/`;
33
- }
34
-
35
- /** `file://`, the working directory and the position dropped; `/` separators on every OS. */
36
- function relativePath(location: string, root: string | undefined): string {
37
- let path = location.trim().replace(POSITION, '').replaceAll('\\', '/');
38
- if (path.startsWith('file://')) path = path.slice('file://'.length);
39
- if (root !== undefined && path.startsWith(root)) path = path.slice(root.length);
40
- return path.replace(/^\.\//, '');
41
- }
42
-
43
- /**
44
- * The stack's FRAMES: the trailing run of `at …` lines. Read from the end, because the header
45
- * above them is the error's message, and a message may itself hold `\n at x (y:1:1)` — which
46
- * read top-down would set the group to whatever the message's author typed.
47
- */
48
- function framesOf(stack: string): readonly RegExpExecArray[] {
49
- const frames: RegExpExecArray[] = [];
50
- const lines = stack.trimEnd().split('\n');
51
- for (let index = lines.length - 1; index >= 0; index -= 1) {
52
- const match = FRAME.exec(lines[index] ?? '');
53
- if (match === null) break;
54
- frames.unshift(match);
55
- }
56
- return frames;
25
+ /** The top application frame as `fn path` (no line, no column), or `undefined`. */
26
+ function applicationFrame(stack: string | undefined): string | undefined {
27
+ if (stack === undefined) return undefined;
28
+ const frame = read(() => stackFrames(stack).find((each) => each.inApp));
29
+ if (frame === undefined) return undefined;
30
+ return frame.fn === undefined ? frame.path : `${frame.fn} ${frame.path}`;
57
31
  }
58
32
 
59
33
  /**
60
- * The top application frame as `fn path`, or `undefined`. A frame with no file location (`native`,
61
- * `<anonymous>`, `processTicksAndRejections (native:7:39)`) is skipped as well: it is the
62
- * runtime's, and two faults share it. A file location has a `/`; a runtime's never does.
34
+ * The monitor's group, as the envelope's `fingerprint` list: `[code]` for a classified code — one
35
+ * code raised from five operations is one issue, its `source` and `operation` facets of it (tags,
36
+ * `transaction`). `X_INTERNAL` adds the application frame, since on its code alone every
37
+ * unclassified throw is one issue; `X_CLIENT_ERROR` adds its operation, since a bundle's frame
38
+ * moves every deploy. Total: a report it cannot read degrades to `[X_INTERNAL]`.
63
39
  */
64
- function applicationFrame(stack: string | undefined): string | undefined {
65
- if (stack === undefined) return undefined;
66
- const root = workingDirectory();
67
- for (const match of framesOf(stack)) {
68
- const location = match[2] ?? match[3] ?? '';
69
- if (!POSITION.test(location.trim())) continue;
70
- if (!location.replaceAll('\\', '/').includes('/')) continue;
71
- const path = relativePath(location, root);
72
- if (path === '' || LIBRARY.test(path)) continue;
73
- const name = (match[1] ?? '').replace(/^new\s+/, '').trim();
74
- return name === '' ? path : `${name} ${path}`;
75
- }
76
- return undefined;
40
+ export function monitorFingerprint(report: ErrorReport): readonly string[] {
41
+ const code = stringField(report, 'code') ?? UNCLASSIFIED;
42
+ const extra =
43
+ code === UNCLASSIFIED
44
+ ? applicationFrame(stringField(report, 'stack'))
45
+ : code === BROWSER
46
+ ? stringField(
47
+ read(() => report.scope),
48
+ 'operation',
49
+ )
50
+ : undefined;
51
+ return extra === undefined ? [code] : [code, extra];
77
52
  }
78
53
 
79
54
  /**
@@ -81,7 +56,8 @@ function applicationFrame(stack: string | undefined): string | undefined {
81
56
  * `scope.operation`; `X_INTERNAL` adds the top application frame (function and root-relative path,
82
57
  * no line or column), because on its code alone every unclassified throw in an app is one group.
83
58
  * Never `cause`, `meta`, an id or `release`: a row id splits one fault into a group per row, and a
84
- * deploy is not a new fault. Total: a report it cannot read degrades to the frameless key.
59
+ * deploy is not a new fault. The LOCAL group (`errorGroupsSink`, failure capture); the monitor's is
60
+ * `monitorFingerprint`. Total: a report it cannot read degrades to the frameless key.
85
61
  */
86
62
  export function errorFingerprint(report: ErrorReport): string {
87
63
  const code = stringField(report, 'code');
@@ -1,6 +1,6 @@
1
- // Single responsibility: the adopter's say over what the Sentry transport sends — drop by code,
2
- // sample, regroup, scrub. Functions of the report or the event, decided per report; the envelope
3
- // format stays `error-reporter-sentry.ts`'s alone.
1
+ // Single responsibility: the adopter's say over the Sentry transport — its one options object
2
+ // (wiring, then drop by code, sample, regroup, scrub), applied per report. The envelope format
3
+ // stays `error-reporter-sentry.ts`'s alone.
4
4
 
5
5
  import { renderThrowable } from './error-render';
6
6
  import type { ErrorReport } from './error-reporter';
@@ -10,16 +10,26 @@ import { logger } from './logger';
10
10
  /** The event payload as the envelope will carry it: the third line, before serialisation. */
11
11
  export type SentryEvent = Readonly<Record<string, unknown>>;
12
12
 
13
- export interface SentryReporterHooks {
13
+ /**
14
+ * `sentryErrorReporter`'s options: the ONE seam over what reaches the monitor. Scrub, drop and
15
+ * regroup are options here, never a wrapper around the transport — a wrapper needs
16
+ * `sentryTransport()` to be recognised, and every behaviour below it is rebuilt by hand.
17
+ */
18
+ export interface SentryReporterOptions {
19
+ /** From the app's typed env. The framework declares no default and ships no constant. */
20
+ readonly dsn: string;
21
+ /** Injected by tests; the preload seals the real one. */
22
+ readonly fetch?: typeof globalThis.fetch | undefined;
23
+ readonly clientName?: string | undefined;
14
24
  /**
15
- * The last word on an event: return it (changed or not) to send, `null` to drop. Scrub by VALUE
16
- * here — `redactFields` already masked by key. A hook that throws drops the event: an event the
17
- * scrubber failed on is exactly the one that must not leave unscrubbed.
25
+ * SCRUB, and the last word on an event: return it (changed or not) to send, `null` to drop.
26
+ * Scrub by VALUE here — `redactFields` already masked by key. A hook that throws drops the event:
27
+ * an event the scrubber failed on is exactly the one that must not leave unscrubbed.
18
28
  */
19
29
  readonly beforeSend?: ((event: SentryEvent) => SentryEvent | null) | undefined;
20
- /** `true` drops every report with this code, before the event is even built. */
30
+ /** DROP by code: `true` drops every report with this code, before the event is even built. */
21
31
  readonly ignore?: ((code: string) => boolean) | undefined;
22
- /** The monitor's grouping, replacing `errorFingerprint`'s one-element default. */
32
+ /** The monitor's grouping, replacing `monitorFingerprint`'s default (`[code]`, …). */
23
33
  readonly fingerprint?: ((report: ErrorReport) => readonly string[]) | undefined;
24
34
  /** The share of reports sent, `0..1` inclusive. Default 1: every report. */
25
35
  readonly sampleRate?: number | undefined;
@@ -27,6 +37,12 @@ export interface SentryReporterHooks {
27
37
  readonly random?: (() => number) | undefined;
28
38
  }
29
39
 
40
+ /**
41
+ * The options minus the wiring — the name the hooks shipped under (31.0), kept as an alias of
42
+ * `SentryReporterOptions` so a typed hooks object still spreads in. Not a second seam.
43
+ */
44
+ export type SentryReporterHooks = Omit<SentryReporterOptions, 'dsn' | 'fetch' | 'clientName'>;
45
+
30
46
  /** Refused at wiring time, like the DSN: a rate past 1 or below 0 is a monitor nobody configured. */
31
47
  export function screenSampleRate(rate: number | undefined): number {
32
48
  if (rate === undefined) return 1;
@@ -3,7 +3,7 @@
3
3
  // is documented and several self-hostable monitors ingest it. Nothing here names a host, a project
4
4
  // or an organisation — the DSN is the app's own typed env, passed in at wiring time.
5
5
 
6
- import { errorFingerprint } from './error-fingerprint';
6
+ import { monitorFingerprint } from './error-fingerprint';
7
7
  import { renderThrowable } from './error-render';
8
8
  import type { ErrorReport, ErrorReporter, ErrorSeverity } from './error-reporter';
9
9
  import {
@@ -11,12 +11,15 @@ import {
11
11
  customFingerprint,
12
12
  finalEvent,
13
13
  type SentryEvent,
14
- type SentryReporterHooks,
14
+ type SentryReporterOptions,
15
15
  screenSampleRate,
16
16
  } from './error-reporter-sentry-hooks';
17
17
  import { type CodedErrorInit, UltimateError } from './errors';
18
18
  import { traceId } from './ids';
19
19
  import { logger, redactFields } from './logger';
20
+ import { sentryFrames } from './sentry-frames';
21
+
22
+ export type { SentryReporterOptions } from './error-reporter-sentry-hooks';
20
23
 
21
24
  export class ErrorReporterDsnInvalidError extends UltimateError {
22
25
  static readonly code = 'X_ERROR_REPORTER_DSN_INVALID';
@@ -83,7 +86,7 @@ export interface SentryEnvelopeOptions {
83
86
  readonly dsn: string;
84
87
  /** 32 lowercase hex, no dashes. `traceId()` already produces exactly that shape. */
85
88
  readonly eventId: string;
86
- /** The monitor's grouping. Default: `[errorFingerprint(report)]`. */
89
+ /** The monitor's grouping. Default: `monitorFingerprint(report)`. */
87
90
  readonly fingerprint?: readonly string[] | undefined;
88
91
  }
89
92
 
@@ -109,9 +112,9 @@ function payloadOf(
109
112
  server_name: report.resource.serviceName,
110
113
  ...(report.release === null ? {} : { release: report.release }),
111
114
  ...(report.scope.operation === undefined ? {} : { transaction: report.scope.operation }),
112
- // The group. Without it the monitor groups on its own reading of the exception, which is the
113
- // code, so every unclassified throw in the app was one issue (`errorFingerprint`).
114
- fingerprint: fingerprint ?? [errorFingerprint(report)],
115
+ // The group: the code, so one fault raised from five operations is one issue — never the
116
+ // monitor's own reading of the frames, which splits it per call site (`monitorFingerprint`).
117
+ fingerprint: fingerprint ?? monitorFingerprint(report),
115
118
  // Tags are the monitor's facets, so only bounded values go here — the same rule metric labels
116
119
  // follow. `requestId` and `actorId` are unbounded and live in `extra`.
117
120
  tags: {
@@ -145,7 +148,19 @@ function payloadOf(
145
148
  // Under its own key, so no name an error author picks can collide with one above.
146
149
  ...(report.meta === undefined ? {} : { meta: redactFields(report.meta) }),
147
150
  },
148
- exception: { values: [{ type: report.code, value: `${report.title} — ${report.cause}` }] },
151
+ exception: { values: [exceptionOf(report)] },
152
+ };
153
+ }
154
+
155
+ /** The one exception value: the contract as type and value, the throw's frames when there are any. */
156
+ function exceptionOf(report: ErrorReport): Record<string, unknown> {
157
+ const frames = sentryFrames(report.stack);
158
+ return {
159
+ type: report.code,
160
+ value: `${report.title} — ${report.cause}`,
161
+ // `extra.stack` keeps the raw string for one release beside these (31.6.0); a monitor rule
162
+ // reading it has that long to move.
163
+ ...(frames.length === 0 ? {} : { stacktrace: { frames } }),
149
164
  };
150
165
  }
151
166
 
@@ -170,14 +185,6 @@ function envelopeOf(event: SentryEvent, options: SentryEnvelopeOptions, at: numb
170
185
  return `${header}\n${item}\n${payload}\n`;
171
186
  }
172
187
 
173
- export interface SentryReporterOptions extends SentryReporterHooks {
174
- /** From the app's typed env. The framework declares no default and ships no constant. */
175
- readonly dsn: string;
176
- /** Injected by tests; the preload seals the real one. */
177
- readonly fetch?: typeof globalThis.fetch | undefined;
178
- readonly clientName?: string | undefined;
179
- }
180
-
181
188
  /**
182
189
  * Every reporter that is an app's Sentry transport: built by `sentryErrorReporter`, or marked by
183
190
  * `sentryTransport`. Identity, never shape: a reporter is `{ report }`, and the boot must tell an
@@ -3,7 +3,7 @@
3
3
  // subject — a process's own account of what it did — and `index.ts` re-exports every name below
4
4
  // explicitly, so this file changes what a reader looks at and never what the package exports.
5
5
 
6
- export { errorFingerprint } from '../error-fingerprint';
6
+ export { errorFingerprint, monitorFingerprint } from '../error-fingerprint';
7
7
  export type {
8
8
  ErrorReport,
9
9
  ErrorReporter,
@@ -30,6 +30,25 @@ export class ImageTooLargeError extends UltimateError {
30
30
  }
31
31
  }
32
32
 
33
+ export class ImageRasterBudgetError extends UltimateError {
34
+ static readonly code = 'X_IMAGE_RASTER_BUDGET';
35
+ override readonly name = 'ImageRasterBudgetError';
36
+ constructor(cause: string, fix: string, meta?: Readonly<Record<string, unknown>>) {
37
+ super({ code: ImageRasterBudgetError.code, cause, fix, meta });
38
+ }
39
+ }
40
+
41
+ /**
42
+ * The web role, with no raster Worker, asked to run a raster hop that blocks its event loop past
43
+ * the budget. The fix is the job that makes the request path never decode: `warmVariants`.
44
+ */
45
+ export const imageRasterBudget = (pixels: number, budget: number): ImageRasterBudgetError =>
46
+ new ImageRasterBudgetError(
47
+ `the transform's raster hops touch ${pixels} pixels on the web role's event loop, over its ${budget}-pixel budget, because no raster Worker could start here`,
48
+ 'warmVariants({ disk, key, widths, formats }) # from @ultimat3/storage (packages/storage/src/image-warm.ts), in a job on the worker role, so the media route answers from storage; or run the role from source so transformImageBytes reaches its Worker',
49
+ { pixels, budget },
50
+ );
51
+
33
52
  /** A format or a coding feature the built-in pipeline does not implement. */
34
53
  export const imageUnsupported = (
35
54
  cause: string,