@ultimat3/core 31.27.0 → 31.29.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
@@ -147,6 +147,7 @@ server-only, never on `page.ts`. One call site per recorder; a second is the bug
147
147
  | `recordJob` | `@ultimat3/jobs` `worker.ts`, the outcome branch inside `tick()` (`JOB_OUTCOME_LABELS` drops `suspended`) |
148
148
  | `recordLeaseLost` | `@ultimat3/jobs` `heartbeat.ts`, once per lapsed lease |
149
149
  | `recordBreakerTransition` | `breaker.ts`, on every state change |
150
+ | `recordFrameworkSchema` | `@ultimat3/cli`'s framework-schema verdict (`schema-metrics.ts`) |
150
151
 
151
152
  - **One bus, `instrument.ts`**: every observer is a `subscribe()` — OTLP spans (`span.end`, sampled
152
153
  only), logs (`log.record`), metrics. No `set*Observer`/`set*Sink`/`recent*()` slot
package/README.md CHANGED
@@ -53,7 +53,7 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
53
53
  | typed env validated at boot | `env.ts` |
54
54
  | `.env.example` rendered from that schema, and its drift check | `env-example.ts` |
55
55
  | named environments + `ULTIMATE_ENV` resolution | `environment.ts` |
56
- | which store backs a seam — `storeMode(env)`: `memory` under `test`, `database` everywhere else | `store-mode.ts` |
56
+ | which store backs a seam — `storeMode(env)`: `memory` under `test`, `database` everywhere else; `withStoreMode(mode, work)` declares the answer for a process that knows better (`x exercise`: a test process on its scratch database) | `store-mode.ts` |
57
57
  | the boot refusal of a shipped dev signing secret outside development/test — `X_CURSOR_SECRET_DEV` | `dev-secrets.ts` |
58
58
  | a value that cannot be printed by accident | `secret.ts` |
59
59
  | the committed encrypted secrets envelope, AES-256-GCM | `secrets.ts` |
@@ -102,6 +102,7 @@ JSON.stringify({ dsn }); // the value never prints: a Secret redacts by value, a
102
102
  | the `/metrics` scrape body | `metrics-text.ts` |
103
103
  | the series every process emits, incl. what the chart scales on | `runtime-metrics.ts` |
104
104
  | 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}`, `process_memory_limit_bytes` (cgroup `memory.max`; absent when unbounded) — **server-only**, never on `@ultimat3/core/page` | `process-metrics.ts` (`startProcessMetrics`) |
105
+ | whether this build's framework schema is applied and the newest applied build's major skew: `framework_schema_applied`, `framework_schema_major_skew` — `recordFrameworkSchema({ applied, majorSkew })`, one call per stamp verdict; the chart's `UltimateSchemaUnapplied` and `UltimateVersionSkew` read them | `schema-metrics.ts` |
105
106
  | graceful drain, `/healthz`, `/readyz` | `lifecycle.ts` |
106
107
  | 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` |
107
108
  | the readiness grace between `/readyz` → 503 and the listener closing (`drain.readinessGraceMs`) | `lifecycle-grace.ts` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/core",
3
- "version": "31.27.0",
3
+ "version": "31.29.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.27.0"
57
+ "@ultimat3/schema": "31.29.0"
58
58
  }
59
59
  }
@@ -111,7 +111,8 @@ export function renderCauseValue(value: unknown): string {
111
111
  * `\u2028` and `\u2029` are included because they terminate a line for a JavaScript parser and
112
112
  * for several log viewers, while `String.prototype.split('\n')` never sees them.
113
113
  *
114
- * The set is every C0 control, DEL, and `\u2028`/`\u2029`. Line breaks are the structural half —
114
+ * The set is every C0 control, DEL, every C1 control (`\u009b` is a one-byte CSI), and
115
+ * `\u2028`/`\u2029`. Line breaks are the structural half —
115
116
  * they add a line to a line-oriented format — and the rest ride along because a terminal reads them
116
117
  * as commands of its own: a raw `\u001b` in a cause is an ANSI escape, so a value could repaint the
117
118
  * screen, hide the line above it or move the cursor over what a reader had already been shown.
@@ -121,7 +122,7 @@ export function renderCauseValue(value: unknown): string {
121
122
  */
122
123
  export function singleLine(text: string): string {
123
124
  // biome-ignore lint/suspicious/noControlCharactersInRegex: escaping them is the point.
124
- return text.replace(/[\u0000-\u001f\u007f\u2028\u2029]/g, (char) => {
125
+ return text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, (char) => {
125
126
  const known = Object.hasOwn(CONTROL_ESCAPES, char) ? CONTROL_ESCAPES[char] : undefined;
126
127
  if (known !== undefined) return known;
127
128
  return `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`;
@@ -98,6 +98,7 @@ export type {
98
98
  RenderPageEvent,
99
99
  StatementAttribution,
100
100
  StorageEvent,
101
+ StorageMultipartEvent,
101
102
  TimedEvent,
102
103
  } from '../instrument-events';
103
104
  export { INSTRUMENT_EVENTS } from '../instrument-events';
@@ -54,11 +54,12 @@ export const FRAMEWORK_ENV: readonly FrameworkEnvName[] = [
54
54
  ...contract('cli', 'NODE_ENV', 'TRUSTED_PROXY_HOPS', 'WORKER_QUEUES', 'SENTRY_DSN'),
55
55
  ...contract('cli', 'S3_ENDPOINT', 'S3_BUCKET', 'S3_REGION', 'S3_FORCE_PATH_STYLE'),
56
56
  ...contract('cli', 'SCRAPE_CDP_URL', 'TLS_CERT', 'TLS_KEY'),
57
+ ...contract('cli', 'ULTIMATE_SCHEMA_WAIT_MS'),
57
58
  ...toggles('cli', 'OTEL_SDK_DISABLED'),
58
59
  ...internal('cli', 'ULTIMATE_SEED_TIER', 'ULTIMATE_STATE_DIR', 'ULTIMATE_BUILD_CAPTURE'),
59
60
  ...internal('cli', 'ULTIMATE_DEV_CHILD', 'ULTIMATE_DEV_SUPERVISOR_PID', 'X_ENV'),
60
61
  ...internal('cli', 'ULTIMATE_KEEP_GLOBAL_CLI', 'ULTIMATE_VERIFY_STEP', 'CI_RUNNER'),
61
- ...host('cli', 'CI', 'GITHUB_SHA', 'GITHUB_BASE_REF', 'EDITOR', 'VISUAL'),
62
+ ...host('cli', 'CI', 'GITHUB_SHA', 'GITHUB_BASE_REF', 'EDITOR', 'VISUAL', 'USERPROFILE'),
62
63
  ...contract('core', 'ULTIMATE_ENV', 'ROLE', 'BUILD_ID', 'APP_VERSION', 'LOG_LEVEL'),
63
64
  ...contract('core', 'ULTIMATE_CURSOR_SECRET', 'ULTIMATE_SECRETS_KEY'),
64
65
  ...contract('core', 'ULTIMATE_SECRETS_RETIRED_KEYS', 'METRICS_INTERVAL_MS'),
package/src/index.ts CHANGED
@@ -536,6 +536,7 @@ export type {
536
536
  StartSpanOptions,
537
537
  StatementAttribution,
538
538
  StorageEvent,
539
+ StorageMultipartEvent,
539
540
  TelemetryOptions,
540
541
  TimedEvent,
541
542
  } from './exports/observability';
@@ -960,6 +961,8 @@ export { HYDRATE_STRATEGIES, OFFLINE_STRATEGIES, RENDER_MODES, SURFACES } from '
960
961
  export { safeUrl, URL_ATTRIBUTES } from './safe-url';
961
962
  export type { OriginEvidence } from './same-origin';
962
963
  export { type OriginVerdict, proveSameOrigin } from './same-origin';
964
+ export type { FrameworkSchemaSample } from './schema-metrics';
965
+ export { recordFrameworkSchema } from './schema-metrics';
963
966
  export type { SealOptions, SealPurposeOptions } from './seal';
964
967
  export { isSealed, open, openText, seal, sealAll, sealedKeyId } from './seal';
965
968
  export { SealInvalidError, SealKeyMissingError, SealKeyUnknownError } from './seal-errors';
@@ -990,7 +993,7 @@ export { singleFlight } from './single-flight';
990
993
  export { ambientClock, noWaitClock } from './sleep-clock';
991
994
  export { endOfLiteral, maskLiterals, QUOTES, stripComments } from './source-mask';
992
995
  export type { StoreMode } from './store-mode';
993
- export { storeMode } from './store-mode';
996
+ export { storeMode, withStoreMode } from './store-mode';
994
997
  export { THEME_STORAGE_KEY } from './theme-storage';
995
998
  export { timingSafeEqual } from './timing-safe-equal';
996
999
  export type { ToolDescriptionSource } from './tool-description';
@@ -144,6 +144,15 @@ export interface StorageEvent extends TimedEvent {
144
144
  readonly bytes?: number | undefined;
145
145
  }
146
146
 
147
+ /**
148
+ * One change to a multipart upload session on a resolved disk: opened, a part stored, assembled
149
+ * into the object at `key`, or dropped with its parts. Signing a part URL or listing parts changes
150
+ * nothing and is no event. `bytes` is the part's, or the assembled object's.
151
+ */
152
+ export interface StorageMultipartEvent extends StorageEvent {
153
+ readonly op: 'create' | 'part' | 'complete' | 'abort';
154
+ }
155
+
147
156
  export interface CacheLookupEvent {
148
157
  readonly tier: string;
149
158
  readonly key: string;
@@ -207,6 +216,7 @@ export interface FrameworkEventMap {
207
216
  'storage.copy': StorageEvent;
208
217
  'storage.delete': StorageEvent;
209
218
  'storage.list': StorageEvent;
219
+ 'storage.multipart': StorageMultipartEvent;
210
220
  'cache.hit': CacheLookupEvent;
211
221
  'cache.miss': CacheLookupEvent;
212
222
  'cache.invalidate': CacheInvalidateEvent;
@@ -259,6 +269,7 @@ export const INSTRUMENT_EVENTS = Object.freeze({
259
269
  'storage.copy': { span: 'client', owner: '@ultimat3/storage' },
260
270
  'storage.delete': { span: 'client', owner: '@ultimat3/storage' },
261
271
  'storage.list': { span: 'client', owner: '@ultimat3/storage' },
272
+ 'storage.multipart': { span: 'client', owner: '@ultimat3/storage' },
262
273
  'cache.hit': { span: 'event', owner: '@ultimat3/cache' },
263
274
  'cache.miss': { span: 'event', owner: '@ultimat3/cache' },
264
275
  'cache.invalidate': { span: 'internal', owner: '@ultimat3/cache' },
@@ -62,7 +62,10 @@ const redactedKeys = new Set<string>([
62
62
  * snake and the header spelling. It names what BEARS a credential and nothing wider, because a
63
63
  * redacted field is one an operator cannot correlate on:
64
64
  *
65
- * - `password` / `passphrase` anywhere — no ordinary field carries the word.
65
+ * - `password` / `passphrase` ANYWHERE — `password1`, `new_password2`, `passwordConfirm` are all
66
+ * plaintext — except the named metadata: a `has`/`is` prefix, and a `policy`, `minLength`,
67
+ * `maxLength`, `length`, `changedAt` or `set` suffix. `pass` / `pwd` as a service's credential
68
+ * (`SMTP_PASS`, `dbPwd`, `pgpass`); the shell's own `PWD` / `OLDPWD` stay readable.
66
69
  * - `secret` as the LAST word (`mfaSecret`, `webhookSecret`, `appSecrets`, `secretAccessKey`), so
67
70
  * `clientSecretEnv` and `secretsPath` — a variable name and a path — stay readable.
68
71
  * - a `token` is a bearer UNLESS its qualifier says it is not: fail closed, with the exceptions
@@ -84,6 +87,7 @@ const redactedKeys = new Set<string>([
84
87
  * `credentialId`, `jwtIssuer`, `cookieName`, `privateKeyId` name a credential, not hold one.
85
88
  * - card verification codes (`cvv`, `cvc2`) as a suffix, and a `pin` only as the WHOLE word
86
89
  * behind an owner qualifier — three letters inside `spinner`, `shipping` or `pinned` are not one.
90
+ * Any other owner (`ADMIN_PIN`, `adminPin`) is `SEGMENT`'s, below; a `passcode` as a suffix.
87
91
  *
88
92
  * Built from constant alternatives with no nested quantifier, so there is no input it backtracks on.
89
93
  */
@@ -96,11 +100,17 @@ const verdicts = new Map<string, boolean>();
96
100
  /** Exported for its own work-count test only (`logger-redact.test.ts`); never on the barrel. */
97
101
  export const CREDENTIAL_NAME = new RegExp(
98
102
  [
99
- 'passw(?:or)?d|passphrase',
100
- 'secrets?$',
101
- '(?:api|private|signing|encryption|master|hmac|secrets?|access|retired)keys?$|accesskeyid$',
103
+ '(?<!^(?:has|is))passw(?:or)?d(?!(?:policy|minlength|maxlength|length|changedat|set)$)|passphrase',
104
+ 'passcodes?(?:hash(?:es)?)?$|(?<!^(?:old)?)pwd$',
105
+ '^(?:db|pg|smtp|mail|redis|mysql|ldap|ftp|sftp|proxy|admin|root|user|api|imap|amqp|mongo)?pass$',
106
+ 'secrets?$|secretkeybase$',
107
+ '(?:api|private|signing|encryption|master|hmac|secrets?|access|retired|tls|ssl|client|license|app|stripe)keys?$|accesskeyid$',
102
108
  '(?:token|key)hash(?:es)?$',
103
- '(?<!idempotency|page|continuation|cursor|sync)token$',
109
+ '(?<!idempotency|page|continuation|cursor|sync|next|resume|start|cancellation)token$',
110
+ 'authorization$|authheader$|^auth$|^npmconfigauth$',
111
+ '^session$|sessid$',
112
+ '(?:totp|mfa|otp)seeds?$',
113
+ 'codeverifier$|clientassertion$|samlresponse$|webhookurls?$',
104
114
  '(?:access|refresh|id|session|reset|bearer|auth|api|csrf|xsrf|captcha|card|verification|invite|magic|magiclink|device|push|workload|oauth)tokens$',
105
115
  'authconfig$|connectionstring$|dsn$',
106
116
  '(?:database|db|redis|replication|nats|smtp|amqp|mongo)ur[li]s?$',
@@ -113,6 +123,41 @@ export const CREDENTIAL_NAME = new RegExp(
113
123
  ].join('|'),
114
124
  );
115
125
 
126
+ /**
127
+ * A short credential word by SEGMENT, which the joined form above cannot see: `ADMIN_PIN` and
128
+ * `adminPin` are `adminpin`, and no list of owners is complete. Asked of the key split at camel
129
+ * humps, `_`, `-` and `.` (`admin_pin`, `connect_sid`), so each word matches only whole and last:
130
+ * a `pin` (or before `code` / `number` / `hash`), a `pass`, a session `sid`, a personal access
131
+ * token `pat` — and `spinner`, `mapping`, `pinned`, `bypass`, `sidebar` and `pattern` stay readable.
132
+ */
133
+ const SEGMENT = /(?:^|_)(?:pin(?:_(?:code|number))?(?:_hash(?:es)?)?|pass(?:_hash)?|sid|pat)$/;
134
+
135
+ /**
136
+ * An env-spelled `*_KEY` (`STRIPE_KEY`, `SENDGRID_KEY`) is key material whatever the provider: a
137
+ * provider list is never complete. Only SCREAMING_SNAKE, because a camel `fooKey` in app data is a
138
+ * lookup far more often than a credential (`cacheKey`, `sortKey`), and those stay on the joined
139
+ * list's qualifiers instead. The lookups an env var does name keep their reading.
140
+ */
141
+ const ENV_KEY = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*_KEYS?$/;
142
+ const LOOKUP_KEY =
143
+ /(?:^|_)(?:CACHE|IDEMPOTENCY|PARTITION|PRIMARY|FOREIGN|SORT|I18N|ROUTING|DEDUPE|SHARD|LOOKUP|OBJECT)_KEYS?$/;
144
+ const isEnvKeyMaterial = (key: string): boolean => ENV_KEY.test(key) && !LOOKUP_KEY.test(key);
145
+
146
+ /** How much of a key's end the segment rules read. */
147
+ const SEGMENT_WINDOW = 64;
148
+
149
+ /** `adminPin` / `ADMIN_PIN` / `PINCode` / `admin-pin` → `admin_pin` / `pin_code`: one word per segment. */
150
+ const segmented = (key: string): string =>
151
+ // The TAIL only: every segment rule ends at `$` and spans under 20 characters, and a key is caller
152
+ // data — the camel-hump pass over 20,000 capitals took 1.2 s. 64 keeps every word whole.
153
+ key
154
+ .slice(-SEGMENT_WINDOW)
155
+ // A lookahead, not `([A-Z]+)([A-Z][a-z])`: the same split, with nothing to backtrack over.
156
+ .replace(/([A-Z])(?=[A-Z][a-z])/g, '$1_')
157
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
158
+ .replace(/[-.]/g, '_')
159
+ .toLowerCase();
160
+
116
161
  /** Mark keys as secret everywhere. `defineEnv()` calls this for every `secret: true` var. */
117
162
  export function redactKeys(keys: Iterable<string>): void {
118
163
  for (const key of keys) redactedKeys.add(key.toLowerCase());
@@ -155,7 +200,11 @@ export function isRedactedKey(key: string): boolean {
155
200
  const known = verdicts.get(key);
156
201
  if (known !== undefined) return known;
157
202
  const lower = key.toLowerCase();
158
- const verdict = redactedKeys.has(lower) || CREDENTIAL_NAME.test(lower.replace(/[_-]/g, ''));
203
+ const verdict =
204
+ redactedKeys.has(lower) ||
205
+ CREDENTIAL_NAME.test(lower.replace(/[_-]/g, '')) ||
206
+ SEGMENT.test(segmented(key)) ||
207
+ isEnvKeyMaterial(key);
159
208
  // Insertion order is age, so the first key is the oldest: FIFO, no bookkeeping per hit. Bounded
160
209
  // because a key is caller data — a request body's own keys reach `redactFields`.
161
210
  if (verdicts.size >= REDACTION_MEMO_SIZE) verdicts.delete(verdicts.keys().next().value ?? '');
@@ -0,0 +1,41 @@
1
+ // Single responsibility: whether this process's build has its framework schema applied, and whether
2
+ // the newest applied build is another major — as two gauges, so a rollout that ran its roles before
3
+ // migrate, or a fleet left straddling a breaking release, raises an alert instead of a log line.
4
+
5
+ import type { Gauge } from './metrics';
6
+ import { gauge } from './metrics';
7
+
8
+ interface SchemaGauges {
9
+ readonly applied: Gauge;
10
+ readonly majorSkew: Gauge;
11
+ }
12
+
13
+ let declared: SchemaGauges | undefined;
14
+
15
+ /** On the first verdict, never at import: a process that verifies nothing declares no series. */
16
+ function gauges(): SchemaGauges {
17
+ declared ??= {
18
+ applied: gauge('framework_schema_applied', {
19
+ unit: '1',
20
+ description:
21
+ "1 when this build's schema is applied: the framework stamp and every app migration it ships. 0 while a role waits for the migrate step",
22
+ }),
23
+ majorSkew: gauge('framework_schema_major_skew', {
24
+ unit: '1',
25
+ description: '1 when the newest applied framework schema is another major than this build',
26
+ }),
27
+ };
28
+ return declared;
29
+ }
30
+
31
+ export interface FrameworkSchemaSample {
32
+ readonly applied: boolean;
33
+ readonly majorSkew: boolean;
34
+ }
35
+
36
+ /** One call per stamp verdict, from the serving role's framework-schema check. */
37
+ export function recordFrameworkSchema(sample: FrameworkSchemaSample): void {
38
+ const g = gauges();
39
+ g.applied.record(sample.applied ? 1 : 0);
40
+ g.majorSkew.record(sample.majorSkew ? 1 : 0);
41
+ }
package/src/store-mode.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  // Which store backs a framework seam in this process — the in-memory one or the database — decided
2
2
  // once. Three apps each wrote the ternary with a different predicate, and under `x dev` one seam
3
- // sat in memory while every repository read the embedded Postgres.
3
+ // sat in memory while every repository read the embedded Postgres. A process that knows better than
4
+ // its environment — `x exercise`, a test process on a migrated scratch database — declares it.
4
5
 
6
+ import { assert } from './assert';
7
+ import { asyncContext } from './async-context';
5
8
  import { resolveEnvironment } from './environment';
6
9
 
7
10
  export const STORE_MODES = ['memory', 'database'] as const;
@@ -9,7 +12,33 @@ export const STORE_MODES = ['memory', 'database'] as const;
9
12
  export type StoreMode = (typeof STORE_MODES)[number];
10
13
 
11
14
  /**
12
- * `memory` under `test`, `database` everywhere else. The environment and never `DATABASE_URL`:
15
+ * The process slot `withStoreMode` writes: the declared mode and the call that declared it. On
16
+ * `globalThis` under a registered symbol rather than a module `let`: an app's modules and the CLI
17
+ * may hold two copies of core, and both must read it.
18
+ */
19
+ const DECLARED: unique symbol = Symbol.for('ultimate.store-mode');
20
+
21
+ interface Declared {
22
+ readonly mode: StoreMode;
23
+ /** The declaring call's identity, in flight in its `work`: what a nested call is inside. */
24
+ readonly owner: object;
25
+ }
26
+
27
+ /** Which declaration the caller's async context is inside — `undefined` outside every one. */
28
+ const inside = asyncContext<object>('the declared store mode');
29
+
30
+ const declared = (): Declared | undefined => {
31
+ const value: unknown = Reflect.get(globalThis, DECLARED);
32
+ if (typeof value !== 'object' || value === null) return undefined;
33
+ const mode: unknown = Reflect.get(value, 'mode');
34
+ const owner: unknown = Reflect.get(value, 'owner');
35
+ if (mode !== 'memory' && mode !== 'database') return undefined;
36
+ return typeof owner === 'object' && owner !== null ? { mode, owner } : undefined;
37
+ };
38
+
39
+ /**
40
+ * The mode `withStoreMode` declared, if any; else `memory` under `test`, `database` everywhere
41
+ * else. The environment and never `DATABASE_URL`:
13
42
  * `x dev` installs the embedded PGlite as the process client and sets no URL, and a container
14
43
  * gets its pool from the URL — both are `database`. `bun test` installs no client at all, so a
15
44
  * statement there would have nothing to reach; that is the one carve-out. An unknown
@@ -19,5 +48,34 @@ export type StoreMode = (typeof STORE_MODES)[number];
19
48
  * process environment, so the caller passes `Bun.env`.
20
49
  */
21
50
  export function storeMode(env: Readonly<Record<string, string | undefined>>): StoreMode {
51
+ const active = declared();
52
+ if (active !== undefined) return active.mode;
22
53
  return resolveEnvironment({ env }) === 'test' ? 'memory' : 'database';
23
54
  }
55
+
56
+ /**
57
+ * `mode` as `storeMode`'s answer for the length of `work`, whatever the environment says — for a
58
+ * process whose stores a module picks at LOAD, so it is process-wide and not async-scoped. Only
59
+ * `x exercise` calls it: a test process (`ULTIMATE_ENV=test`) on a migrated scratch database,
60
+ * where a seam left in memory would make every reach writing it prove nothing. Restored after,
61
+ * thrown or not; nested inside the in-flight one's `work`, the inner one wins until it returns.
62
+ *
63
+ * Any other overlap is refused (`X_INVARIANT`): two declarations side by side restore out of order
64
+ * — A ends and restores nothing, B ends and restores A's — and the process keeps a mode nobody
65
+ * declares any more. One process has one answer, so a second must wait for the first.
66
+ */
67
+ export async function withStoreMode<T>(mode: StoreMode, work: () => Promise<T>): Promise<T> {
68
+ const before = declared();
69
+ assert(
70
+ before === undefined || inside.get() === before.owner,
71
+ `withStoreMode('${mode}') started while withStoreMode('${before?.mode ?? mode}') is in flight and not inside its work: the two would restore out of order`,
72
+ `await withStoreMode('${mode}', work) // after the in-flight one resolves, or from inside its work`,
73
+ );
74
+ const owner = {};
75
+ Reflect.set(globalThis, DECLARED, { mode, owner } satisfies Declared);
76
+ try {
77
+ return await inside.run(owner, work);
78
+ } finally {
79
+ Reflect.set(globalThis, DECLARED, before);
80
+ }
81
+ }