@noy-db/hub 0.7.0-pre.12 → 0.7.0-pre.13
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/CHANGELOG.md +102 -0
- package/dist/cargo/index.js +1 -1
- package/dist/chunk-66TQOPFM.js +37 -0
- package/dist/chunk-66TQOPFM.js.map +1 -0
- package/dist/{chunk-H7XCIM3Z.js → chunk-AJQY44CE.js} +43 -16
- package/dist/chunk-AJQY44CE.js.map +1 -0
- package/dist/{chunk-E5OHKSBD.js → chunk-BMELYFHU.js} +2 -2
- package/dist/chunk-BWXGSSFX.js +1589 -0
- package/dist/chunk-BWXGSSFX.js.map +1 -0
- package/dist/{chunk-HN4FNA4X.js → chunk-COTPDJR5.js} +8 -8
- package/dist/{chunk-E3EBMC4G.js → chunk-E2MYJGSG.js} +2 -2
- package/dist/{chunk-JJR2JIN4.js → chunk-FFBYRWDJ.js} +2 -2
- package/dist/{chunk-WQF3QABE.js → chunk-IHFXR2VQ.js} +9 -79
- package/dist/chunk-IHFXR2VQ.js.map +1 -0
- package/dist/chunk-MGOXJIBV.js +176 -0
- package/dist/chunk-MGOXJIBV.js.map +1 -0
- package/dist/{chunk-KL7AS3HV.js → chunk-PDD75NUZ.js} +5 -2
- package/dist/chunk-PDD75NUZ.js.map +1 -0
- package/dist/chunk-RTBJ5IOO.js +87 -0
- package/dist/chunk-RTBJ5IOO.js.map +1 -0
- package/dist/{chunk-7NTBVFGD.js → chunk-SXCYYMVS.js} +2 -2
- package/dist/{chunk-THNJ3IKU.js → chunk-ULUMAZ5S.js} +2 -2
- package/dist/{chunk-NO272T7Q.js → chunk-V4PXLYWM.js} +2 -31
- package/dist/chunk-V4PXLYWM.js.map +1 -0
- package/dist/{chunk-SWVNZQVR.js → chunk-YPXNAP72.js} +2 -169
- package/dist/chunk-YPXNAP72.js.map +1 -0
- package/dist/{chunk-XMF3GKUR.js → chunk-ZVCC36XQ.js} +50 -870
- package/dist/chunk-ZVCC36XQ.js.map +1 -0
- package/dist/{collection-facade-MGGHQ3HU.js → collection-facade-4ACKIDDY.js} +4 -3
- package/dist/derivations/index.js +6 -2
- package/dist/{dispatch-XEBHUGBV.js → dispatch-MSTR5VBI.js} +10 -5
- package/dist/dispatch-MSTR5VBI.js.map +1 -0
- package/dist/{dispatch-44J4TL72.js → dispatch-PDP5TA73.js} +5 -5
- package/dist/{executor-KSPGNVDO.js → executor-YDDC5XGY.js} +4 -3
- package/dist/index.js +25 -21
- package/dist/index.js.map +1 -1
- package/dist/lazy/index.js +3 -2
- package/dist/materialized-views/index.js +4 -3
- package/dist/{noydb-JJXPICIC.js → noydb-2C6QQJ5S.js} +12 -9
- package/dist/pod/index.js +12 -9
- package/dist/{registry-BZQIVNNO.js → registry-D2YXKRYC.js} +7 -3
- package/dist/search/index.js +1 -1
- package/dist/{stale-KSPG6LFX.js → stale-2CHKZTMK.js} +2 -2
- package/dist/with-formula/derivations/registry.d.ts +6 -7
- package/dist/with-shape/introspection/describe.d.ts +29 -9
- package/package.json +3 -3
- package/dist/chunk-7BE7ZDVQ.js +0 -722
- package/dist/chunk-7BE7ZDVQ.js.map +0 -1
- package/dist/chunk-H7XCIM3Z.js.map +0 -1
- package/dist/chunk-KL7AS3HV.js.map +0 -1
- package/dist/chunk-NO272T7Q.js.map +0 -1
- package/dist/chunk-SWVNZQVR.js.map +0 -1
- package/dist/chunk-WQF3QABE.js.map +0 -1
- package/dist/chunk-XMF3GKUR.js.map +0 -1
- package/dist/dispatch-XEBHUGBV.js.map +0 -1
- /package/dist/{chunk-E5OHKSBD.js.map → chunk-BMELYFHU.js.map} +0 -0
- /package/dist/{chunk-HN4FNA4X.js.map → chunk-COTPDJR5.js.map} +0 -0
- /package/dist/{chunk-E3EBMC4G.js.map → chunk-E2MYJGSG.js.map} +0 -0
- /package/dist/{chunk-JJR2JIN4.js.map → chunk-FFBYRWDJ.js.map} +0 -0
- /package/dist/{chunk-7NTBVFGD.js.map → chunk-SXCYYMVS.js.map} +0 -0
- /package/dist/{chunk-THNJ3IKU.js.map → chunk-ULUMAZ5S.js.map} +0 -0
- /package/dist/{collection-facade-MGGHQ3HU.js.map → collection-facade-4ACKIDDY.js.map} +0 -0
- /package/dist/{dispatch-44J4TL72.js.map → dispatch-PDP5TA73.js.map} +0 -0
- /package/dist/{executor-KSPGNVDO.js.map → executor-YDDC5XGY.js.map} +0 -0
- /package/dist/{noydb-JJXPICIC.js.map → noydb-2C6QQJ5S.js.map} +0 -0
- /package/dist/{registry-BZQIVNNO.js.map → registry-D2YXKRYC.js.map} +0 -0
- /package/dist/{stale-KSPG6LFX.js.map → stale-2CHKZTMK.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/with-shape/introspection/field-meta.ts","../src/with-shape/introspection/describe.ts","../src/kernel/via/graph.ts"],"sourcesContent":["/**\n * Consumer-neutral, data-relatable field descriptors — the canonical,\n * validator-agnostic authoring channel. Merged by `collection.describe()`.\n *\n * Descriptive, never prescriptive: label/semanticType/unit/sensitivity/\n * aggregate/aliases/displayFor only. Layout, styling, and active-locale\n * selection stay app-side.\n *\n * @module\n */\n\n/** Known semantic types; the union is open — unknown strings pass through. */\nexport type SemanticType =\n | 'date' | 'datetime' | 'email' | 'url' | 'currency' | 'percent'\n | 'country' | 'vat' | 'iban' | 'entity'\n | (string & {})\n\nexport interface FieldMeta {\n /** Human label for any displayable field. Required. */\n label: string\n description?: string\n semanticType?: SemanticType\n /** Display unit, e.g. '€', '%', 'kg'. */\n unit?: string\n /** Data classification driving redaction/inspector masking. */\n sensitivity?: 'public' | 'pii' | 'secret'\n /** Default aggregation for this field. */\n aggregate?: 'sum' | 'count' | 'distinct' | 'none'\n /** Canonical search synonyms (data vocabulary, not UI). */\n aliases?: readonly string[]\n /** Entity pairing: the field holding the human label for this id (buyerId → buyerName). */\n displayFor?: string\n /**\n * Override the widget hint derived from semanticType/type.\n * e.g. 'textarea', 'date', 'money', 'select', 'checkbox', 'number', 'text'.\n * When absent, the widget is derived automatically by buildDescription.\n */\n widget?: string\n /**\n * Card/section grouping hint for detail & form layouts (e.g. 'Identity',\n * 'Amounts'). Purely descriptive metadata — consumers group; describe()\n * keeps emitting fields alphabetically.\n */\n group?: string\n /** Relative ordering hint within (and across) groups. Lower renders first. */\n order?: number\n}\n\nexport class FieldMetaUnknownFieldError extends Error {\n constructor(public readonly collection: string, public readonly key: string) {\n super(`fieldMeta for collection \"${collection}\" references unknown field \"${key}\". `\n + `Declare it in the schema/config or remove the fieldMeta entry.`)\n this.name = 'FieldMetaUnknownFieldError'\n }\n}\n\n/** Reject fieldMeta keys that are not known fields (typo guard), fail-loud. */\nexport function validateFieldMetaKeys(\n collection: string,\n fieldMeta: Record<string, FieldMeta>,\n knownFields: ReadonlySet<string>,\n): void {\n for (const key of Object.keys(fieldMeta)) {\n if (!knownFields.has(key)) throw new FieldMetaUnknownFieldError(collection, key)\n }\n}\n\nexport interface MergeInputs {\n channel?: FieldMeta\n zodMeta?: Partial<FieldMeta>\n inferred?: Partial<FieldMeta>\n}\nexport interface ResolvedMeta extends Partial<FieldMeta> { label: string }\n\n/** camelCase / snake_case → Title Case words. */\nexport function humanizeFieldKey(key: string): string {\n return key\n .replace(/[_-]+/g, ' ')\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .trim()\n .split(/\\s+/)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ')\n}\n\n/** Merge one field's metadata: channel > zodMeta > inferred; label always present. */\nexport function resolveFieldMeta(key: string, inputs: MergeInputs): ResolvedMeta {\n const { channel, zodMeta, inferred } = inputs\n const pick = <K extends keyof FieldMeta>(k: K): FieldMeta[K] | undefined =>\n channel?.[k] ?? zodMeta?.[k] ?? inferred?.[k]\n const description = pick('description')\n const semanticType = pick('semanticType')\n const unit = pick('unit')\n const sensitivity = pick('sensitivity')\n const aggregate = pick('aggregate')\n const aliases = pick('aliases')\n const displayFor = pick('displayFor')\n const widget = pick('widget')\n const group = pick('group')\n const order = pick('order')\n return {\n label: pick('label') ?? humanizeFieldKey(key),\n ...(description !== undefined ? { description } : {}),\n ...(semanticType !== undefined ? { semanticType } : {}),\n ...(unit !== undefined ? { unit } : {}),\n ...(sensitivity !== undefined ? { sensitivity } : {}),\n ...(aggregate !== undefined ? { aggregate } : {}),\n ...(aliases !== undefined ? { aliases } : {}),\n ...(displayFor !== undefined ? { displayFor } : {}),\n ...(widget !== undefined ? { widget } : {}),\n ...(group !== undefined ? { group } : {}),\n ...(order !== undefined ? { order } : {}),\n }\n}\n","/**\n * `buildDescription` — pure assembler that merges collection config\n * (moneyFields / dictKeyFields / refs / computed / fieldMeta) with an\n * optional validator-derived `zodFields` map into a normalised\n * {@link CollectionDescription}.\n *\n * The sync path (`collection.describe()`) passes `zodFields: undefined`.\n * The async path supplies a populated map and validator-derived type\n * strings.\n *\n * @module\n */\n\nimport type { FieldMeta } from './field-meta.js'\nimport { resolveFieldMeta, validateFieldMetaKeys, FieldMetaUnknownFieldError, humanizeFieldKey } from './field-meta.js'\nimport type { CollectionMeta } from './meta.js'\nimport type { MoneyDescriptor } from '../../via/money/descriptor.js'\nimport type { ViaDescriptor, ViaPosture } from '../../kernel/via/index.js'\nimport type { DictKeyDescriptor, StaticDictDescriptor } from '../../via/i18n/dictionary.js'\nimport { isStaticDictDescriptor } from '../../via/i18n/dictionary.js'\n// #650 Task 2 — native lookup()/enumOf()/dict() fields (separate from\n// dictKeyFields above, which stays the dictKey()/staticDict() alias's own\n// input). Emits the SAME `dict` block shape for byte-parity (the tiers this\n// covers — 'static' with a table, 'reserved' — are the alias-equivalent\n// ones; a first-class 'collection' backing degrades to the \"no resolved\n// labels\" fallback, same as an unresolved dynamic dictKey).\nimport type { LookupDescriptor } from '../../via/lookup/descriptor.js'\n// #650 Task 7 — the 'lookup' binding's describeFragment payload shape (the\n// first-ever NoydbVia.describeFragment consumer, via/index.ts:136). describe.ts\n// is NOT under kernel/**, so importing this via/ type directly is fine\n// (Check 14 via-layering only restricts the kernel spine).\nimport type { LookupDescribeFragment, LookupDescribeFragmentEntry } from '../../via/lookup/binding.js'\n// #657 — the 'blob' binding's describeFragment payload shape (the second-ever\n// NoydbVia.describeFragment consumer, after lookup above). Same rationale:\n// describe.ts is not under kernel/**, so importing this via/ type is fine.\nimport type { BlobDescribeFragment, BlobDescribeFragmentEntry } from '../../via/blob/binding.js'\nimport type { I18nTextDescriptor } from '../../via/i18n/core.js'\nimport type { ComputedFields } from '../../with-formula/computed/index.js'\nimport type { RefDescriptor } from '../../kernel/refs.js'\nimport type { ClassifiedFieldSpec } from '../../via/classified/descriptor.js'\nimport { derivePersistedSchema, isZod4Schema } from '../persisted-schemas/derive.js'\nimport { loadPersistedSchema } from '../persisted-schemas/storage.js'\nimport { jsonSchemaToFields } from './fields.js'\nimport type { NoydbStore } from '../../kernel/types.js'\nimport type { EnclaveKey } from '../../kernel/enclave/index.js'\n\n// ─── Public types ──────────────────────────────────────────────────────────\n\nexport interface DescribedField {\n readonly key: string\n /**\n * Stable, opaque per-field identity (#946) — survives a rename (the field\n * keeps its id when its name/`key` changes). Sourced from the persisted\n * schema's `PersistedSchemaEnvelope.fieldIds` map, so it is only present on\n * the async `describeAsync()` path for a collection that has persisted a\n * schema (`persistJsonSchema: true`) at least once; absent on the sync\n * `describe()` path (no store I/O) and on any field with no persisted id\n * yet.\n */\n readonly id?: string\n /** Sync: inferred from config ('number'|'enum'|'string'|'array'|'unknown'). Async (Task 4): validator-derived. */\n readonly type: string\n readonly optional: boolean\n readonly constraints?: Record<string, unknown>\n readonly label: string\n readonly description?: string\n /** Card/section grouping hint for detail & form layouts. From fieldMeta/zod .meta(). */\n readonly group?: string\n /** Relative ordering hint within and across groups. Lower renders first. */\n readonly order?: number\n readonly semanticType?: string\n readonly unit?: string\n readonly sensitivity?: 'public' | 'pii' | 'secret'\n readonly aggregate?: 'sum' | 'count' | 'distinct' | 'none'\n readonly aliases?: readonly string[]\n readonly ref?: { target: string; mode: string; isArray?: true }\n readonly displayFor?: string\n readonly money?: { mode: 'fixed' | 'multi'; currency?: string; scale?: number; rounding?: string }\n readonly dict?: { name: string; static: boolean; values?: readonly { value: string; label?: string }[] }\n /**\n * Normalized lookup metadata (#650 Task 7 — the first-ever\n * `NoydbVia.describeFragment` consumer; sourced from the `'lookup'`\n * binding's fragment, NOT from config directly — see `buildDescription`).\n * Present for every `lookup()`/`enumOf()`/`dict()` field, ALONGSIDE the\n * pre-existing `dict` block above (kept byte-stable for the\n * `dictKey()`/`staticDict()` alias — this is additive, not a replacement).\n * `dimension` is omitted for a bare `enumOf()` (no backing store, no\n * dimension name — the #650 Task 2 `dimension:''` sentinel resolved).\n * `keys` is the statically-known closed-vocabulary key set (declared\n * `keys`, or a static table's own keys) — omitted when membership lives\n * only in the backing collection/dictionary.\n */\n readonly lookup?: {\n readonly dimension?: string\n readonly backing: 'static' | 'reserved' | 'collection'\n readonly vocabulary: 'open' | 'closed'\n readonly key: string\n readonly altKeys?: readonly string[]\n readonly present?: { readonly label: string; readonly by?: string }\n readonly sortBy?: string\n readonly onDelete: 'restrict' | 'cascade' | 'nullify'\n readonly keys?: readonly string[]\n }\n readonly computed?: true\n /** i18n metadata for fields declared with i18nText(). Present only when the field is i18n-enabled. */\n readonly i18n?: { readonly locales?: readonly string[]; readonly densify?: boolean }\n /** Widget hint derived from semanticType+type, overridable via fieldMeta.widget. */\n readonly widget: string\n /** Whether the field is user-editable. False for computed, id, and provenance-stamped fields. */\n readonly editable: boolean\n /** Present when the field is classified. Serialized read-projection contract. */\n readonly classified?: {\n readonly preset: string\n readonly storage: 'recoverable' | 'never' | 'digest-only'\n readonly list: 'omit' | { readonly mask: string } | { readonly rider: string }\n /**\n * Present (and `true`) only when the field opted into the equatable blind\n * index. Additive metadata — emitted UNGATED (no `withClassified()` needed;\n * `toJSONSchema()` carries it too), so it advertises *that* the field is\n * equatable beyond the DEK-consent boundary. Intended: it's a structural\n * property a schema consumer legitimately needs and discloses no value. A\n * deployment wanting it gated can gate this behind its value-bearing door.\n */\n readonly equatable?: true\n }\n /**\n * Present only for a field declared via `blobFields` (#657) — out-of-band\n * attachment storage (`collection.blob(id)`), never a sealed or plaintext\n * record field. `queryable` mirrors the binding's fixed `ViaPosture`\n * (blob content is never indexed — always `'none'`); the rest mirrors the\n * declared `blobFields[field]` policy verbatim (scalars) or as a presence\n * flag (predicate knobs — a predicate has no serializable form). Sourced\n * from the `'blob'` binding's `describeFragment()`, the same\n * `viaFragments` door the `lookup` block above is sourced from.\n */\n readonly blob?: {\n readonly retainDays?: number\n readonly evictWhen?: true\n readonly legalHold?: true\n readonly retainUntil?: true\n readonly external?: true\n readonly public?: true\n readonly backlink?: string\n readonly queryable: 'none'\n }\n /**\n * Present only for a graph-tainted derived field (#638 Task 3 — computed/\n * derivation output whose effective posture was forced away from the\n * plain baseline by a source's posture, e.g. a computed field reading a\n * classified field). `forcedBy` names the immediate declared source\n * field(s) responsible.\n */\n readonly taint?: {\n readonly posture: ViaPosture\n readonly forcedBy: readonly string[]\n }\n}\n\nexport interface CollectionDescription {\n readonly collection: string\n readonly fields: readonly DescribedField[]\n /** Collection-level descriptive metadata; label falls back to the humanized collection name. */\n readonly meta: CollectionMeta\n}\n\n/** Options for the async describe(opts) overload. */\nexport interface DescribeOptions {\n /**\n * When true, resolve dynamic-dict labels from vault.dictionary(name).list()\n * and populate dict.values[].label for dynamic dictKey fields.\n */\n readonly resolveDictLabels?: boolean\n}\n\n// ─── ZodField slot (async path wires this; sync path passes undefined) ───\n\nexport interface ZodFieldSlot {\n readonly type?: string\n readonly optional?: boolean\n readonly constraints?: Record<string, unknown>\n readonly meta?: Partial<FieldMeta>\n}\n\n// ─── RECOGNIZED zod-4 .meta() keys ────────────────────────────────────────\n//\n// Empirically verified 2026-06-25 via:\n// node -e \"const {z,toJSONSchema}=require('zod'); console.log(JSON.stringify(toJSONSchema(z.object({n:z.number().meta({label:'L',unit:'kg',sensitivity:'public',semanticType:'percent',description:'d',aggregate:'sum',aliases:['a'],displayFor:'x'})}))), null, 2)\"\n// Result: .meta() keys are emitted INLINE on each JSON Schema property object\n// at the same level as `type`/`format` — NOT nested under a `metadata` key.\n// Example: z.number().meta({ unit: 'kg' }) → { \"type\": \"number\", \"unit\": \"kg\" }\n// Unknown .meta() keys (not in this set) are ignored.\nconst ZOD_META_KEYS = new Set<string>([\n 'label', 'description', 'unit', 'semanticType', 'sensitivity', 'aggregate', 'aliases', 'displayFor',\n 'group', 'order',\n])\n\n// ─── deriveZodFields ──────────────────────────────────────────────────────\n\n/**\n * Derive per-field slots from a Standard Schema validator.\n * - Calls `derivePersistedSchema` to get the JSON Schema.\n * - Falls back to `{}` for non-Zod or unknown validators.\n * - For zod-4 schemas: reads recognized `.meta()` keys from inline property annotations.\n * - Returns: `Record<fieldKey, { type, optional, constraints?, meta? }>`.\n *\n * No static zod import — all zod access is lazy via derivePersistedSchema.\n */\n/**\n * Field KEYS from a configured validator, synchronously — the complement to\n * {@link deriveZodFields}, which derives field TYPES and must be async.\n *\n * The distinction is the whole point (#1253). `describe()`'s sync path passed\n * `zodFields: undefined`, so `fieldMeta` key-validation could never run there\n * and a typo'd key became a PHANTOM FIELD carrying its declared `sensitivity`\n * while the real field went undescribed — an inventory wrong in both\n * directions, silently, on the surface `sensitivity` exists to serve.\n *\n * That was read as unavoidable (\"the sync path cannot know the schema's\n * fields\"), which is true of types and false of keys: a Zod object exposes\n * `.shape` directly, on both v3 and v4, with no JSON-Schema derivation and no\n * `zod-to-json-schema` peer. The latter matters — on Zod 3 that peer is\n * required for the async path, so the sync path is the only one some\n * consumers can reach.\n *\n * A duck-typed probe, not a Zod dependency: an unrecognised validator returns\n * `undefined` and the caller stays silent rather than guessing, so a validator\n * hub cannot read never produces a false \"unknown field\" error.\n *\n * ZodEffects (reported by the pilot on #1249's guard, and it equally affected\n * #1253's): on Zod 3 an OBJECT-LEVEL `.refine()` wraps the object in a\n * ZodEffects whose `.shape` is undefined — the object sits at `_def.schema` —\n * so \"has a schema\" and \"hub can enumerate its fields\" silently diverged for\n * exactly the schemas most worth guarding (validated ones). Unwrapped here,\n * but ONLY through refinement effects: a `.transform()`/`.preprocess()`\n * changes the OUTPUT shape, so its inner keys would be a lie — those stay\n * `undefined` (silent), deliberately. Zod 4 keeps `.shape` through `.refine()`\n * and never enters the loop. Bounded depth, so a cyclic duck cannot hang us.\n */\nexport function schemaFieldKeys(schema: unknown): readonly string[] | undefined {\n let s: unknown = schema\n for (let depth = 0; depth < 10; depth++) {\n if (s === null || typeof s !== 'object') return undefined\n const shape: unknown = (s as { shape?: unknown }).shape\n if (shape !== null && typeof shape === 'object') {\n const keys = Object.keys(shape as Record<string, unknown>)\n return keys.length > 0 ? keys : undefined\n }\n // Zod 3 ZodEffects: follow `_def.schema` for refinements only.\n const def = (s as { _def?: { effect?: { type?: unknown }; schema?: unknown } })._def\n if (def?.schema !== undefined && def.effect?.type === 'refinement') {\n s = def.schema\n continue\n }\n return undefined\n }\n return undefined\n}\n\nexport async function deriveZodFields(\n schema: unknown,\n): Promise<Record<string, ZodFieldSlot>> {\n const envelope = await derivePersistedSchema(schema)\n if (!envelope.jsonSchema) return {}\n\n const isZod4 = isZod4Schema(schema)\n const jsonSchema = envelope.jsonSchema as Record<string, unknown>\n\n // Use the existing JSON-Schema→field mapper for type/optional/constraints.\n const fieldDescriptors = jsonSchemaToFields(jsonSchema, 'live-validator')\n\n // For zod-4: the JSON Schema properties contain inline .meta() annotations.\n // We need to walk the raw properties to extract recognized meta keys.\n const propertiesRaw = jsonSchema['properties'] as Record<string, Record<string, unknown>> | undefined\n\n const result: Record<string, ZodFieldSlot> = {}\n\n for (const [key, descriptor] of Object.entries(fieldDescriptors)) {\n let meta: Partial<FieldMeta> | undefined\n\n if (isZod4 && propertiesRaw) {\n const prop = propertiesRaw[key]\n if (prop) {\n const extracted: Partial<FieldMeta> = {}\n let hasAny = false\n for (const mk of ZOD_META_KEYS) {\n if (mk in prop) {\n (extracted as Record<string, unknown>)[mk] = prop[mk]\n hasAny = true\n }\n }\n if (hasAny) meta = extracted\n }\n }\n\n result[key] = {\n type: descriptor.type,\n optional: descriptor.optional === true,\n ...(descriptor.constraints !== undefined ? { constraints: descriptor.constraints } : {}),\n ...(meta !== undefined ? { meta } : {}),\n }\n }\n\n return result\n}\n\n// ─── resolveDescribeFieldIds (#946) ───────────────────────────────────────\n\n/**\n * Resolve the persisted-schema `fieldIds` map for `describeAsync()`'s\n * `BuildDescriptionInput` (#946). Returns a spreadable partial so the call\n * site can inline it with `...(await resolveDescribeFieldIds(...))` without\n * an intermediate local — `collection.ts`'s `describe()` bodies are under a\n * near-zero line-ceiling headroom.\n *\n * Silent-degrades to `{}` (no ids — every `DescribedField.id` stays\n * `undefined`, never a describe() crash) on any failure: `getDEK` throwing,\n * no persisted envelope yet, or an envelope with no `fieldIds` (legacy /\n * never-persisted). Mirrors the leak/degrade posture of\n * `satellites/dead-filter.ts`'s `liveBaseIdSetsForBundle`, but degrading to\n * \"no ids\" is lossless here (unlike that filter's data-exposure tradeoff) —\n * describe() simply omits `id` for every field.\n */\nexport async function resolveDescribeFieldIds(\n store: NoydbStore,\n vaultName: string,\n collectionName: string,\n getDEK: (collectionName: string) => Promise<EnclaveKey>,\n): Promise<{ fieldIds?: Record<string, string> }> {\n let dek: EnclaveKey\n try {\n dek = await getDEK(collectionName)\n } catch {\n return {}\n }\n const persisted = await loadPersistedSchema(store, vaultName, collectionName, dek)\n return persisted?.fieldIds !== undefined ? { fieldIds: persisted.fieldIds } : {}\n}\n\n// ─── buildDescription ─────────────────────────────────────────────────────\n\nexport interface BuildDescriptionInput {\n readonly collection: string\n readonly fieldMeta: Record<string, FieldMeta> | undefined\n /**\n * Kernel-visible collections only carry the opaque {@link ViaDescriptor}\n * marker (the kernel never inspects a Via feature's concrete descriptor\n * shape). Every entry here is actually a {@link MoneyDescriptor} — only\n * `money()` constructs them — narrowed locally below where its\n * mode/currency/scale are read for the describe() output.\n */\n readonly moneyFields: Record<string, ViaDescriptor> | undefined\n readonly dictKeyFields: Record<string, DictKeyDescriptor | StaticDictDescriptor> | undefined\n /** Native lookup()/enumOf()/dict() fields (#650 Task 2) — declared only via `viaFields`/`via()`, no sugar key. */\n readonly lookupFields?: Record<string, LookupDescriptor> | undefined\n readonly computed: ComputedFields | undefined\n readonly refs: Record<string, RefDescriptor>\n /** Async path fills this; sync path passes `undefined`. */\n readonly zodFields: Record<string, ZodFieldSlot> | undefined\n /**\n * The collection's configured validator, if any. The sync path passes it so\n * `fieldMeta` keys can still be validated (#1253): field KEYS are readable\n * synchronously via {@link schemaFieldKeys} even though field TYPES are not.\n * `undefined` means no validator is configured, which is itself informative\n * — the config keys are then the complete field set.\n */\n readonly schema?: unknown\n /**\n * Async path: when `resolveDictLabels` was true, this map holds\n * `{ dictName -> { value -> label } }` for dynamic dictKey fields.\n * Used to populate `dict.values[].label`.\n */\n readonly dictLabels?: Record<string, Record<string, string>> | undefined\n /** Collection-level descriptive metadata. Label falls back to humanized collection name. */\n readonly meta?: CollectionMeta | undefined\n /**\n * Map of field name → I18nTextDescriptor for fields declared with i18nText().\n * When present, describe() surfaces an `i18n` block on matching DescribedField entries.\n */\n readonly i18nFields?: Record<string, I18nTextDescriptor> | undefined\n /** Per-field classified specs (already resolved/flattened). */\n readonly classified?: Record<string, ClassifiedFieldSpec> | undefined\n /** Graph-computed taint overlay (#638 Task 3) — `Collection.via?.taint`. */\n readonly taint?: { readonly postures: ReadonlyMap<string, ViaPosture>; readonly provenance?: ReadonlyMap<string, readonly string[]> } | undefined\n /**\n * Per-binding `describeFragment()` output, keyed by binding brand (#650\n * Task 7 — first-ever consumer of `NoydbVia.describeFragment`,\n * `via/index.ts:136`). `Collection.describe()`/`describeAsync()` build this\n * from `this.via?.describeFragments()`. The `'lookup'` brand's fragment\n * feeds the `lookup` block below; `'blob'`'s feeds the `blob` block\n * (#657, the second consumer). Other brands' fragments ride along unread\n * until they gain a consumer too.\n */\n readonly viaFragments?: Record<string, Record<string, unknown>> | undefined\n /**\n * Persisted-schema `fieldName -> id` map (#946), resolved by the async\n * describe path via {@link resolveDescribeFieldIds}. The sync path passes\n * no `fieldIds` (no store I/O), so every field's `id` is `undefined` there.\n */\n readonly fieldIds?: Record<string, string> | undefined\n}\n\n// Re-export so that callers that want to catch the error don't need another import path.\nexport { FieldMetaUnknownFieldError }\n\n// ─── Widget derivation ────────────────────────────────────────────────────────\n\n/**\n * Derive a widget hint from resolved field metadata.\n * Priority: explicit override (resolvedWidget) > semanticType > dict > type > 'text'.\n */\nfunction deriveWidget(opts: {\n semanticType?: string\n type: string\n dict?: unknown\n /** #650 Task 7 — same 'select' outcome as `dict` (today always co-present for a lookup field via the existing `dict` block; kept as its own check so a future lookup-only field, with no `dict` block, still derives 'select'). */\n lookup?: unknown\n /** #657 — a blobFields-declared field derives the 'file' widget, never the 'text' default (binary content, not a text input). */\n blob?: unknown\n resolvedWidget?: string\n}): string {\n if (opts.resolvedWidget !== undefined) return opts.resolvedWidget\n switch (opts.semanticType) {\n case 'date':\n case 'datetime':\n return 'date'\n case 'currency':\n return 'money'\n case 'entity':\n return 'ref-select'\n case 'url':\n return 'url'\n case 'email':\n return 'email'\n case 'percent':\n return 'number'\n }\n if (opts.dict !== undefined || opts.lookup !== undefined) return 'select'\n if (opts.blob !== undefined) return 'file'\n if (opts.type === 'boolean') return 'checkbox'\n if (opts.type === 'number') return 'number'\n return 'text'\n}\n\n/**\n * Pure assembler: no I/O, no side effects.\n * Builds a {@link CollectionDescription} from the collection's in-memory config.\n *\n * When `zodFields` is supplied (async path), validates that every `fieldMeta` key\n * refers to a known field (config ∪ zodFields). Throws `FieldMetaUnknownFieldError`\n * on the first unknown key — this is the real validation that the vault.ts no-op\n * couldn't do (schema fields weren't knowable synchronously).\n */\nexport function buildDescription(input: BuildDescriptionInput): CollectionDescription {\n const { collection, fieldMeta, moneyFields, dictKeyFields, lookupFields, computed, refs, zodFields, schema, dictLabels, meta, i18nFields, classified, taint, fieldIds } = input\n\n // #650 Task 7 — the 'lookup' binding's describeFragment, keyed per field.\n // Deliberately routed through `viaFragments` rather than reused directly\n // from `lookupFields` above (which only feeds the pre-existing `dict`\n // block, byte-stable for the alias) — this IS the first-ever\n // `describeFragment` consumption the task wires up.\n const lookupFragments = (input.viaFragments?.['lookup'] as LookupDescribeFragment | undefined)?.lookupFields\n\n // #657 — the 'blob' binding's describeFragment, keyed per field (same\n // routing pattern as lookupFragments above). A blobFields-declared field\n // has no other config-map source (unlike money/dict/lookup/i18n/classified,\n // each of which is fed a dedicated map below) — `blobFragments` is BOTH\n // this field's block source AND (via its keys) how it joins `allKeys` at\n // all, since otherwise a blobFields-only field with no fieldMeta entry is\n // invisible in describe() (#657 finding 1).\n const blobFragments = (input.viaFragments?.['blob'] as BlobDescribeFragment | undefined)?.blobFields\n\n // Validate fieldMeta keys against the real known-field set = config keys ∪ the\n // validator's fields. Sound whenever that set can be enumerated COMPLETELY:\n //\n // async path zodFields is non-empty — derived types carry the keys\n // sync path `.shape` was readable — no derivation, no peer dep (#1253)\n //\n // Silent in EVERY other case, and the third one is the instructive one. It is\n // tempting to reason \"no validator configured, therefore the config keys are the\n // whole field set\" — that is FALSE. A collection may be typed by a TypeScript\n // generic alone (`v.collection<Sale>('sales', { moneyFields: … })`), whose fields\n // are real, are present in the data, and are legitimately named by `fieldMeta`,\n // yet appear in NO runtime config. Guarding there rejects correct code.\n //\n // So these are deliberate false NEGATIVES on both counts: an unreadable validator\n // and an absent one. A rule that over-fires teaches people to stop declaring\n // fieldMeta at all, which costs more than the typos it would catch.\n //\n // Before #1253 this ran on the async path alone, so a typo'd key on the sync path\n // became a phantom field carrying its `sensitivity` while the real field went\n // undescribed — see schemaFieldKeys() for why that was thought unavoidable.\n const validatorKeys = zodFields !== undefined && Object.keys(zodFields).length > 0\n ? Object.keys(zodFields)\n : schemaFieldKeys(schema)\n const canEnumerateFields = validatorKeys !== undefined\n if (canEnumerateFields && fieldMeta !== undefined) {\n const knownFields = new Set<string>([\n ...Object.keys(moneyFields ?? {}),\n ...Object.keys(dictKeyFields ?? {}),\n ...Object.keys(refs),\n ...Object.keys(computed ?? {}),\n ...(validatorKeys ?? []),\n ...Object.keys(i18nFields ?? {}),\n ...Object.keys(lookupFields ?? {}),\n ...Object.keys(blobFragments ?? {}),\n ...Object.keys(classified ?? {}),\n ])\n validateFieldMetaKeys(collection, fieldMeta, knownFields)\n }\n\n // Union of all config key sources — stable alphabetical order.\n const allKeys = new Set<string>([\n ...Object.keys(moneyFields ?? {}),\n ...Object.keys(dictKeyFields ?? {}),\n ...Object.keys(lookupFields ?? {}),\n ...Object.keys(refs),\n ...Object.keys(computed ?? {}),\n ...Object.keys(fieldMeta ?? {}),\n ...Object.keys(zodFields ?? {}),\n ...Object.keys(i18nFields ?? {}),\n ...Object.keys(classified ?? {}),\n ...Object.keys(blobFragments ?? {}),\n ])\n\n const fields: DescribedField[] = []\n\n for (const key of [...allKeys].sort()) {\n const zod = zodFields?.[key]\n // Narrow the opaque marker back to the concrete descriptor — see the\n // {@link BuildDescriptionInput.moneyFields} doc comment.\n const money = moneyFields?.[key] as MoneyDescriptor | undefined\n const dict = dictKeyFields?.[key]\n const lookupDesc = lookupFields?.[key]\n const refDesc = refs[key]\n const isComputed = computed !== undefined && key in computed\n const i18nDesc = i18nFields?.[key]\n const cls = classified?.[key]\n const blobFragmentEntry: BlobDescribeFragmentEntry | undefined = blobFragments?.[key]\n const taintPosture = taint?.postures.get(key)\n\n // ── Infer type + structural extras ────────────────────────────────────\n let type = zod?.type ?? 'unknown'\n const inferred: Partial<FieldMeta> = {}\n\n let moneyBlock: DescribedField['money'] | undefined\n let dictBlock: DescribedField['dict'] | undefined\n let refBlock: DescribedField['ref'] | undefined\n let lookupBlock: DescribedField['lookup'] | undefined\n let blobBlock: DescribedField['blob'] | undefined\n\n if (money) {\n type = 'number'\n inferred.semanticType = 'currency'\n inferred.aggregate = 'sum'\n const currency = money.soleCurrency()\n const scale = currency !== undefined ? money.scaleFor(currency) : undefined\n moneyBlock = {\n mode: money.mode,\n ...(currency !== undefined ? { currency } : {}),\n ...(scale !== undefined ? { scale } : {}),\n ...(money.rounding !== undefined ? { rounding: money.rounding } : {}),\n }\n } else if (refDesc) {\n type = refDesc.isArray ? 'array' : 'string'\n inferred.semanticType = 'entity'\n refBlock = {\n target: refDesc.target,\n mode: refDesc.mode,\n ...(refDesc.isArray ? { isArray: true as const } : {}),\n }\n } else if (dict) {\n type = 'enum'\n if (isStaticDictDescriptor(dict)) {\n // Static dict: labels available synchronously from the in-code table.\n const displayLocale = dict.displayLocale\n const values = dict.keys.map((k) => {\n const localeMap = dict.table[k]\n const label = displayLocale !== undefined\n ? (localeMap?.[displayLocale] ?? undefined)\n : undefined\n return label !== undefined\n ? { value: k, label }\n : { value: k }\n })\n dictBlock = { name: dict.name, static: true, values }\n } else {\n // Dynamic dictKey: keys declared in config; labels optionally resolved\n // from vault.dictionary(name).list() when resolveDictLabels was requested.\n const labelMap = dictLabels?.[dict.name]\n const labelMapHasEntries = labelMap !== undefined && Object.keys(labelMap).length > 0\n if (labelMapHasEntries) {\n // We have resolved labels — build values from the label map.\n const values = Object.entries(labelMap).map(([value, label]) => ({ value, label }))\n dictBlock = { name: dict.name, static: false, values }\n } else if (dict.keys !== undefined) {\n const values = dict.keys.map((k) => {\n const label = dict.labels?.[k]\n return label !== undefined ? { value: k, label } : { value: k }\n })\n dictBlock = { name: dict.name, static: false, values }\n } else {\n dictBlock = { name: dict.name, static: false }\n }\n }\n } else if (lookupDesc) {\n // Native lookup()/enumOf()/dict() field (#650 Task 2) — the SAME `dict`\n // block shape as above, for byte-parity with the dictKey()/staticDict()\n // alias. A table-bearing descriptor ('static' backing, the lookup(static)\n // form staticDict() compiles onto) resolves synchronously like a static\n // dict; a reserved-tier dict() resolves via `dictLabels` exactly like a\n // dynamic dictKey (review fix — was previously falling to the\n // declared-keys-only fallback below, breaking async describe parity);\n // everything else (collection/bare enum) falls to that fallback.\n type = 'enum'\n const lookupLabelMap = dictLabels?.[lookupDesc.dimension]\n const lookupLabelMapHasEntries = lookupLabelMap !== undefined && Object.keys(lookupLabelMap).length > 0\n if (lookupDesc.table !== undefined) {\n const displayLocale = lookupDesc.displayLocale\n const table = lookupDesc.table\n const values = (lookupDesc.keys ?? Object.keys(table)).map((k) => {\n const localeMap = table[k]\n const label = displayLocale !== undefined\n ? (localeMap?.[displayLocale] ?? undefined)\n : undefined\n return label !== undefined ? { value: k, label } : { value: k }\n })\n dictBlock = { name: lookupDesc.dimension, static: true, values }\n } else if (lookupLabelMapHasEntries) {\n const values = Object.entries(lookupLabelMap).map(([value, label]) => ({ value, label }))\n dictBlock = { name: lookupDesc.dimension, static: false, values }\n } else if (lookupDesc.keys !== undefined) {\n const values = lookupDesc.keys.map((k) => {\n const label = lookupDesc.labels?.[k]\n return label !== undefined ? { value: k, label } : { value: k }\n })\n dictBlock = { name: lookupDesc.dimension, static: false, values }\n } else {\n dictBlock = { name: lookupDesc.dimension, static: false }\n }\n } else if (i18nDesc) {\n // i18nText field: the stored value is a locale-map object, but the resolved\n // type exposed to consumers is 'string' (locale resolution collapses to a string).\n type = 'string'\n } else if (isComputed) {\n // type already initialized to zod?.type ?? 'unknown' above; no re-set needed\n } else if (blobFragmentEntry !== undefined) {\n // #657 finding 1 — a blobFields-only field (no schema/money/dict/\n // lookup/i18n config) was previously invisible; with a fieldMeta\n // entry it fell through to the 'unknown'/'text'/editable:true default,\n // actively wrong for binary content. `type` is a plain `string` on\n // DescribedField (not a closed union), so 'blob' is not a breaking\n // union extension.\n type = 'blob'\n blobBlock = { ...blobFragmentEntry, queryable: 'none' }\n }\n\n // ── lookup block (#650 Task 7 — first-ever NoydbVia.describeFragment\n // consumer) ── Sourced from `lookupFragments` (the binding's fragment),\n // NOT from `lookupDesc` above (which only feeds the pre-existing `dict`\n // block, byte-stable for the alias) — routing through the fragment is\n // the point: `backing`/`vocabulary`/`key`/`onDelete` have no other\n // source in this function, so their presence here is itself proof the\n // describeFragment seam (declared via/index.ts:136, zero consumers before\n // this task) carries data end to end from binding to describe() output.\n const lookupFragmentEntry: LookupDescribeFragmentEntry | undefined = lookupFragments?.[key]\n if (lookupFragmentEntry !== undefined) {\n lookupBlock = {\n ...(lookupFragmentEntry.dimension !== undefined ? { dimension: lookupFragmentEntry.dimension } : {}),\n backing: lookupFragmentEntry.backing,\n vocabulary: lookupFragmentEntry.vocabulary,\n key: lookupFragmentEntry.key,\n onDelete: lookupFragmentEntry.onDelete,\n ...(lookupFragmentEntry.altKeys !== undefined ? { altKeys: lookupFragmentEntry.altKeys } : {}),\n ...(lookupFragmentEntry.present !== undefined ? { present: lookupFragmentEntry.present } : {}),\n ...(lookupFragmentEntry.sortBy !== undefined ? { sortBy: lookupFragmentEntry.sortBy } : {}),\n ...(lookupFragmentEntry.keys !== undefined ? { keys: lookupFragmentEntry.keys } : {}),\n }\n }\n\n // Classified sensitivity feeds inferred meta at lowest precedence — channel\n // fieldMeta and zod .meta() still win via resolveFieldMeta's merge order.\n if (cls !== undefined) inferred.sensitivity = cls.sensitivity\n\n // ── Merge fieldMeta channel ────────────────────────────────────────────\n const channelEntry = fieldMeta?.[key]\n const zodMeta = zod?.meta\n const resolved = resolveFieldMeta(key, {\n ...(channelEntry !== undefined ? { channel: channelEntry } : {}),\n ...(zodMeta !== undefined ? { zodMeta } : {}),\n inferred,\n })\n\n // ── i18n block (only for i18nText fields) ─────────────────────────────\n let i18nBlock: DescribedField['i18n'] | undefined\n if (i18nDesc !== undefined) {\n const locales = i18nDesc.options.languages\n const densify = i18nDesc.options.densifyOnWrite\n i18nBlock = {\n ...(locales !== undefined ? { locales } : {}),\n ...(densify !== undefined ? { densify } : {}),\n }\n }\n\n // ── Widget (derived, overridable via resolvedWidget from fieldMeta/zodMeta) ──\n const widget = deriveWidget({\n type,\n ...(resolved.semanticType !== undefined ? { semanticType: resolved.semanticType } : {}),\n ...(dictBlock !== undefined ? { dict: dictBlock } : {}),\n ...(lookupBlock !== undefined ? { lookup: lookupBlock } : {}),\n ...(blobBlock !== undefined ? { blob: blobBlock } : {}),\n ...(resolved.widget !== undefined ? { resolvedWidget: resolved.widget } : {}),\n })\n\n // ── Editable: false for computed, id, provenance-stamped, blob fields ──\n // Provenance fields (_source, _sourceTs) are envelope-level metadata, not\n // user schema fields — they won't appear as keys in fieldMeta so this check\n // is implicitly handled (they'd never appear in allKeys). Explicitly guard\n // computed + 'id' as the two structural non-editable cases. A blobFields\n // field (#657) is never written through the record codec — it's mutated\n // exclusively via `collection.blob(id)` — so it is never editable either.\n const editable = !isComputed && key !== 'id' && blobBlock === undefined\n\n // ── Assemble the field (exactOptionalPropertyTypes-safe spreads) ───────\n const field: DescribedField = {\n key,\n ...(fieldIds?.[key] !== undefined ? { id: fieldIds[key] } : {}),\n type,\n optional: zod?.optional ?? false,\n ...(zod?.constraints !== undefined ? { constraints: zod.constraints } : {}),\n label: resolved.label,\n ...(resolved.description !== undefined ? { description: resolved.description } : {}),\n ...(resolved.group !== undefined ? { group: resolved.group } : {}),\n ...(resolved.order !== undefined ? { order: resolved.order } : {}),\n ...(resolved.semanticType !== undefined ? { semanticType: resolved.semanticType } : {}),\n ...(resolved.unit !== undefined ? { unit: resolved.unit } : {}),\n ...(resolved.sensitivity !== undefined ? { sensitivity: resolved.sensitivity } : {}),\n ...(resolved.aggregate !== undefined ? { aggregate: resolved.aggregate } : {}),\n ...(resolved.aliases !== undefined ? { aliases: resolved.aliases } : {}),\n ...(resolved.displayFor !== undefined ? { displayFor: resolved.displayFor } : {}),\n ...(refBlock !== undefined ? { ref: refBlock } : {}),\n ...(moneyBlock !== undefined ? { money: moneyBlock } : {}),\n ...(dictBlock !== undefined ? { dict: dictBlock } : {}),\n ...(lookupBlock !== undefined ? { lookup: lookupBlock } : {}),\n ...(blobBlock !== undefined ? { blob: blobBlock } : {}),\n ...(isComputed ? { computed: true as const } : {}),\n ...(i18nBlock !== undefined ? { i18n: i18nBlock } : {}),\n widget,\n editable,\n ...(cls !== undefined ? {\n classified: {\n preset: cls.preset,\n storage: cls.storage,\n list: cls.list.kind === 'omit' ? 'omit' as const\n : cls.list.kind === 'mask' ? { mask: cls.list.pattern }\n : { rider: cls.list.rider },\n ...(cls.equatable === true ? { equatable: true as const } : {}),\n },\n } : {}),\n ...(taintPosture !== undefined ? { taint: { posture: taintPosture, forcedBy: taint?.provenance?.get(key) ?? [] } } : {}),\n }\n\n fields.push(field)\n }\n\n // Build collection-level meta with label fallback to humanized collection name.\n const collectionMeta: CollectionMeta = {\n ...meta,\n label: meta?.label ?? humanizeFieldKey(collection),\n }\n\n return {\n collection,\n fields,\n meta: collectionMeta,\n }\n}\n","// kernel/via/graph.ts — the per-vault ViaGraph dependency model (Via port phase C, #638).\n//\n// Metadata-only dependency graph over (collection, field) nodes: source-field\n// postures, derived-field edges, and the taint (effective-posture) algebra.\n// NEVER stores record values or key material — see\n// design-history/2026-07-11-via-phase-c-design.md §1/§2.\n\nimport { DerivationCycleError, MaterializedViewCycleError } from '../errors.js'\nimport type { ViaPosture } from './index.js'\n\n/** A (collection, field) node. Artifact-grain targets (rollup field, MV row-class,\n * overlay output) are modelled as a field node whose `field` is the artifact key. */\nexport interface FieldRef { readonly collection: string; readonly field: string }\n\nexport type EdgeKind = 'computed' | 'derivation' | 'rollup' | 'mv' | 'overlay' | 'ref'\n/** `'virtual'` (#638 Task 7) marks a `computed(fn, { mode: 'virtual' })` field's edge —\n * never stored (rides the `present` phase), so it can never be sealed at rest\n * ({@link ViaGraph.taintSealedFields} excludes it) and is always non-queryable\n * regardless of source posture ({@link ViaGraph.effectivePosture} clamps it). */\nexport type Grain = 'record' | 'aggregate' | 'virtual'\n\n/** Delete/forget-time referential policy for a `'ref'` edge (#650 Task 5, spec §4) — duplicated\n * (not imported) from `via/lookup/descriptor.ts`'s `OnDelete`: the kernel spine may not\n * statically import `via/**` (Check 14, `via-layering`). Keep the two in sync by hand. */\nexport type OnDelete = 'restrict' | 'cascade' | 'nullify'\n\n/** Plain (non-via) field baseline — max-permissive; taint only ever tightens. */\nexport const DEFAULT_POSTURE: ViaPosture =\n { encryptedAtRest: 'envelope', queryable: 'full', exportable: true, forgettable: false }\n\nconst QUERYABLE_RANK: Record<ViaPosture['queryable'], number> = {\n none: 0,\n 'det-exact': 1,\n ordered: 2,\n full: 3,\n}\n\n/** The per-axis \"most restrictive\" fold — pure, exported for direct unit testing. */\nexport function foldPosture(a: ViaPosture, b: ViaPosture): ViaPosture {\n return {\n encryptedAtRest: a.encryptedAtRest === 'sealed' || b.encryptedAtRest === 'sealed' ? 'sealed' : 'envelope',\n queryable: QUERYABLE_RANK[a.queryable] <= QUERYABLE_RANK[b.queryable] ? a.queryable : b.queryable,\n exportable: a.exportable && b.exportable,\n forgettable: a.forgettable || b.forgettable,\n }\n}\n\n/** Security-axes-only fold for a wildcard collection node (#642): sealed-wins encryptedAtRest,\n * AND exportable, OR forgettable — queryable is NOT folded (stays base.queryable; the sealed\n * clamp to 'none' is buildTaintOverlay's job, so inheriting `sealed` never over-restricts a\n * blob-adjacent output to unqueryable). Pure; exported for unit testing. Distinct from\n * {@link foldPosture} (which folds all four axes) — do NOT reuse foldPosture here. */\nexport function foldWildcardSecurity(base: ViaPosture, contributor: ViaPosture): ViaPosture {\n return {\n encryptedAtRest: base.encryptedAtRest === 'sealed' || contributor.encryptedAtRest === 'sealed' ? 'sealed' : 'envelope',\n queryable: base.queryable,\n exportable: base.exportable && contributor.exportable,\n forgettable: base.forgettable || contributor.forgettable,\n }\n}\n\n// the folded formula kinds a '*' source contributes its collection-fold to (ref keeps identity):\ntype FoldedKind = 'derivation' | 'rollup' | 'mv' | 'overlay'\nconst FOLDED_KINDS: ReadonlySet<EdgeKind> = new Set<FoldedKind>(['derivation', 'rollup', 'mv', 'overlay'])\n\n/** Whether `p` is exactly the plain, non-taint baseline (Task 3 — `taintProvenance`). */\nfunction isDefaultPosture(p: ViaPosture): boolean {\n return p.encryptedAtRest === DEFAULT_POSTURE.encryptedAtRest && p.queryable === DEFAULT_POSTURE.queryable &&\n p.exportable === DEFAULT_POSTURE.exportable && p.forgettable === DEFAULT_POSTURE.forgettable\n}\n\n/** One `_out` entry — a `source -> target` derived edge, carrying its OWN registration's\n * `kind` (#678). `kind` must be edge-local, not re-derived from `_in`: `_in` is single-slot\n * per target and can be overwritten by a LATER `registerDerived` call on the SAME target\n * (a dual-role target, e.g. #631's exempt {computed, lookup} field composition) — asking\n * `_in` for \"this target's current kind\" answers the wrong question for a specific edge. */\ninterface OutEdge { readonly target: FieldRef; readonly kind: EdgeKind }\n\n/** One registered `registerDerived` call — a target's whole in-edge set. */\ninterface DerivedEdge {\n readonly target: FieldRef\n readonly sources: readonly FieldRef[]\n readonly kind: EdgeKind\n readonly grain: Grain\n /** `'ref'` edges only — the referencing field's delete/forget policy (#650 Task 5). */\n readonly onDelete?: OnDelete\n /** `'ref'` edges only — the backing dimension's canonical-key FIELD NAME on its own row (matrix\n * tier's `lookup(dim, {key})`; always `'id'` for reserved/static tiers). Defaults to `'id'`\n * when absent — a referencing field always stores this field's VALUE, never the backing row's\n * PUT-id when the two differ (#650 Task 5, mirrors Task 3's membership review fix). */\n readonly keyField?: string\n}\n\nconst SEP = '\\0'\nconst EMPTY_SET: ReadonlySet<string> = new Set()\n\nfunction nodeId(ref: FieldRef): string {\n return `${ref.collection}${SEP}${ref.field}`\n}\n\n/** Inverse of `nodeId`, for building a human-readable cycle path. */\nfunction displayNodeId(id: string): string {\n const sep = id.indexOf(SEP)\n return `${id.slice(0, sep)}.${id.slice(sep + 1)}`\n}\n\n/** Metadata-only dependency graph, ONE per vault. Never stores values or key material. */\nexport class ViaGraph {\n /** Declared source-field postures (registerField), keyed by node id. */\n private readonly _posture = new Map<string, ViaPosture>()\n /** Every derived target's registration, keyed by the target's node id. */\n private readonly _in = new Map<string, DerivedEdge>()\n /** source node id -> derived edges that depend on it (dispatch/erasure), each carrying\n * its own registration's `kind` (#678 — see {@link OutEdge}). */\n private readonly _out = new Map<string, OutEdge[]>()\n /** Memoized effective posture per derived target node id. */\n private readonly _effectiveCache = new Map<string, ViaPosture>()\n /** Memoized whole-collection security-axes fold for `'*'` wildcard LEAF nodes (#642),\n * keyed by collection name — see {@link _wildcardContribution}. Cleared alongside\n * `_effectiveCache` on every `registerField`/`registerDerived` (a later-registered\n * field must re-fold on the next read — registration ordering is free). */\n private readonly _wildcardCache = new Map<string, ViaPosture>()\n /** Collections with at least one classified field (#638 Task 2 fix wave 2,\n * Finding I1 — the reconcile path's combined-state leak guard memory). */\n private readonly _classifiedCollections = new Set<string>()\n /** Computed field names declared with no `deps` entry, per collection\n * (Finding I1 — such a field registers no edge when no classified field is\n * present yet, so a LATER, separate reconcile call attaching classifiedFields\n * still needs to see it regardless of declaration order). */\n private readonly _depslessComputed = new Map<string, Set<string>>()\n\n /** Declare a source field's posture (money/i18n/classified/plain). Plain fields\n * default to `DEFAULT_POSTURE`; a later declaration for the same node wins-first (idempotent). */\n registerField(collection: string, field: string, posture: ViaPosture): void {\n const id = nodeId({ collection, field })\n if (this._posture.has(id)) return\n this._posture.set(id, posture)\n this._effectiveCache.clear()\n this._wildcardCache.clear()\n }\n\n /** A derived target depends on `sources` (may be cross-collection). `kind`/`grain`\n * drive dispatch + erasure semantics; sources drive taint. Re-registering the same\n * target replaces `_in` but does not prune stale `_out` edges — callers must\n * register each target at most once per graph lifetime. `onDelete`/`keyField` (#650 Task 5)\n * are meaningful only for `kind === 'ref'` edges — {@link referencingEdgesOf} reads them back. */\n registerDerived(target: FieldRef, sources: readonly FieldRef[], kind: EdgeKind, grain: Grain, onDelete?: OnDelete, keyField?: string): void {\n const id = nodeId(target)\n this._in.set(id, {\n target, sources, kind, grain,\n ...(onDelete !== undefined ? { onDelete } : {}),\n ...(keyField !== undefined ? { keyField } : {}),\n })\n for (const source of sources) {\n const sourceId = nodeId(source)\n const outEdge: OutEdge = { target, kind }\n const dependents = this._out.get(sourceId)\n if (dependents) dependents.push(outEdge)\n else this._out.set(sourceId, [outEdge])\n }\n this._effectiveCache.clear()\n this._wildcardCache.clear()\n }\n\n /** Whether `target` already has a registered in-edge — lets a caller skip\n * re-registering the same target (#638 Task 2 fix wave 2, Finding I2i:\n * `registerDerived`'s at-most-once contract must hold across repeated\n * identical `vault.collection()` calls, not just within a single one). */\n hasDerived(target: FieldRef): boolean {\n return this._in.has(nodeId(target))\n }\n\n /** Mark/query a collection as having declared at least one classified field. */\n markClassified(collection: string): void {\n this._classifiedCollections.add(collection)\n }\n\n isClassified(collection: string): boolean {\n return this._classifiedCollections.has(collection)\n }\n\n /** Mark/query a collection's depsless (no declared `deps`) computed\n * field names — see `_depslessComputed`'s doc comment above. */\n markDepslessComputed(collection: string, field: string): void {\n let set = this._depslessComputed.get(collection)\n if (!set) { set = new Set(); this._depslessComputed.set(collection, set) }\n set.add(field)\n }\n\n depslessComputedFields(collection: string): ReadonlySet<string> {\n return this._depslessComputed.get(collection) ?? EMPTY_SET\n }\n\n /** Every field name the graph already has memory of for `collection` — from an\n * EARLIER, separate `vault.collection()` call (registered postures, derived\n * targets, depsless-computed names) — regardless of which via feature declared\n * it. #645 — `via/graph-wiring.ts`'s reconcile-path `knownFields` universe\n * (`collectKnownFieldNames`) is scoped to THIS call's own options only, so a\n * computed field attached in a LATER call whose `deps` correctly names a field\n * declared in an EARLIER call was spuriously refused as \"unknown\"; this method\n * lets that call site union in the graph's cross-call memory. Excludes the `'*'`\n * wildcard target (an overlay/derivation whole-record fold node, never a real\n * record field — see {@link registerDerived}'s doc comment). */\n knownFieldNames(collection: string): ReadonlySet<string> {\n const out = new Set<string>()\n const prefix = `${collection}${SEP}`\n for (const id of this._posture.keys()) {\n if (id.startsWith(prefix)) out.add(id.slice(prefix.length))\n }\n for (const edge of this._in.values()) {\n if (edge.target.collection === collection && edge.target.field !== '*') out.add(edge.target.field)\n }\n const depsless = this._depslessComputed.get(collection)\n if (depsless) for (const field of depsless) out.add(field)\n return out\n }\n\n /** Reject cycles at declare time (vault open). Throws `DerivationCycleError` for a\n * derivation/rollup/computed cycle, `MaterializedViewCycleError` for an MV cycle —\n * same classes + message shape the registries throw today (behavior lock). */\n assertAcyclic(): void {\n const visited = new Set<string>()\n const stack: string[] = []\n\n /** #639 — containment expansion: writing a real field `f` on collection `C` is\n * a write to `C`, so it must ALSO reach every whole-record (`'*'`) dependent of\n * `C` — the missing reachability step that made mutual/rotating rollup cycles\n * invisible (a rollup target is always a real field node and never itself a\n * graph SOURCE, so the old `_out.get(id)`-only walk dead-ended on it).\n *\n * TRAVERSAL-LOCAL ONLY (law, #642): this is a virtual adjacency computed\n * during the DFS walk, reading `_out` only. It must NEVER be materialized via\n * `registerDerived` (no new `(C,f)→(C,'*')` edge) and must NEVER touch `_in` —\n * putting `(C,'*')` into `_in` would flip `_contribution('C\\0*')` from the\n * `_wildcardContribution` fold (`#642`) onto the `_computeEffective` path,\n * bleeding cycle-reachability taint into `foldWildcardSecurity`'s posture\n * fold. Posture folding (`_contribution`/`_computeEffective`/\n * `_wildcardContribution`) never reads `_out`, so an expansion that reads\n * `_out` only is provably unable to perturb it. */\n // #671 item 5 — exclude `kind:'ref'` consuming edges: mutual FK lookups (two\n // collections each referencing the other) are legal and must not be treated as a\n // derivation cycle. Ref edges exist for cascade/rename machinery\n // (`referencingEdgesOf`/delete-time restrict/cascade/nullify), never derivation\n // ordering, so they carry no ordering constraint here. #678 — `kind` is read off\n // THIS `_out` entry (edge-local), NOT re-derefed from `_in`: a dual-role target\n // (e.g. #631's exempt {computed, lookup} composition) can have its `_in` entry's\n // `kind` overwritten by a LATER `registerDerived` call for the SAME target, so\n // asking `_in` \"what kind is `t` registered as NOW\" wrongly excluded a real\n // computed edge from the DFS as if it were a ref edge, hiding a genuine\n // derivation cycle. Asking \"what kind is THIS specific edge\" is correct\n // regardless of what else was later registered for the target.\n const notRefEdge = (entry: OutEdge): boolean => entry.kind !== 'ref'\n const neighboursOf = (id: string): readonly FieldRef[] => {\n const own = (this._out.get(id) ?? []).filter(notRefEdge).map((entry) => entry.target)\n const sep = id.indexOf(SEP)\n if (id.slice(sep + 1) === '*') return own\n const wildcard = (this._out.get(`${id.slice(0, sep)}${SEP}*`) ?? []).filter(notRefEdge).map((entry) => entry.target)\n if (wildcard.length === 0) return own\n return [...own, ...wildcard]\n }\n\n const visit = (id: string): void => {\n const idx = stack.indexOf(id)\n if (idx !== -1) {\n const cycle = stack.slice(idx).concat(id)\n const isMv = cycle.some(cycleId => this._in.get(cycleId)?.kind === 'mv')\n const path = cycle.map(displayNodeId)\n if (isMv) throw new MaterializedViewCycleError(path)\n throw new DerivationCycleError(path)\n }\n if (visited.has(id)) return\n stack.push(id)\n for (const dependent of neighboursOf(id)) visit(nodeId(dependent))\n stack.pop()\n visited.add(id)\n }\n\n for (const id of this._out.keys()) visit(id)\n }\n\n /** A leaf (non-derived) node's own posture contribution: its declared posture,\n * or `DEFAULT_POSTURE` if never declared via `registerField`. */\n private _declaredPosture(id: string): ViaPosture {\n return this._posture.get(id) ?? DEFAULT_POSTURE\n }\n\n /** A node's posture contribution when folded into a dependent: recurse if it is itself\n * derived; else its declared/default posture — UNLESS it is a `'*'` LEAF node consumed\n * by a folded formula kind (#642, `derivation|rollup|mv|overlay`), in which case it\n * contributes its collection's whole-record security fold ({@link _wildcardContribution}).\n * `kind` is the CONSUMING edge's kind, threaded from {@link _computeEffective}. `'ref'`\n * edges (and the provenance-only untyped call, `kind` left `undefined`) keep `'*'` =\n * identity — the phase-D lookup reliance (`via/lookup/registry.ts:392-397`) that a\n * referencing field must not seal just because its dimension collection has a classified\n * column. */\n private _contribution(id: string, kind?: EdgeKind): ViaPosture {\n const edge = this._in.get(id)\n if (edge) return this._computeEffective(id, edge)\n if (kind !== undefined && FOLDED_KINDS.has(kind) && id.endsWith(`${SEP}*`)) {\n return this._wildcardContribution(id.slice(0, -2))\n }\n return this._declaredPosture(id)\n }\n\n /** Lazy fold (#642) of a collection's REGISTERED field postures on the security axes only\n * ({@link foldWildcardSecurity} — sealed-wins encryptedAtRest, AND exportable, OR\n * forgettable; queryable stays at DEFAULT_POSTURE's 'full', never folded), seeded at\n * DEFAULT_POSTURE. This is the collection-level posture a `'*'` LEAF node contributes to a\n * folded-kind formula edge (derivation/rollup/mv/overlay) — see {@link _contribution}. A\n * plain (unregistered) field contributes nothing (the identity), so the fold is strictly\n * more conservative than deps-based taint and never hits the KNOWN-LIMIT wall (it names no\n * fields — seam map §1d). Memoized per collection in `_wildcardCache`. */\n private _wildcardContribution(collection: string): ViaPosture {\n const cached = this._wildcardCache.get(collection)\n if (cached) return cached\n let result = DEFAULT_POSTURE\n const prefix = `${collection}${SEP}`\n for (const [id, posture] of this._posture) {\n if (!id.startsWith(prefix) || id === `${prefix}*`) continue\n result = foldWildcardSecurity(result, posture)\n }\n this._wildcardCache.set(collection, result)\n return result\n }\n\n private _computeEffective(id: string, edge: DerivedEdge): ViaPosture {\n const cached = this._effectiveCache.get(id)\n if (cached) return cached\n let result = DEFAULT_POSTURE\n for (const source of edge.sources) {\n result = foldPosture(result, this._contribution(nodeId(source), edge.kind))\n }\n // #638 Task 7 — a virtual field is computed fresh on every read and never\n // stored, so it is structurally unqueryable regardless of what its\n // sources' fold would otherwise permit (e.g. a money-sourced virtual\n // field must NOT inherit money's 'ordered' queryability — there is no\n // stored/indexed form to query against). Every OTHER axis (exportable/\n // forgettable/encryptedAtRest) still folds normally — the taint rule is\n // identical to a materialized field; only queryability is a fixed,\n // grain-level property, not a source-derived one.\n if (edge.grain === 'virtual' && result.queryable !== 'none') {\n result = { ...result, queryable: 'none' }\n }\n this._effectiveCache.set(id, result)\n return result\n }\n\n /** Strictest source posture on every axis, per §2. `undefined` when `target` has no\n * in-edges (not a derived field). Transitive: folds through chained derivations. */\n effectivePosture(target: FieldRef): ViaPosture | undefined {\n const id = nodeId(target)\n const edge = this._in.get(id)\n if (!edge) return undefined\n return this._computeEffective(id, edge)\n }\n\n /** Per-collection { field → effectivePosture } overlay the pipeline consumes (Task 3). */\n taintedPostures(collection: string): ReadonlyMap<string, ViaPosture> {\n const out = new Map<string, ViaPosture>()\n for (const edge of this._in.values()) {\n if (edge.target.collection !== collection) continue\n out.set(edge.target.field, this._computeEffective(nodeId(edge.target), edge))\n }\n return out\n }\n\n /** Materialized (`grain !== 'virtual'`) derived fields on `collection` whose effective\n * encryptedAtRest resolves to 'sealed' — the taint-seal set (Task 3). #638 Task 7\n * makes the `grain !== 'virtual'` filter meaningful: a `computed(fn, { mode: 'virtual' })`\n * field is never stored (rides the `present` phase, seam map Part 4's money-Formatted/\n * i18n-Label precedent), so it is EXCLUDED here even when its effective `encryptedAtRest`\n * folds to `'sealed'` — there is no envelope slot to seal. It still surfaces in\n * {@link taintedPostures} (query refusal via `postureFor`'s `queryable` clamp above, and\n * export refusal via `exportable`) — only the AT-REST SEALING ACTION is skipped. */\n taintSealedFields(collection: string): ReadonlySet<string> {\n const out = new Set<string>()\n for (const edge of this._in.values()) {\n if (edge.target.collection !== collection || edge.grain === 'virtual') continue\n const posture = this._computeEffective(nodeId(edge.target), edge)\n if (posture.encryptedAtRest === 'sealed') out.add(edge.target.field)\n }\n return out\n }\n\n /** Fields on `collection` whose registered edge is `grain === 'virtual'` (#638 Task 7) —\n * `via/graph-wiring.ts#applyTaintOverlay` intersects this with `exportable === false`\n * postures to know which virtual fields need PRESENT-TIME (not just export-time)\n * redaction, since a virtual field's value is only ever materialized inside `present()`. */\n virtualFields(collection: string): ReadonlySet<string> {\n const out = new Set<string>()\n for (const edge of this._in.values()) {\n if (edge.target.collection === collection && edge.grain === 'virtual') out.add(edge.target.field)\n }\n return out\n }\n\n /** Per-collection { field → immediate source field names that forced its\n * effective posture away from `DEFAULT_POSTURE` } — `describe()`'s\n * provenance (Task 3). Only the DIRECT declared sources are named (not the\n * ultimate origin several hops up a transitive chain); a source absent\n * from the result contributed nothing restrictive. */\n taintProvenance(collection: string): ReadonlyMap<string, readonly string[]> {\n const out = new Map<string, readonly string[]>()\n for (const edge of this._in.values()) {\n if (edge.target.collection !== collection) continue\n const forcedBy = edge.sources\n .filter((source) => !isDefaultPosture(this._contribution(nodeId(source))))\n .map((source) => source.field)\n if (forcedBy.length > 0) out.set(edge.target.field, forcedBy)\n }\n return out\n }\n\n private _targetsDependingOn(collection: string): ReadonlyArray<{ readonly target: FieldRef; readonly kind: EdgeKind; readonly grain: Grain }> {\n const out: Array<{ target: FieldRef; kind: EdgeKind; grain: Grain }> = []\n for (const edge of this._in.values()) {\n if (edge.sources.some(source => source.collection === collection)) {\n out.push({ target: edge.target, kind: edge.kind, grain: edge.grain })\n }\n }\n return out\n }\n\n /** Dispatch (Task 4): every derived target triggered by a write to `collection`. Excludes\n * `'ref'` edges (#650 Task 5 review, folded Minor) — a `'ref'` edge is consulted only by the\n * delete/forget-time restrict/cascade/nullify path ({@link referencingEdgesOf}), never by the\n * sync/cutover/restore dispatch wave (`runGraphDispatchWave`); counting it here defeated that\n * wave's zero-cost early-continue, costing every write to a referenced backing collection an\n * unconditional decrypt + two no-op dispatch passes. {@link derivedArtifactsOf} (erasure\n * fanout) still includes `'ref'` edges — the forget path genuinely needs them. */\n dependentsOf(collection: string): ReadonlyArray<{ readonly target: FieldRef; readonly kind: EdgeKind; readonly grain: Grain }> {\n return this._targetsDependingOn(collection).filter((edge) => edge.kind !== 'ref')\n }\n\n /** Erasure (Task 6): derived artifacts of a forgotten record whose source is `collection`. */\n derivedArtifactsOf(collection: string): ReadonlyArray<{ readonly target: FieldRef; readonly kind: EdgeKind; readonly grain: Grain }> {\n return this._targetsDependingOn(collection)\n }\n\n /** Referencing edges pointing AT a backing dimension (delete/forget-time restrict/cascade/\n * nullify, #650 Task 5) — an O(1) reverse lookup via the existing `_out` map (keyed at the\n * dimension's wildcard `field:'*'` node, the same convention every whole-collection source\n * already uses), NEVER a scan across collections or records. `backing` is the collection name\n * a lookup field's edge was registered against (a reserved dimension's `_dict_<name>`/\n * `_lookup_<name>` collection name, or a matrix dimension's own collection name). */\n referencingEdgesOf(backing: string): ReadonlyArray<{ readonly referencing: FieldRef; readonly onDelete: OnDelete; readonly keyField: string }> {\n const targets = this._out.get(nodeId({ collection: backing, field: '*' }))\n if (!targets) return []\n const out: Array<{ referencing: FieldRef; onDelete: OnDelete; keyField: string }> = []\n for (const entry of targets) {\n // #678 — `kind` is read directly off THIS `_out` entry (edge-local) instead of\n // re-derefing `_in`. This also fixes the symmetric ref-vanishes hazard: under a\n // registration order where a LATER `registerDerived` call for the same target\n // overwrites `_in`'s kind away from `'ref'`, the old `_in`-derefing check would\n // silently drop a genuine referencing edge from cascade/nullify delete machinery\n // even though this specific edge was truly registered as `'ref'`.\n if (entry.kind !== 'ref') continue\n const edge = this._in.get(nodeId(entry.target))\n if (edge?.onDelete !== undefined) {\n out.push({ referencing: entry.target, onDelete: edge.onDelete, keyField: edge.keyField ?? 'id' })\n }\n }\n return out\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgDO,IAAM,6BAAN,cAAyC,MAAM;AAAA,EACpD,YAA4B,YAAoC,KAAa;AAC3E,UAAM,6BAA6B,UAAU,+BAA+B,GAAG,mEACX;AAF1C;AAAoC;AAG9D,SAAK,OAAO;AAAA,EACd;AAAA,EAJ4B;AAAA,EAAoC;AAKlE;AAGO,SAAS,sBACd,YACA,WACA,aACM;AACN,aAAW,OAAO,OAAO,KAAK,SAAS,GAAG;AACxC,QAAI,CAAC,YAAY,IAAI,GAAG,EAAG,OAAM,IAAI,2BAA2B,YAAY,GAAG;AAAA,EACjF;AACF;AAUO,SAAS,iBAAiB,KAAqB;AACpD,SAAO,IACJ,QAAQ,UAAU,GAAG,EACrB,QAAQ,sBAAsB,OAAO,EACrC,KAAK,EACL,MAAM,KAAK,EACX,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY,IAAI,EAAE,MAAM,CAAC,CAAC,EACjD,KAAK,GAAG;AACb;AAGO,SAAS,iBAAiB,KAAa,QAAmC;AAC/E,QAAM,EAAE,SAAS,SAAS,SAAS,IAAI;AACvC,QAAM,OAAO,CAA4B,MACvC,UAAU,CAAC,KAAK,UAAU,CAAC,KAAK,WAAW,CAAC;AAC9C,QAAM,cAAc,KAAK,aAAa;AACtC,QAAM,eAAe,KAAK,cA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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,mBAAmB,SAA4H;AAC7I,UAAM,UAAU,KAAK,KAAK,IAAI,OAAO,EAAE,YAAY,SAAS,OAAO,IAAI,CAAC,CAAC;AACzE,QAAI,CAAC,QAAS,QAAO,CAAC;AACtB,UAAM,MAA8E,CAAC;AACrF,eAAW,SAAS,SAAS;AAO3B,UAAI,MAAM,SAAS,MAAO;AAC1B,YAAM,OAAO,KAAK,IAAI,IAAI,OAAO,MAAM,MAAM,CAAC;AAC9C,UAAI,MAAM,aAAa,QAAW;AAChC,YAAI,KAAK,EAAE,aAAa,MAAM,QAAQ,UAAU,KAAK,UAAU,UAAU,KAAK,YAAY,KAAK,CAAC;AAAA,MAClG;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/with-formula/derivations/strategy-hash.ts","../src/with-formula/derivations/registry.ts"],"sourcesContent":["/**\n * Deterministic hash of a derivation strategy's \"shape\": source\n * collection, declared sibling sources, output keys, derive function\n * source. Used to detect\n * strategy drift: a record whose `_derivedFrom.strategyHash` doesn't\n * match the current strategy is considered stale.\n *\n * Web Crypto SHA-256 — no extra deps.\n */\nimport { sha256Hex } from '../../kernel/enclave/index.js'\n\nexport async function computeStrategyHash(\n source: string,\n outputKeys: readonly string[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n derive: (...args: any[]) => any,\n sources?: ReadonlyArray<string>,\n): Promise<string> {\n const canonical = JSON.stringify({\n source,\n outputs: [...outputKeys].sort(),\n derive: derive.toString(),\n // Declared sibling sources — adding/removing a trigger\n // collection invalidates cached derived records. Omitted when empty\n // so strategies without siblings keep their existing hash.\n ...(sources?.length ? { sources: [...sources].sort() } : {}),\n })\n const bytes = new TextEncoder().encode(canonical)\n return sha256Hex(bytes)\n}\n","import { DerivationCycleError, DuplicateBehaviorNameError, ValidationError } from '../../kernel/errors.js'\nimport { ViaGraph, type FieldRef, type EdgeKind, type Grain } from '../../kernel/via/graph.js'\nimport { schemaFieldKeys } from '../../with-shape/introspection/describe.js'\nimport { computeStrategyHash } from './strategy-hash.js'\nimport { normalizeTriggerBy, type NormalizedTrigger } from './trigger-match.js'\nimport type { DerivationSpec } from './types.js'\n\n/**\n * Whole-record artifact-grain field marker (#638 Task 2). A derivation's\n * `derive()`/a rollup's `compute()` reads the WHOLE source record — there is\n * no single declared field to point at — so a trigger/output collection is\n * modelled as one artifact node per collection (`kernel/via/graph.ts`'s\n * \"Artifact-grain targets... modelled as a field node whose field is the\n * artifact key\" convention). MUST match `materialized-views/registry.ts`'s\n * and `vault.ts`'s overlay-edge marker so cross-registry edges (a derivation\n * feeding into / out of an MV or overlay collection) resolve to the SAME\n * graph node.\n */\nconst WHOLE_RECORD = '*'\n\n/** Strip this registry's `.${WHOLE_RECORD}` artifact suffix off a graph cycle\n * path entry, recovering the bare collection name — preserves the exact\n * pre-#638 `DerivationCycleError` message shape (behavior lock) for a pure\n * record-shape derivation cycle. A rollup's real-field target (not suffixed\n * `.${WHOLE_RECORD}`) is left untouched. */\nfunction stripArtifactSuffix(displayId: string): string {\n const suffix = `.${WHOLE_RECORD}`\n return displayId.endsWith(suffix) ? displayId.slice(0, -suffix.length) : displayId\n}\n\ninterface RegisteredStrategy {\n // Type-erased to allow the registry to hold heterogeneous strategies.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n spec: DerivationSpec<any, any>\n strategyHash: string\n readonly triggers: ReadonlyArray<NormalizedTrigger>\n}\n\n/**\n * Vault-internal registry of derivation strategies. Owned by `Vault`;\n * not exported.\n *\n * @internal\n */\nexport class DerivationRegistry {\n private readonly _bySource = new Map<string, RegisteredStrategy[]>()\n private readonly _byOutput = new Map<string, RegisteredStrategy[]>()\n private readonly _byName = new Map<string, RegisteredStrategy>()\n\n /**\n * Register a derivation strategy. If `spec.name` is given and already\n * registered by another derivation in this vault, throws\n * {@link DuplicateBehaviorNameError} before indexing.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async register(spec: DerivationSpec<any, any>): Promise<void> {\n if (spec.name !== undefined && this._byName.has(spec.name)) {\n throw new DuplicateBehaviorNameError(spec.name, 'derivation')\n }\n\n const outputKeys = Object.keys(spec.outputs)\n const strategyHash = await computeStrategyHash(spec.source, outputKeys, spec.derive, spec.sources)\n const triggers = normalizeTriggerBy(spec.triggerBy)\n const reg: RegisteredStrategy = { spec, strategyHash, triggers }\n\n if (spec.name !== undefined) this._byName.set(spec.name, reg)\n\n const fromSource = this._bySource.get(spec.source)\n if (fromSource) fromSource.push(reg)\n else this._bySource.set(spec.source, [reg])\n\n // Declared sibling sources index the SAME `reg` under each\n // extra collection so `strategiesForSource(extra)` returns it and a\n // sibling write re-fires the derivation. Sibling keys also enter\n // `_bySource`, so `validate()`'s cycle DFS walks them automatically.\n for (const extra of spec.sources ?? []) {\n const fromExtra = this._bySource.get(extra)\n if (fromExtra) fromExtra.push(reg)\n else this._bySource.set(extra, [reg])\n }\n\n // FK triggers index the SAME `reg` under each parent collection so\n // a parent write re-fires the derivation (fanned out to matching source\n // records in `dispatchDerivations`). Like sources[], these keys enter\n // `_bySource` so the cycle DFS walks the trigger→output edge.\n for (const t of triggers) {\n const fromTrigger = this._bySource.get(t.collection)\n if (fromTrigger) fromTrigger.push(reg)\n else this._bySource.set(t.collection, [reg])\n }\n\n // Rollup: a write to the child `from` collection recomputes\n // the parent (= spec.source = into) at id child[key]. Index under `from`\n // so a child write fires it; spec.source (into) is already indexed above,\n // so a parent write also recomputes its own aggregate (covers the\n // parent-created-after-children case). The from→into edge enters the cycle\n // DFS automatically.\n if (spec.rollup) {\n const fromRollup = this._bySource.get(spec.rollup.from)\n if (fromRollup) fromRollup.push(reg)\n else this._bySource.set(spec.rollup.from, [reg])\n }\n\n for (const key of outputKeys) {\n const output = spec.outputs[key]\n if (!output) continue\n const outputCollection = output.collection\n const arr = this._byOutput.get(outputCollection)\n if (arr) arr.push(reg)\n else this._byOutput.set(outputCollection, [reg])\n }\n }\n\n strategiesForSource(source: string): ReadonlyArray<RegisteredStrategy> {\n return this._bySource.get(source) ?? []\n }\n\n strategiesProducingOutput(collection: string): ReadonlyArray<RegisteredStrategy> {\n return this._byOutput.get(collection) ?? []\n }\n\n /**\n * The #1253-pattern typo guard for match fields (#1249): a misspelt\n * `to`/`from` silently matches nothing forever, so validate against the\n * collection's enumerable field set at the earliest point it exists.\n * `schemaFieldKeys(schema) === undefined` (TS-generic collection,\n * unreadable validator) is DELIBERATELY silent — those fields are real\n * and unenumerable. `configKeys` folds in the collection's other\n * non-schema field declarations (fieldMeta/moneyFields/dictKeyFields/\n * refs/computed); `denormExempt` is derived here from this registry's\n * own strategies rather than taken as a parameter — a field this\n * collection's own derivations write via `denorm` is never a typo.\n */\n validateFieldsFor(collectionName: string, schema: unknown, configKeys: ReadonlyArray<string>): void {\n const shapeKeys = schemaFieldKeys(schema)\n if (shapeKeys === undefined) return\n const keys = new Set([...shapeKeys, ...configKeys])\n const denormExempt = new Set<string>()\n for (const reg of new Set([...this._bySource.values()].flat())) {\n if (reg.spec.source !== collectionName) continue\n for (const out of Object.values(reg.spec.outputs) as Array<{ collection?: string; denorm?: readonly string[] }>) {\n if (out.collection === collectionName) for (const d of out.denorm ?? []) denormExempt.add(d)\n }\n }\n const regs = new Set([...this._bySource.values()].flat())\n for (const reg of regs) {\n for (const t of reg.triggers) {\n if (reg.spec.source === collectionName) {\n for (const p of t.match) {\n if (!keys.has(p.to) && !denormExempt.has(p.to)) {\n throw new ValidationError(\n `derivation \"${reg.spec.name ?? reg.spec.source}\": triggerBy match names source field \"${p.to}\", which \"${collectionName}\" does not declare — a typo here silently matches nothing forever`)\n }\n }\n }\n if (t.collection === collectionName) {\n for (const p of t.match) {\n if (p.from !== 'id' && !keys.has(p.from) && !denormExempt.has(p.from)) {\n throw new ValidationError(\n `derivation \"${reg.spec.name ?? reg.spec.source}\": triggerBy match reads \"${p.from}\" from written \"${collectionName}\" records, which that collection does not declare — a typo here silently matches nothing forever`)\n }\n }\n }\n }\n }\n }\n\n /**\n * All registered strategies as a flat, deduplicated array.\n * Each strategy is indexed once per source (not once per output key),\n * so iterating `_bySource.values()` naturally yields each strategy\n * exactly once per source — deduplication is handled by flattening\n * the per-source arrays and collecting into a Set by identity.\n *\n * Used by `dumpSchema()` / `describeDerivations()` in the introspection\n * walker to populate the derivations map.\n */\n all(): ReadonlyArray<RegisteredStrategy> {\n const seen = new Set<RegisteredStrategy>()\n for (const strategies of this._bySource.values()) {\n for (const s of strategies) seen.add(s)\n }\n return [...seen]\n }\n\n /**\n * Graph edges for #638 Task 2: one `'derivation'`/`'record'` edge per\n * (non-self-write) output key — target = the output collection (a\n * `WHOLE_RECORD` artifact node), sources = every collection that can\n * trigger this strategy (`source`, `sources[]`, `triggerBy[].collection`,\n * and — for a rollup — `rollup.from`), mirroring EXACTLY the trigger keys\n * `register()` indexes under `_bySource`. The self-write reverse-denorm\n * output (`output.collection === source` with `denorm` declared) is\n * skipped — the SAME condition the old local DFS used; it is not a cycle\n * (see the comment `validate()` used to carry, now on this skip).\n * Rollups ADDITIONALLY get a dedicated `'rollup'`/`'aggregate'` edge\n * targeting the real `rollup.field` on the parent (`source`) — the\n * self-write output above only covers the cycle-DFS skip, not\n * dispatch/taint (Tasks 3/4/6), which need the real field.\n */\n edges(): ReadonlyArray<{ readonly target: FieldRef; readonly sources: readonly FieldRef[]; readonly kind: EdgeKind; readonly grain: Grain }> {\n const out: Array<{ target: FieldRef; sources: FieldRef[]; kind: EdgeKind; grain: Grain }> = []\n for (const reg of this.all()) {\n const spec = reg.spec\n const triggerCollections = [\n spec.source,\n ...(spec.sources ?? []),\n ...(spec.triggerBy ?? []).map((t) => t.collection),\n ...(spec.rollup ? [spec.rollup.from] : []),\n ]\n const sources: FieldRef[] = triggerCollections.map((c) => ({ collection: c, field: WHOLE_RECORD }))\n for (const key of Object.keys(spec.outputs)) {\n const output = spec.outputs[key]\n if (!output) continue\n if (output.shape === 'record' && output.collection === spec.source && output.denorm !== undefined) continue\n out.push({ target: { collection: output.collection, field: WHOLE_RECORD }, sources, kind: 'derivation', grain: 'record' })\n }\n if (spec.rollup) {\n out.push({\n target: { collection: spec.source, field: spec.rollup.field },\n sources: [{ collection: spec.rollup.from, field: WHOLE_RECORD }],\n kind: 'rollup',\n grain: 'aggregate',\n })\n }\n }\n return out\n }\n\n /**\n * Cycle detection, delegated to `ViaGraph.assertAcyclic()` (#638 Task 2 —\n * retires the local DFS). Call after all `register()` calls complete (i.e.\n * at vault open). Throws `DerivationCycleError` on the first cycle found —\n * SAME class/timing as before; the message/path is byte-identical to the\n * pre-#638 shape for a pure record-shape derivation cycle (the\n * `WHOLE_RECORD` artifact suffix is stripped back to a bare collection\n * name before re-throwing).\n *\n * `graph` is the caller's shared per-vault graph, ALREADY carrying this\n * registry's `edges()` (the caller registers them — see `Vault._initDerivations`)\n * — omit it (e.g. this registry's own unit tests) to validate this\n * registry's edges in isolation against a throwaway graph.\n */\n validate(graph?: ViaGraph): void {\n const g = graph ?? new ViaGraph()\n if (!graph) {\n for (const edge of this.edges()) g.registerDerived(edge.target, edge.sources, edge.kind, edge.grain)\n }\n try {\n g.assertAcyclic()\n } catch (e) {\n if (e instanceof DerivationCycleError) throw new DerivationCycleError(e.path.map(stripArtifactSuffix))\n throw e\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAWA,eAAsB,oBACpB,QACA,YAEA,QACA,SACiB;AACjB,QAAM,YAAY,KAAK,UAAU;AAAA,IAC/B;AAAA,IACA,SAAS,CAAC,GAAG,UAAU,EAAE,KAAK;AAAA,IAC9B,QAAQ,OAAO,SAAS;AAAA;AAAA;AAAA;AAAA,IAIxB,GAAI,SAAS,SAAS,EAAE,SAAS,CAAC,GAAG,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC;AAAA,EAC5D,CAAC;AACD,QAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,SAAS;AAChD,SAAO,UAAU,KAAK;AACxB;;;ACXA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I;AACF,QAAE,cAAc;AAAA,IAClB,SAAS,GAAG;AACV,UAAI,aAAa,qBAAsB,OAAM,IAAI,qBAAqB,EAAE,KAAK,IAAI,mBAAmB,CAAC;AACrG,YAAM;AAAA,IACR;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/with-formula/derivations/stale.ts"],"sourcesContent":["import type { Collection } from '../../kernel/collection.js'\nimport type { DerivationExecutor as DerivationExecutorType } from './executor.js'\nimport type { ReadOnlyVaultFacade } from '../../with-audit/guards/types.js'\nimport type { TxContext } from '../../with-commit/tx/transaction.js'\nimport type { DerivationRegistry } from './registry.js'\n// Type-only — runtime class loaded via dynamic import in\n// `resolveStaleOnRead` only when a stale flag actually fires. Keeps\n// the executor chunk out of the floor bundle.\nimport type { DerivationSpec } from './types.js'\n\nimport { lazy } from '../../kernel/lazy.js'\n\n/** #846c — one memoized binding instead of a cast at the call site. */\nconst loadDerivationExecutor = lazy(() => import('./executor.js'))\n\n/**\n * Accessor shape passed through from the owning Vault. Provides the\n * registry (used to look up strategies and as the WeakMap key) and a\n * resolver from collection name to the live `Collection` instance.\n * Same shape as `Collection.derivationSource` so callers can pass it\n * through directly.\n */\nexport interface DerivationStaleAccessor {\n registry(): DerivationRegistry\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getCollection(name: string): Collection<any>\n /**\n * Read-only vault facade handed to `derive(source, ctx)` on the lazy\n * resolve-on-read path. Same instance/shape as the eager path uses.\n */\n getReadOnlyFacade(): ReadOnlyVaultFacade\n /**\n * Active multi-record TxContext or `null`. The lazy resolve-on-read\n * path uses this to register tombstone deletes on `_executed` so a\n * later rollback restores the prior emission. Mirrors the eager\n * path's rollback tracking; the lazy `put` was historically\n * unregistered but the tombstone delete (a NEW write path)\n * matches the eager registration for symmetry.\n */\n getActiveTxContext(): TxContext | null\n}\n\n/**\n * In-memory stale map keyed by `DerivationRegistry` instance (stable\n * per vault). Maps `${source}/${sourceId}` → set of pending strategies.\n *\n * Persistence across vault close is NOT implemented in v1 (concern\n * flagged in the dim14 spec). On vault re-open, derived records'\n * `_derivedFrom.strategyHash` will still match the registered\n * strategies' hash, so an unset stale flag is interpreted as \"fresh.\"\n * `vault.deriveAll()` (Task D13) is the explicit recompute escape\n * hatch.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst _staleByRegistry = new WeakMap<DerivationRegistry, Map<string, Set<DerivationSpec<any, any>>>>()\n\nconst keyFor = (source: string, sourceId: string): string => `${source}/${sourceId}`\n\n/** Mark every output of (strategy, sourceId) as stale. */\nexport async function markStale(\n registry: DerivationRegistry,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n strategy: DerivationSpec<any, any>,\n sourceId: string,\n): Promise<void> {\n let map = _staleByRegistry.get(registry)\n if (!map) {\n map = new Map()\n _staleByRegistry.set(registry, map)\n }\n const k = keyFor(strategy.source, sourceId)\n let set = map.get(k)\n if (!set) {\n set = new Set()\n map.set(k, set)\n }\n set.add(strategy)\n}\n\n/**\n * Called from `Collection.get` on lazy-mode output collections. If the\n * id has a pending stale flag for any strategy producing this output\n * collection, re-derive before returning the record. No-op when there\n * is no pending work — keeps the read fast path negligible.\n */\nexport async function resolveStaleOnRead(\n accessor: DerivationStaleAccessor,\n outputCollection: string,\n id: string,\n): Promise<void> {\n const registry = accessor.registry()\n const producers = registry.strategiesProducingOutput(outputCollection)\n if (producers.length === 0) return\n\n const map = _staleByRegistry.get(registry)\n if (!map) return\n\n // Dynamic-import the executor only when at least one stale flag\n // actually fires. Vaults with no derivation strategies never call\n // this function (gated on `derivationSource` in `Collection.get`);\n // vaults with strategies but no pending stale ids reach the\n // `pending.has(spec)` short-circuit below without ever touching\n // the executor chunk.\n let DerivationExecutor: typeof DerivationExecutorType | null = null\n\n for (const { spec, strategyHash } of producers) {\n const k = keyFor(spec.source, id)\n const pending = map.get(k)\n if (!pending || !pending.has(spec)) continue\n\n // Consume the pending flag BEFORE the source read, not after: for a\n // self-write output (output.collection === spec.source, e.g. a\n // reverse-denorm patch), `sourceColl.get(id)` below re-enters this\n // same collection/id and would otherwise still see this spec pending\n // — infinite recursion. Restored on a strict failure below so a\n // future read still retries.\n pending.delete(spec)\n\n // Everything from here on can throw (source read, executor, output\n // put/delete) — restore the consumed flag on ANY throw so a later\n // read still retries, not just on the strict-failure branch below\n // (which throws through this same catch, so it does not also\n // re-add — `Set.add` is idempotent, but the branch no longer needs\n // its own restore).\n try {\n // Read the source record from the source collection and re-derive.\n // We use the same getCollection accessor that eager dispatch uses\n // — it returns the live `Collection<any>` instance with full\n // crypto / keyring wiring.\n const sourceColl = accessor.getCollection(spec.source)\n const source = await sourceColl.get(id)\n if (!source) {\n continue\n }\n const sourceWithId = { ...(source as Record<string, unknown>), id } as Record<string, unknown> & { id: string }\n // sourceVersion: not tracked in v1 stale map; pass 0 — matches the\n // forthcoming v0 semantics, `_derivedFrom.sourceVersion` is\n // informational, not load-bearing for correctness.\n DerivationExecutor ??= (await loadDerivationExecutor()).DerivationExecutor\n const ctx = { vault: accessor.getReadOnlyFacade() }\n const result = await DerivationExecutor.run(spec, sourceWithId, 0, strategyHash, ctx)\n for (const key of Object.keys(spec.outputs)) {\n const out = result.outputs[key]\n if (!out) continue\n if (out.kind === 'failed') {\n const err = out.error\n if (spec.strict) throw err\n console.warn(\n `[derivation] lazy output \"${key}\" for source \"${spec.source}\" id=\"${id}\" failed:`,\n err,\n )\n continue\n }\n if (out.kind === 'array') {\n // Defensive — array-shape requires `lifecycle: 'eager'`\n // (validated at withDerivation registration).\n // Reaching the lazy-resolve path for array-shape would mean\n // a registration check was bypassed. Log and skip.\n console.warn(\n `[derivation] unexpected array-shape output \"${key}\" in lazy resolve path; `\n + 'array-shape derivations require lifecycle: \"eager\".',\n )\n continue\n }\n const outSpec = spec.outputs[key]\n if (!outSpec) continue\n const outputColl = accessor.getCollection(outSpec.collection)\n if (out.skipped === true) {\n // Optional output skipped on lazy resolve — delete any\n // prior emission so the read returns null (matches eager-path\n // tombstone semantics). Routed through `_internalDelete` so a\n // user-registered `onDelete` on the output collection\n // does NOT fire. The active TxContext (if any) is forwarded:\n // `resolveStaleOnRead` is reachable from `Collection.get()`\n // which can be called from inside a transaction, so the\n // tombstone must be observable to `revertExecuted` on\n // rollback.\n await outputColl._internalDelete(id, accessor.getActiveTxContext())\n continue\n }\n await outputColl.put(id, out.value)\n }\n pending.delete(spec)\n } catch (e) {\n // Restore the stale flag consumed above so a future read retries.\n pending.add(spec)\n throw e\n }\n }\n}\n"],"mappings":";;;;;AAaA,IAAM,yBAAyB,KAAK,MAAM,OAAO,wBAAe,CAAC;AA2CjE,IAAM,mBAAmB,oBAAI,QAAwE;AAErG,IAAM,SAAS,CAAC,QAAgB,aAA6B,GAAG,MAAM,IAAI,QAAQ;AAGlF,eAAsB,UACpB,UAEA,UACA,UACe;AACf,MAAI,MAAM,iBAAiB,IAAI,QAAQ;AACvC,MAAI,CAAC,KAAK;AACR,UAAM,oBAAI,IAAI;AACd,qBAAiB,IAAI,UAAU,GAAG;AAAA,EACpC;AACA,QAAM,IAAI,OAAO,SAAS,QAAQ,QAAQ;AAC1C,MAAI,MAAM,IAAI,IAAI,CAAC;AACnB,MAAI,CAAC,KAAK;AACR,UAAM,oBAAI,IAAI;AACd,QAAI,IAAI,GAAG,GAAG;AAAA,EAChB;AACA,MAAI,IAAI,QAAQ;AAClB;AAQA,eAAsB,mBACpB,UACA,kBACA,IACe;AACf,QAAM,WAAW,SAAS,SAAS;AACnC,QAAM,YAAY,SAAS,0BAA0B,gBAAgB;AACrE,MAAI,UAAU,WAAW,EAAG;AAE5B,QAAM,MAAM,iBAAiB,IAAI,QAAQ;AACzC,MAAI,CAAC,IAAK;AAQV,MAAI,qBAA2D;AAE/D,aAAW,EAAE,MAAM,aAAa,KAAK,WAAW;AAC9C,UAAM,IAAI,OAAO,KAAK,QAAQ,EAAE;AAChC,UAAM,UAAU,IAAI,IAAI,CAAC;AACzB,QAAI,CAAC,WAA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../src/kernel/cache/lru.ts","../src/kernel/cache/policy.ts","../src/port/with/lazy-strategy.ts"],"sourcesContent":["/**\n * Generic LRU cache for `Collection`'s lazy hydration mode.\n *\n * Backed by a JavaScript `Map`, which preserves insertion order. Promotion\n * is implemented as `delete()` + `set()` — O(1) on `Map` since both\n * operations are constant-time. Eviction walks the iterator from the front\n * (least recently used) until both budgets are satisfied.\n *\n * ships in-memory only. The cache is never persisted; on collection\n * close every entry is dropped. Persisting cache state is a follow-up\n * once the access patterns from real consumers tell us whether it would\n * pay back the complexity.\n */\n\nexport interface LruEntry<V> {\n /** The cached value. */\n readonly value: V\n /**\n * Approximate decrypted byte size of the entry. Used by the byte-budget\n * eviction path. Callers compute this once at insert time and pass it\n * in — recomputing on every access would dominate the per-record cost.\n */\n readonly size: number\n}\n\nexport interface LruOptions {\n /** Maximum number of entries before eviction. Required if `maxBytes` is unset. */\n maxRecords?: number\n /** Maximum total bytes before eviction. Computed from per-entry `size`. */\n maxBytes?: number\n}\n\nexport interface LruStats {\n /** Total cache hits since construction (or `resetStats()`). */\n hits: number\n /** Total cache misses since construction (or `resetStats()`). */\n misses: number\n /** Total entries evicted since construction (or `resetStats()`). */\n evictions: number\n /** Current number of cached entries. */\n size: number\n /** Current sum of cached entry sizes (in bytes, approximate). */\n bytes: number\n}\n\n/**\n * O(1) LRU cache. Both `get()` and `set()` promote the touched entry to\n * the most-recently-used end. Eviction happens after every insert and\n * walks the front of the Map iterator dropping entries until both\n * budgets are satisfied.\n */\nexport class Lru<K, V> {\n private readonly entries = new Map<K, LruEntry<V>>()\n private readonly maxRecords: number | undefined\n private readonly maxBytes: number | undefined\n private currentBytes = 0\n private hits = 0\n private misses = 0\n private evictions = 0\n\n constructor(options: LruOptions) {\n if (options.maxRecords === undefined && options.maxBytes === undefined) {\n throw new Error('Lru: must specify maxRecords, maxBytes, or both')\n }\n this.maxRecords = options.maxRecords\n this.maxBytes = options.maxBytes\n }\n\n /**\n * Look up a key. Hits promote the entry to most-recently-used; misses\n * return undefined. Both update the running stats counters.\n */\n get(key: K): V | undefined {\n const entry = this.entries.get(key)\n if (!entry) {\n this.misses++\n return undefined\n }\n // Promote: re-insert moves the entry to the end of the iteration order.\n this.entries.delete(key)\n this.entries.set(key, entry)\n this.hits++\n return entry.value\n }\n\n /**\n * Insert or update a key. If the key already exists, its size is\n * accounted for and the entry is promoted to MRU. After insertion,\n * eviction runs to maintain both budgets.\n */\n set(key: K, value: V, size: number): void {\n const existing = this.entries.get(key)\n if (existing) {\n // Update path: subtract the old size before adding the new one.\n this.currentBytes -= existing.size\n this.entries.delete(key)\n }\n this.entries.set(key, { value, size })\n this.currentBytes += size\n this.evictUntilUnderBudget()\n }\n\n /**\n * Remove a key without affecting hit/miss stats. Used by `Collection.delete()`.\n * Returns true if the key was present.\n */\n remove(key: K): boolean {\n const existing = this.entries.get(key)\n if (!existing) return false\n this.currentBytes -= existing.size\n this.entries.delete(key)\n return true\n }\n\n /** True if the cache currently holds an entry for the given key. */\n has(key: K): boolean {\n return this.entries.has(key)\n }\n\n /**\n * Drop every entry. Stats counters survive — call `resetStats()` if you\n * want a clean slate. Used by `Collection.invalidate()` on key rotation.\n */\n clear(): void {\n this.entries.clear()\n this.currentBytes = 0\n }\n\n /** Reset hit/miss/eviction counters to zero. Does NOT touch entries. */\n resetStats(): void {\n this.hits = 0\n this.misses = 0\n this.evictions = 0\n }\n\n /** Snapshot of current cache statistics. Cheap — no copying. */\n stats(): LruStats {\n return {\n hits: this.hits,\n misses: this.misses,\n evictions: this.evictions,\n size: this.entries.size,\n bytes: this.currentBytes,\n }\n }\n\n /**\n * Iterate over all currently-cached values. Order is least-recently-used\n * first. Used by tests and devtools — production callers should use\n * `Collection.scan()` instead.\n */\n *values(): IterableIterator<V> {\n for (const entry of this.entries.values()) yield entry.value\n }\n\n /**\n * Walk the cache from the LRU end and drop entries until both budgets\n * are satisfied. Called after every `set()`. Single pass — entries are\n * never re-promoted during eviction.\n */\n private evictUntilUnderBudget(): void {\n while (this.overBudget()) {\n const oldest = this.entries.keys().next()\n if (oldest.done) return // empty cache; nothing more to evict\n const key = oldest.value\n const entry = this.entries.get(key)\n if (entry) this.currentBytes -= entry.size\n this.entries.delete(key)\n this.evictions++\n }\n }\n\n private overBudget(): boolean {\n if (this.maxRecords !== undefined && this.entries.size > this.maxRecords) return true\n if (this.maxBytes !== undefined && this.currentBytes > this.maxBytes) return true\n return false\n }\n}\n","/**\n * Cache policy helpers — parse human-friendly byte budgets into raw numbers.\n *\n * Accepted shapes (case-insensitive on suffix):\n * number — interpreted as raw bytes\n * '1024' — string of digits, raw bytes\n * '50KB' — kilobytes (×1024)\n * '50MB' — megabytes (×1024²)\n * '1GB' — gigabytes (×1024³)\n *\n * Decimals are accepted (`'1.5GB'` → 1610612736 bytes).\n *\n * Anything else throws — better to fail loud at construction time than\n * to silently treat a typo as 0 bytes (which would evict everything).\n */\n\nconst UNITS: Record<string, number> = {\n '': 1,\n 'B': 1,\n 'KB': 1024,\n 'MB': 1024 * 1024,\n 'GB': 1024 * 1024 * 1024,\n // 'TB' deliberately not supported — if you need it, you're not using NOYDB.\n}\n\n/** Parse a byte budget into a positive integer number of bytes. */\nexport function parseBytes(input: number | string): number {\n if (typeof input === 'number') {\n if (!Number.isFinite(input) || input <= 0) {\n throw new Error(`parseBytes: numeric input must be a positive finite number, got ${String(input)}`)\n }\n return Math.floor(input)\n }\n\n const trimmed = input.trim()\n if (trimmed === '') {\n throw new Error('parseBytes: empty string is not a valid byte budget')\n }\n\n // Accept either a bare number or a number followed by a unit suffix.\n // Regex: optional sign, digits with optional decimal, optional unit.\n const match = /^([0-9]+(?:\\.[0-9]+)?)\\s*([A-Za-z]*)$/.exec(trimmed)\n if (!match) {\n throw new Error(`parseBytes: invalid byte budget \"${input}\". Expected format: \"1024\", \"50KB\", \"50MB\", \"1GB\"`)\n }\n\n const value = parseFloat(match[1]!)\n const unit = (match[2] ?? '').toUpperCase()\n\n if (!(unit in UNITS)) {\n throw new Error(`parseBytes: unknown unit \"${match[2]}\" in \"${input}\". Supported: B, KB, MB, GB`)\n }\n\n const bytes = Math.floor(value * UNITS[unit]!)\n if (bytes <= 0) {\n throw new Error(`parseBytes: byte budget must be > 0, got ${bytes} from \"${input}\"`)\n }\n return bytes\n}\n\n/**\n * Estimate the in-memory byte size of a decrypted record.\n *\n * Uses `JSON.stringify().length` as a stand-in for actual heap usage.\n * It's a deliberate approximation: real V8 heap size includes pointer\n * overhead, hidden classes, and string interning that we can't measure\n * from JavaScript. The JSON length is a stable, monotonic proxy that\n * costs O(record size) per insert — fine when records are typically\n * < 1 KB and the cache eviction is the slow path anyway.\n *\n * Returns `0` (and the caller must treat it as 1 for accounting) if\n * stringification throws on circular references; this is documented\n * but in practice records always come from JSON-decoded envelopes.\n */\nexport function estimateRecordBytes(record: unknown): number {\n try {\n return JSON.stringify(record).length\n } catch {\n return 0\n }\n}\n","/**\n * Lazy-mode capability contract (#267 Track A tail — lazy-mode promoted out\n * of `routing` into its own `lazy` service). Lives on the `/with` port (the\n * one seam the kernel spine may import statically) so `Collection` can hold\n * the back-compat default without a spine→service static import.\n *\n * Lazy mode (`prefetch: false`) skips bulk hydration: reads go per-id\n * against the store and land in a bounded LRU working set. The strategy owns\n * constructing that LRU:\n *\n * - `withLazy()` (`with-store/lazy/active.ts`, subpath `@noy-db/hub/lazy`)\n * is the explicit catalog opt-in — silent, forward-stable.\n * - {@link IMPLICIT_LAZY} is the floor default reached when a collection\n * declares `prefetch: false` WITHOUT `lazyStrategy: withLazy()`. It keeps\n * the pre-#267 behavior byte-for-byte (back-compat delegation, pre-1.0)\n * but emits a one-time deprecation warn outside test env. It will become\n * a throwing stub at 1.0, letting the LRU leave the floor bundle\n * entirely once the per-record-CEK cache stops pinning `Lru` there.\n *\n * The on-demand read/write branches themselves stay kernel-resident (they\n * are `if (this.lazy)` forks on the hot get/put/scan paths); the service\n * seam owns cache construction + budget validation, which is where the\n * opt-in and the future tree-shake win live.\n * @internal\n */\nimport { Lru, parseBytes } from '../../kernel/cache/index.js'\nimport type { CacheOptions } from '../../kernel/collection.js'\n\nexport interface LazyStrategy {\n /**\n * Build the bounded LRU working-set cache for a lazy collection.\n * MUST throw when `cache` declares neither `maxRecords` nor `maxBytes` —\n * an unbounded lazy cache defeats the purpose.\n */\n createCache<V>(collection: string, cache: CacheOptions | undefined): Lru<string, V>\n}\n\n/**\n * Shared budget validation + LRU construction — the one implementation both\n * {@link IMPLICIT_LAZY} and `withLazy()` run, so the two paths cannot drift.\n * @internal\n */\nexport function buildLazyCache<V>(collection: string, cache: CacheOptions | undefined): Lru<string, V> {\n if (!cache || (cache.maxRecords === undefined && cache.maxBytes === undefined)) {\n throw new Error(\n `Collection \"${collection}\": lazy mode (prefetch: false) requires a cache option ` +\n `with maxRecords and/or maxBytes. An unbounded lazy cache defeats the purpose.`,\n )\n }\n const lruOptions: { maxRecords?: number; maxBytes?: number } = {}\n if (cache.maxRecords !== undefined) lruOptions.maxRecords = cache.maxRecords\n if (cache.maxBytes !== undefined) lruOptions.maxBytes = parseBytes(cache.maxBytes)\n return new Lru<string, V>(lruOptions)\n}\n\nlet implicitLazyWarned = false\n\n/**\n * Back-compat default (deprecated): `prefetch: false` without\n * `lazyStrategy: withLazy()`. Identical behavior to the explicit opt-in,\n * plus a one-time deprecation warn (suppressed under NODE_ENV=test,\n * mirroring the listPage fallback warn). @internal\n */\nexport const IMPLICIT_LAZY: LazyStrategy = {\n createCache<V>(collection: string, cache: CacheOptions | undefined): Lru<string, V> {\n if (!implicitLazyWarned) {\n implicitLazyWarned = true\n if (!(typeof process !== 'undefined' && process.env['NODE_ENV'] === 'test')) {\n console.warn(\n `[noy-db] Collection \"${collection}\": lazy mode (prefetch: false) without the lazy ` +\n `service is deprecated — pass \\`lazyStrategy: withLazy()\\` (from \"@noy-db/hub/lazy\") ` +\n `to createNoydb(). The implicit path will be removed at 1.0.`,\n )\n }\n }\n return buildLazyCache<V>(collection, cache)\n },\n}\n"],"mappings":";AAmDO,IAAM,MAAN,MAAgB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;AACrB,UAAI,EAAE,OAAO,YAAY,eAAe,QAAQ,IAAI,UAAU,MAAM,SAAS;AAC3E,gBAAQ;AAAA,UACN,wBAAwB,UAAU;AAAA,QAGpC;AAAA,MACF;AAAA,IACF;AACA,WAAO,eAAkB,YAAY,KAAK;AAAA,EAC5C;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/via/lookup/registry.ts","../src/via/lookup/snapshot.ts","../src/port/with/lookup-strategy.ts","../src/kernel/via/dispatch.ts"],"sourcesContent":["/**\n * Pure dict-registry helpers — extracted from `kernel/vault.ts`'s dict\n * bodies (#650 Task 1 — via-lookup extraction, phase D).\n *\n * These take the vault-resident registry Maps (and a couple of vault-bound\n * callbacks) as ARGUMENTS instead of closing over `this` — no `Vault`\n * import here, so this module stays a plain, testable function library.\n * `kernel/vault.ts` keeps the registry Maps themselves (they're populated\n * by `vault.collection()` and read by the backup path) and calls these\n * helpers through the `port/with/lookup-strategy.ts` seam.\n */\n\nimport { getAtPath } from '../../kernel/paths.js'\nimport { UnknownDictCodeError, ValidationError } from '../../kernel/errors.js'\nimport type { JoinableSource } from '../../kernel/query/index.js'\nimport type { FieldRef, ViaGraph } from '../../kernel/via/graph.js'\nimport type { StaticDictDescriptor } from '../../port/with/i18n-strategy.js'\nimport { dictCollectionName, type LookupHandle } from './handle.js'\nimport type { LookupDescriptor, OnDelete } from './descriptor.js'\n\n/**\n * Validate staticDict codes on a `put()`. For each `staticDict()` field,\n * every stored code must be a declared key of the descriptor's table, else\n * `UnknownDictCodeError`. Opt out per descriptor with `{ validateCodes:\n * false }`. Supports scalar, dotted, and `[].`-wildcard field paths via\n * `getAtPath` (same path support as i18n validation).\n *\n * `staticFields` is the collection's `field → StaticDictDescriptor` map\n * (`Vault#staticDescriptorByField.get(collectionName)`) — `undefined`/empty\n * is a no-op.\n */\nexport function enforceStaticDictOnPut(\n staticFields: Record<string, StaticDictDescriptor> | undefined,\n record: unknown,\n): void {\n if (!staticFields || Object.keys(staticFields).length === 0) return\n if (!record || typeof record !== 'object') return\n\n const obj = record as Record<string, unknown>\n for (const [field, desc] of Object.entries(staticFields)) {\n if (desc.validateCodes === false) continue\n const known = new Set<string>(desc.keys)\n const values = getAtPath(obj, field)\n for (const value of values) {\n if (value === undefined || value === null) continue\n const codes = Array.isArray(value) ? value : [value]\n for (const code of codes) {\n if (typeof code !== 'string') continue\n if (!known.has(code)) {\n throw new UnknownDictCodeError(desc.name, field, code)\n }\n }\n }\n }\n}\n\n/**\n * Build a `JoinableSource` for a dictKey field, for use in dict joins.\n * Returns a source whose snapshot contains `{ key, labels, ...labels }`\n * records — one per dictionary entry — keyed by the stable key.\n *\n * staticDict: a code-table-backed source — snapshot() materialises the\n * in-memory table into rows, mirroring `LookupHandle.snapshotEntries()`.\n * Carries `displayLocale` so a locale-less `{ by: 'label' }` query has a\n * default locale to resolve at.\n *\n * Plain dictKey: the snapshot is built synchronously from the\n * `LookupHandle`'s write-through cache, which is populated on every\n * `put()`, `rename()`, `delete()`, and `list()` call. For pre-existing\n * data not yet touched this session, call `await vault.dictionary(name).list()`\n * first to warm the cache.\n *\n * Returns `null` when `field` is not a dictKey in `leftCollection`.\n */\nexport function resolveDictSource(\n leftCollection: string,\n field: string,\n staticDescriptorByField: ReadonlyMap<string, Record<string, StaticDictDescriptor>>,\n dictKeyFieldRegistry: ReadonlyMap<string, Record<string, string>>,\n getDictionaryHandle: (name: string) => LookupHandle,\n): JoinableSource | null {\n const staticFields = staticDescriptorByField.get(leftCollection)\n if (staticFields && field in staticFields) {\n const desc = staticFields[field]!\n const rows: readonly Record<string, unknown>[] = Object.entries(desc.table).map(\n ([key, labels]) => ({ key, labels, ...(labels as Record<string, string>) }),\n )\n const source: JoinableSource = {\n snapshot(): readonly unknown[] {\n return rows\n },\n lookupById(id: string): unknown {\n return rows.find((e) => e['key'] === id)\n },\n }\n if (desc.displayLocale !== undefined) {\n ;(source as { displayLocale?: string }).displayLocale = desc.displayLocale\n }\n return source\n }\n\n const dictFields = dictKeyFieldRegistry.get(leftCollection)\n if (!dictFields || !(field in dictFields)) return null\n const dictName = dictFields[field]\n if (!dictName) return null\n const handle = getDictionaryHandle(dictName)\n return {\n snapshot(): readonly unknown[] {\n return handle.snapshotEntries()\n },\n lookupById(id: string): unknown {\n const entries = handle.snapshotEntries()\n return entries.find((e) => e['key'] === id)\n },\n }\n}\n\n/** The minimal collection surface `updateReferencingRecords` needs. */\nexport interface DictReferencingCollection {\n list(): Promise<Record<string, unknown>[]>\n put(id: string, record: Record<string, unknown>): Promise<unknown>\n}\n\n/**\n * Find and rewrite records in every registered collection whose\n * dictKeyField points at `name`, replacing `oldKey` with `newKey`. Used by\n * `LookupHandle.rename()` (the only sanctioned mass-mutation path for\n * dictKey fields) via the vault's `findAndUpdateReferences` callback.\n *\n * `registry` is `Vault#dictKeyFieldRegistry` (collection name → field name\n * → dictionary name); `getCollection` is the vault's collection accessor —\n * rewrites go through the public `coll.put()` choke point, same as before.\n */\nexport async function updateReferencingRecords(\n registry: ReadonlyMap<string, Record<string, string>>,\n getCollection: (collectionName: string) => DictReferencingCollection,\n name: string,\n oldKey: string,\n newKey: string,\n): Promise<void> {\n for (const [collectionName, dictFields] of registry) {\n // Find fields that point at this dictionary\n const fields = Object.entries(dictFields)\n .filter(([, dn]) => dn === name)\n .map(([field]) => field)\n if (fields.length === 0) continue\n\n const coll = getCollection(collectionName)\n const records = await coll.list()\n for (const record of records) {\n let changed = false\n const updated = { ...record }\n for (const field of fields) {\n if (updated[field] === oldKey) {\n updated[field] = newKey\n changed = true\n }\n }\n if (changed) {\n const id = record['id'] as string | undefined\n if (id !== undefined) {\n await coll.put(id, updated)\n }\n }\n }\n }\n}\n\n/**\n * Resolve a label from an in-memory `{ locale -> label }` map, walking the\n * same fallback chain semantics as `LookupHandle.resolveLabel` (#650 Task 2\n * — moved here from `kernel/vault.ts` so the SAME chain serves both the\n * i18n binding's `dictLabelResolver` and the lookup binding's\n * `lookupLabelResolver`, which #650 Task 2 wires to the identical closure).\n */\nexport function resolveLabelFromMap(\n labels: Readonly<Record<string, string>>,\n locale: string,\n fallback?: string | readonly string[],\n): string | undefined {\n if (labels[locale] !== undefined) return labels[locale]\n const chain = Array.isArray(fallback)\n ? (fallback as readonly string[])\n : fallback\n ? [fallback as string]\n : []\n for (const fb of chain) {\n if (fb === 'any') {\n const any = Object.values(labels)[0]\n if (any !== undefined) return any\n } else if (labels[fb] !== undefined) {\n return labels[fb]\n }\n }\n return undefined\n}\n\n/**\n * Project a native `lookup(dimension, { backing:'static', table, … })`\n * descriptor into the legacy `StaticDictDescriptor` shape — the\n * alias-equivalence compat seam (#650 Task 2) that lets a native\n * static-tier lookup field reuse the SAME vault registries\n * (`staticByName`/`staticDescriptorByField`) — and therefore the same\n * `dictLabelResolver`/`resolveDictSource` machinery — as its `staticDict()`\n * alias. `vocabulary:'closed'` maps to `validateCodes:true` (closed = only\n * declared codes are legal); `'open'` maps to `validateCodes:false`.\n * Returns `undefined` for non-static or table-less (bare `enumOf`)\n * descriptors — those have nothing to register.\n */\nexport function lookupToStaticDictCompat(desc: LookupDescriptor): StaticDictDescriptor | undefined {\n if (desc.backing !== 'static' || desc.table === undefined) return undefined\n return {\n _noydbStaticDict: true,\n _viaBrand: 'i18n',\n name: desc.dimension,\n table: desc.table,\n keys: desc.keys ?? Object.keys(desc.table),\n ...(desc.displayLocale !== undefined ? { displayLocale: desc.displayLocale } : {}),\n ...(desc.onMissing !== undefined ? { onMissing: desc.onMissing } : {}),\n ...(desc.substitute !== undefined ? { substitute: desc.substitute } : {}),\n validateCodes: desc.vocabulary === 'closed',\n }\n}\n\n/** The vault-registry entries a collection's `lookupFields` contribute — the alias-equivalence bridge (#650 Task 2). */\nexport interface LookupDictCompat {\n /** Reserved-tier fields: field name -> dimension (dictionary) name — merges into `dictKeyFieldRegistry`. */\n readonly dictFieldMap: Record<string, string>\n /** Static-tier (table-bearing) fields, projected — merges into `staticDescriptorByField`/`staticByName`. */\n readonly staticEntries: ReadonlyArray<readonly [string, StaticDictDescriptor]>\n}\n\n/**\n * Bridge a collection's `lookupFields` into the SAME shape the legacy dict\n * registries expect, so `resolveDictSource`/`dictLabelResolver` (and\n * therefore `.join()`/`orderBy({by:'label'})`) serve a native `dict()`/\n * `lookup(static)` field identically to its `dictKey()`/`staticDict()`\n * alias — the reserved-vs-first-class-backing \"matrix\" tier is NOT bridged\n * here (no vault registry backs it; Task 5/6 build its own graph edge /\n * snapshot seam).\n */\nexport function collectLookupDictCompat(\n lookupFields: Record<string, LookupDescriptor> | undefined,\n): LookupDictCompat {\n const dictFieldMap: Record<string, string> = {}\n const staticEntries: Array<readonly [string, StaticDictDescriptor]> = []\n for (const [field, desc] of Object.entries(lookupFields ?? {})) {\n if (desc.backing === 'reserved') {\n dictFieldMap[field] = desc.dimension\n } else {\n const compat = lookupToStaticDictCompat(desc)\n if (compat) staticEntries.push([field, compat])\n }\n }\n return { dictFieldMap, staticEntries }\n}\n\n/**\n * Reserved-dict deps of a set of named collections (#653) — the `_dict_*`\n * collections partial sync must auto-include alongside a `collections`\n * filter, mirroring `SyncEngine`'s existing satellite-pair expansion.\n * One hop is provably complete: `vault.collection()` refuses `_dict_*`\n * names, so a dict can never itself declare lookup fields — no\n * dict-of-dict chain to recurse through.\n */\nexport function reservedDictDepsOf(\n names: readonly string[],\n dictKeyFieldRegistry: ReadonlyMap<string, Record<string, string>>,\n): readonly string[] {\n const out = new Set<string>()\n for (const name of names) {\n const fieldMap = dictKeyFieldRegistry.get(name)\n if (!fieldMap) continue\n for (const dictName of Object.values(fieldMap)) out.add(dictCollectionName(dictName))\n }\n return [...out]\n}\n\n/**\n * A lookup dimension's sync membership/altKey table, materialized from its\n * backing rows (#650 Task 3). `keys` is every canonical key present;\n * `altIndex` maps an altKey candidate VALUE to its owning canonical key.\n */\nexport interface MaterializedBacking {\n /** Canonical key values present in the materialized rows. */\n readonly keys: ReadonlySet<string>\n /** altKey candidate value -> canonical key. */\n readonly altIndex: ReadonlyMap<string, string>\n}\n\n/**\n * Build a lookup dimension's altKey index from its backing rows, enforcing\n * declare/warm-time uniqueness across `key ∪ altKeys` values (#650 Task 3 —\n * the CHE/SWZ drift class: two different rows must never claim the same\n * candidate key). `rows` is keyed by canonical key (`row[descriptor.key]`\n * for the matrix tier; the dimension's own key for static/reserved).\n * An altKey candidate VALUE may be a string or number — both normalize via\n * `coerceLookupKey` (#651 Task 3); non-scalar/absent values are skipped.\n * Pure — no I/O. Throws `ValidationError` on collision.\n */\nexport function materializeBackingTable(\n descriptor: LookupDescriptor,\n rows: ReadonlyMap<string, Record<string, unknown>>,\n): MaterializedBacking {\n const keys = new Set<string>(rows.keys())\n // Every value that has claimed ownership so far (canonical keys seed it) —\n // the union `key ∪ altKeys` uniqueness set the spec requires.\n const owner = new Map<string, string>()\n for (const key of keys) owner.set(key, key)\n\n const altIndex = new Map<string, string>()\n const altFields = descriptor.altKeys ?? []\n for (const [canonicalKey, row] of rows) {\n for (const altField of altFields) {\n const value = coerceLookupKey(row[altField])\n if (value === undefined || value === '') continue\n const existingOwner = owner.get(value)\n if (existingOwner !== undefined && existingOwner !== canonicalKey) {\n throw new ValidationError(\n `lookup \"${descriptor.dimension}\": altKey field \"${altField}\" value \"${value}\" is claimed by ` +\n `both \"${existingOwner}\" and \"${canonicalKey}\" — key/altKey values must be unique across the dimension.`,\n )\n }\n owner.set(value, canonicalKey)\n altIndex.set(value, canonicalKey)\n }\n }\n return { keys, altIndex }\n}\n\n/**\n * Closed-vocabulary membership test for one candidate key (#650 Task 3).\n * Static tier: sync, against the in-config key set (declared `keys`, or the\n * table's own keys when table-bearing). Reserved tier: sync — the declared\n * `keys` union the reserved handle's live write-through snapshot (closes\n * #649 for the native `dict()` spelling: the declared-keys promise the old\n * `dictKey()` doc comment made falsely). Matrix (collection) tier: sync —\n * delegates to `buildLookupAltIndex` so membership is checked against the\n * SAME `row[descriptor.key]` keying the altKey index uses (review fix,\n * Important 1: an earlier PUT-id `.get(key)` scan disagreed with the\n * altIndex whenever `descriptor.key !== 'id'`, wrongly rejecting valid\n * non-id candidates and wrongly accepting an unrelated row's PUT-id).\n */\nexport function checkLookupMembership(\n descriptor: LookupDescriptor,\n key: string,\n getDictionary: (dimension: string) => LookupHandle,\n getCollection: (dimension: string) => { querySourceForJoin(): JoinableSource },\n): boolean {\n if (descriptor.backing === 'static') {\n const known = descriptor.keys ?? (descriptor.table ? Object.keys(descriptor.table) : [])\n return known.includes(key)\n }\n if (descriptor.backing === 'reserved') {\n if ((descriptor.keys ?? []).includes(key)) return true\n return getDictionary(descriptor.dimension).snapshotEntries().some((e) => e['key'] === key)\n }\n return buildLookupAltIndex(descriptor, getDictionary, getCollection).keys.has(key)\n}\n\n/**\n * The ONE guarded key coercion (#651 Task 3, dm12) — string/number values\n * coerce to their canonical `String()` form; everything else (`null`,\n * `undefined`, objects, …) coerces to `undefined`. Every consumer that turns\n * a raw record field into a lookup key routes through this, closing the\n * bare-`String()` `\"undefined\"`/`\"null\"`-key poisoning class (seam map\n * finding 6): a row whose key field is genuinely absent must never mint the\n * literal candidate string `\"undefined\"`.\n */\nexport function coerceLookupKey(raw: unknown): string | undefined {\n return typeof raw === 'string' || typeof raw === 'number' ? String(raw) : undefined\n}\n\n/**\n * Resolve a backing row's canonical key VALUE — `coerceLookupKey(row[descriptor.key])`\n * (#651 Task 3). The matrix tier's `row[descriptor.key]`, never the row's own PUT-id\n * when the two differ (`descriptor.key !== 'id'`).\n */\nexport function resolveBackingRowKey(\n descriptor: LookupDescriptor,\n row: Record<string, unknown>,\n): string | undefined {\n return coerceLookupKey(row[descriptor.key])\n}\n\n/**\n * The referencing-side match predicate — does `rec[field]` (coerced) equal an\n * already-coerced `compareKey` (#651 Task 3)? Shared by every site that scans a\n * referencing collection for rows pointing at a given backing key\n * (`with-shape/links/vault-facade.ts`'s ref-delete propagation, `kernel/via/dispatch.ts`'s\n * forget-fanout twin).\n */\nexport function matchesReferencingValue(\n rec: Record<string, unknown>,\n field: string,\n compareKey: string,\n): boolean {\n return coerceLookupKey(rec[field]) === compareKey\n}\n\n/**\n * Materialize a lookup dimension's altKey index from whatever backing data\n * is synchronously available (#650 Task 3 — the `ingest` source). Static:\n * the in-config table. Reserved: the reserved handle's live write-through\n * cache (the same warm-via-put()/list() cache `resolveDictSource` already\n * relies on). Matrix (collection): the backing collection's own in-memory\n * eager cache via `querySourceForJoin()` — already public, already the\n * mechanism `.join()` uses (`with-shape/links/vault-facade.ts`'s\n * `resolveSource`); no new I/O, no fire-and-forget warm step. Like that\n * existing join precedent, a dimension collection this vault session has\n * not yet opened/populated sees an empty snapshot (no altKey normalization\n * until it has rows) — open/populate it first for normalization to apply.\n * A matrix row whose `descriptor.key` field coerces to `undefined` (missing/\n * non-scalar) is SKIPPED — never enters the index under a poisoned\n * `\"undefined\"` key (#651 Task 3, dm12).\n */\nexport function buildLookupAltIndex(\n descriptor: LookupDescriptor,\n getDictionary: (dimension: string) => LookupHandle,\n getCollection: (dimension: string) => { querySourceForJoin(): JoinableSource },\n): MaterializedBacking {\n if (descriptor.backing === 'static') {\n return materializeBackingTable(descriptor, new Map(Object.entries(descriptor.table ?? {})))\n }\n if (descriptor.backing === 'reserved') {\n const entries = getDictionary(descriptor.dimension).snapshotEntries()\n return materializeBackingTable(descriptor, new Map(entries.map((e) => [String(e['key']), e])))\n }\n const rows = getCollection(descriptor.dimension).querySourceForJoin().snapshot()\n const keyed = new Map<string, Record<string, unknown>>()\n for (const r of rows) {\n const row = r as Record<string, unknown>\n const key = resolveBackingRowKey(descriptor, row)\n if (key !== undefined) keyed.set(key, row)\n }\n return materializeBackingTable(descriptor, keyed)\n}\n\n/** One cross-collection `'ref'` graph edge a lookup field declares (#650 Task 5). Module-private —\n * only `registerLookupRefEdges` below (the exported entry point) consumes it. */\ninterface LookupRefEdge {\n readonly referencing: FieldRef\n readonly sources: readonly FieldRef[]\n readonly onDelete: OnDelete\n /** The backing dimension's canonical-key FIELD NAME on its own row (`desc.key` — matrix tier\n * only varies this; reserved/static tiers are always `'id'`). A referencing field always\n * stores THIS field's value, never the backing row's PUT-id when the two differ. */\n readonly keyField: string\n}\n\n/**\n * Compute the cross-collection `'ref'` edges a collection's `lookupFields` declare (#650 Task 5,\n * spec §4) — one edge per non-static-backing field: target = the referencing field; sources =\n * the backing dimension's whole-collection node (`field:'*'`, the wildcard key\n * `ViaGraph.referencingEdgesOf` does its O(1) reverse lookup against) PLUS, when the descriptor\n * names a presentation field (`present.label`), that SPECIFIC field too. `foldPosture`'s\n * `DEFAULT_POSTURE` is the fold's identity element, so adding the wildcard alongside a real field\n * source changes nothing when that field is plain — but folds in a classified/money posture when\n * it isn't (taint composition, spec §4: \"a lookup edge whose source names a classified field\n * contributes that field's posture\"). Static tier (`backing:'static'`) has no backing collection/\n * dimension rows to reference-check — excluded. Pure; consumed only by `registerLookupRefEdges` below.\n */\nfunction collectLookupRefEdges(\n collectionName: string,\n lookupFields: Record<string, LookupDescriptor> | undefined,\n): readonly LookupRefEdge[] {\n const edges: LookupRefEdge[] = []\n for (const [field, desc] of Object.entries(lookupFields ?? {})) {\n if (desc.backing === 'static') continue\n const backing = desc.backing === 'reserved' ? dictCollectionName(desc.dimension) : desc.dimension\n edges.push({\n referencing: { collection: collectionName, field },\n sources: [\n { collection: backing, field: '*' },\n ...(desc.present?.label !== undefined ? [{ collection: backing, field: desc.present.label }] : []),\n ],\n onDelete: desc.onDelete,\n keyField: desc.key,\n })\n }\n return edges\n}\n\n/** Thin wrapper — `collectLookupRefEdges` + one `graph.registerDerived` call per edge. Lets\n * `vault.collection()` (kernel-surface-budgeted, #650 Task 5) register a collection's lookup-ref\n * edges with a single line, keeping the ceiling-guarded call site a thin call (route logic here). */\nexport function registerLookupRefEdges(\n graph: ViaGraph,\n collectionName: string,\n lookupFields: Record<string, LookupDescriptor> | undefined,\n): void {\n for (const e of collectLookupRefEdges(collectionName, lookupFields)) {\n graph.registerDerived(e.referencing, e.sources, 'ref', 'record', e.onDelete, e.keyField)\n }\n}\n\n/**\n * `LookupViaConfig.snapshotFor`'s vault-built row source (#650 Task 6, spec\n * §5; matrix-tier coverage added #650 Task 7, spec §6 — Task 6 deferred it,\n * see `task-6-report.md`'s Concerns #1; the reviewer's Task-7 dispatch\n * refuted the \"needs a new vault-resident registry\" premise: the descriptor\n * is already in hand at both call sites, so `snapshotFor` just needs to\n * ACCEPT it). Takes the full `descriptor` (not a bare dimension name) so it\n * can route the matrix tier's `key` field, which — unlike reserved tier's\n * hardcoded `'id'` — varies per collection. Routes on `descriptor.backing`:\n *\n * - **reserved**: rows come straight from the SAME `LookupHandle.\n * snapshotEntries()` write-through cache `dictLabelResolver`/\n * `resolveDictSource` already read (no second copy), keyed by each\n * entry's own canonical `key` (always `'id'` by construction for this\n * tier — `dict()`'s factory hardcodes it).\n * - **collection** (matrix): rows come from `getCollection(dimension).\n * querySourceForJoin().snapshot()` — the SAME sync, already-live cache\n * `buildLookupAltIndex`'s matrix branch (above, this file) and `.join()`\n * itself already read — re-keyed via `resolveBackingRowKey(descriptor, row)`,\n * NOT the row's own PUT-id (which may differ when `key !== 'id'`; the exact\n * distinction the #650 Task 3 review fix already applies to\n * `checkLookupMembership`'s matrix branch). A row whose `descriptor.key`\n * field coerces to `undefined` is skipped (#651 Task 3, dm12).\n * - **static**: never routed here — `descriptor.table` is read directly by\n * the caller (`binding.ts`'s `compareLookupOrder`/`resolveLookupOrderLabel`,\n * `snapshot.ts`'s `presentLookupForJoin`); no vault call needed.\n *\n * `isReservedDimension` is the vault's `reservedLookupCollections`\n * membership test.\n */\nexport function buildLookupSnapshotRows(\n descriptor: LookupDescriptor,\n isReservedDimension: (dimension: string) => boolean,\n getDictionary: (dimension: string) => LookupHandle,\n getCollection: (dimension: string) => { querySourceForJoin(): JoinableSource },\n): ReadonlyMap<string, Record<string, unknown>> | undefined {\n const dimension = descriptor.dimension\n if (isReservedDimension(dimension)) {\n const rows = new Map<string, Record<string, unknown>>()\n for (const entry of getDictionary(dimension).snapshotEntries()) {\n const key = entry['key']\n if (typeof key === 'string') rows.set(key, entry)\n }\n return rows\n }\n if (descriptor.backing === 'collection') {\n const rawRows = getCollection(dimension).querySourceForJoin().snapshot()\n const rows = new Map<string, Record<string, unknown>>()\n for (const r of rawRows) {\n const row = r as Record<string, unknown>\n const key = resolveBackingRowKey(descriptor, row)\n if (key !== undefined) rows.set(key, row)\n }\n return rows\n }\n return undefined\n}\n","/**\n * The sync lookup snapshot + join/locale seam (#650 Task 6, spec §5 — \"the\n * snapshot+locale seam\"). Retires the #626 kernel→via grandfather:\n * `kernel/query/join.ts` no longer imports `via/i18n/core.js` directly\n * — it calls the `presentForJoin` hook this file's `buildPresentForJoin`\n * builds instead (seam map Part 2 item 4, the #626 reviewer-spec'd shape:\n * a sync `presentI18nForJoin`-class hook on `JoinableSource`).\n *\n * `LookupSnapshot` is the sync materialized `key -> row` view over ONE\n * lookup dimension's ALREADY-LIVE backing data (the `active.ts`\n * `_syncCache`/`snapshotEntries` write-through-cache pattern — never a\n * second copy of the data: `LookupViaConfig.snapshotFor`'s vault-built\n * closure reads the SAME `LookupHandle._syncCache` /\n * first-class-collection cache every other lookup consumer\n * (`dictLabelResolver`, `resolveDictSource`, `getAltIndex`) already reads).\n * Serves (reserved AND matrix tier since #650 Task 7 — `registry.ts`'s\n * `buildLookupSnapshotRows` routes both; static tier is read straight off\n * `descriptor.table` by every consumer below, never through this cache):\n * - join dressing (`presentForJoin`, consumed by `kernel/query/join.ts`\n * via `JoinableSource.presentForJoin`)\n * - dimension sort (`compareForOrder`, consumed by\n * `via/lookup/binding.ts`'s `NoydbVia.compareForOrder` closure)\n * - per-call-locale order-label resolution (`resolveOrderLabel`, #650\n * Task 7 — the `orderBy(..., {by:'label'})` channel `compareForOrder`\n * structurally can't serve, no locale param; consumed by\n * `kernel/query/builder.ts`'s `buildOrderLabelMaps`)\n * - membership: reserved/static-tier membership (#650 Task 3,\n * `checkLookupMembership`) already reads the identical sync caches\n * directly — not re-plumbed through this file; see\n * `.superpowers/sdd/task-6-report.md`'s \"bridge disposition\" section.\n *\n * Sync end-to-end (#553) — every function here is a pure, synchronous\n * transform over already-materialized rows; no store read, no Promise.\n */\nimport type { LookupDescriptor } from './descriptor.js'\nimport { presentI18nForJoin, type I18nTextDescriptor } from '../i18n/core.js'\n\n/** A lookup dimension's sync materialized view — see file header. */\nexport interface LookupSnapshot {\n /** The full backing row for `key`, or `undefined` when `key` isn't (yet) present in the snapshot. */\n row(key: string): Record<string, unknown> | undefined\n /** The dimension's declared presentation label for `key` at `locale` — mirrors `binding.ts`'s `fetchLookupLabel` (matrix-row branch), generalized to any tier's already-materialized rows. */\n label(key: string, locale: string, fallback?: unknown): string | undefined\n /**\n * Exact ordering for two canonical keys against `descriptor.sortBy`\n * (falls back to `present.label`, then to the raw keys) at `locale`.\n * Never throws — degrades to comparing the raw keys when no sortable\n * value resolves for either side.\n */\n compareKeys(a: string, b: string, locale: string): number\n}\n\n/** Read one row field, resolving a `by`-keyed (locale-map) value when `by` is declared. */\nfunction readRowField(\n row: Record<string, unknown> | undefined,\n field: string | undefined,\n by: string | undefined,\n locale: string,\n fallback?: unknown,\n): string | undefined {\n if (!row || field === undefined) return undefined\n const raw = row[field]\n if (by === undefined) return typeof raw === 'string' ? raw : undefined\n if (!raw || typeof raw !== 'object') return undefined\n const map = raw as Record<string, unknown>\n const val = map[locale]\n if (typeof val === 'string') return val\n if (typeof fallback === 'string' && typeof map[fallback] === 'string') return map[fallback]\n return undefined\n}\n\n/**\n * Build a sync `LookupSnapshot` over one dimension's already-materialized\n * rows (canonical-key -> row, the SAME keying `materializeBackingTable`\n * (`registry.ts`, #650 Task 3) uses). Pure — never reads a store.\n */\nexport function buildLookupSnapshot(\n dimension: string,\n rows: ReadonlyMap<string, Record<string, unknown>>,\n descriptor: LookupDescriptor,\n): LookupSnapshot {\n void dimension // identity only — kept for parity with materializeBackingTable/buildLookupAltIndex's signature and future diagnostics\n return {\n row: (key) => rows.get(key),\n label: (key, locale, fallback) =>\n readRowField(rows.get(key), descriptor.present?.label, descriptor.present?.by, locale, fallback),\n compareKeys: (a, b, locale) => {\n const sortField = descriptor.sortBy ?? descriptor.present?.label\n const av = readRowField(rows.get(a), sortField, descriptor.present?.by, locale) ?? a\n const bv = readRowField(rows.get(b), sortField, descriptor.present?.by, locale) ?? b\n return av < bv ? -1 : av > bv ? 1 : 0\n },\n }\n}\n\n/**\n * The lookup-label HALF of `presentForJoin` (#626 retirement, spec §5;\n * matrix-tier coverage added #650 Task 7) — resolves `<field>Label` for\n * every declared lookup field with a `present` dressing dimension, sync,\n * from `getSnapshotRows` (the vault-built `LookupViaConfig.snapshotFor`\n * closure — now descriptor-routed, see `registry.ts`'s\n * `buildLookupSnapshotRows`; static tier reads its own in-config `table`\n * directly, no vault call — never `undefined` for a declared static table).\n * Mirrors `binding.ts`'s `runLookupPresent` (the async `present()` hook)\n * minus the array/`[].`-wildcard handling that hook needs for full-record\n * reads — join dressing only ever sees the joined RIGHT-side record's\n * scalar fields, so that complexity doesn't apply here.\n */\nfunction presentLookupForJoin(\n record: Record<string, unknown>,\n locale: string,\n lookupFields: Record<string, LookupDescriptor>,\n getSnapshotRows: (descriptor: LookupDescriptor) => ReadonlyMap<string, Record<string, unknown>> | undefined,\n): Record<string, unknown> {\n let result = record\n for (const [field, desc] of Object.entries(lookupFields)) {\n if (desc.present === undefined) continue\n const raw = record[field]\n if (typeof raw !== 'string') continue\n const rows = desc.backing === 'static'\n ? (desc.table ? new Map(Object.entries(desc.table)) : undefined)\n : getSnapshotRows(desc)\n if (!rows) continue\n const label = buildLookupSnapshot(desc.dimension, rows, desc).label(raw, locale)\n if (label === undefined) continue\n if (result === record) result = { ...record }\n result[`${field}Label`] = label\n }\n return result\n}\n\n/**\n * Build the combined sync `presentForJoin(record, locale)` hook a\n * `Collection` attaches to the `JoinableSource` it exposes\n * (`querySourceForJoin()`) — the i18n-text half (`presentI18nForJoin`, the\n * exact `applyI18nLocale(..., 'join')` partial application\n * `kernel/query/join.ts` used to call directly, #626) composed with the\n * lookup-label half above. `undefined` when the collection declares\n * neither — `JoinableSource.presentForJoin` then stays unset, matching\n * today's `i18nFields`-absent behavior exactly (#626 parity lock).\n */\nexport function buildPresentForJoin(\n i18nFields: Record<string, I18nTextDescriptor> | undefined,\n lookupFields: Record<string, LookupDescriptor> | undefined,\n getSnapshotRows: ((descriptor: LookupDescriptor) => ReadonlyMap<string, Record<string, unknown>> | undefined) | undefined,\n): ((record: unknown, locale: string) => unknown) | undefined {\n const hasI18n = i18nFields !== undefined && Object.keys(i18nFields).length > 0\n const hasLookup = lookupFields !== undefined && Object.keys(lookupFields).length > 0\n if (!hasI18n && !hasLookup) return undefined\n const resolveRows = getSnapshotRows ?? (() => undefined)\n return (record, locale) => {\n if (record === null || typeof record !== 'object') return record\n let result = record as Record<string, unknown>\n if (hasI18n) result = presentI18nForJoin(result, i18nFields, locale)\n if (hasLookup) result = presentLookupForJoin(result, locale, lookupFields, resolveRows)\n return result\n }\n}\n","/**\n * Lookup strategy seam (#650 Task 1 — via-lookup extraction, phase D of the\n * Via port; precedent: `port/with/i18n-strategy.ts`). Lives on the `/with`\n * port (the one seam the kernel spine may import statically) so `Vault` can\n * reach the dict-registry pure helpers and the `LookupHandle`/`NO_LOOKUP`\n * types without a spine→`via/` static import (Check 14 via-layering bans\n * that; `port/with/` is always allowed, Check 9's sanctioned exception).\n *\n * `kernel/vault.ts` imports ONLY this module for lookup — never\n * `via/lookup/*` directly.\n *\n * This task (#650 Task 1) is a pure move: `Vault.dictionary()` still\n * constructs its handle through `i18nStrategy.buildDictionaryHandle`\n * (`port/with/i18n-strategy.ts`), which now internally delegates to\n * `withLookup().buildLookupHandle` (same handle, new home). `LookupStrategy`\n * / `NO_LOOKUP` / `isLookupCollectionName` here are the seam later phase-D\n * tasks bind `vault.collection()`'s lookup fields onto — unused by Task 1's\n * wiring, but their exact shapes are frozen now so later tasks don't\n * re-litigate them.\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../../kernel/types.js'\nimport type { LedgerStore } from '../../with-commit/history/ledger/store.js'\nimport type { UnlockedKeyring } from '../../with-party/team/keyring.js'\nimport type { NoydbEventEmitter } from '../../kernel/events.js'\nimport type { ViaCryptoCtx } from '../../kernel/via/index.js'\nimport type { LookupHandle, DictionaryOptions } from '../../via/lookup/handle.js'\nimport {\n enforceStaticDictOnPut,\n resolveDictSource,\n updateReferencingRecords,\n resolveLabelFromMap,\n collectLookupDictCompat,\n lookupToStaticDictCompat,\n reservedDictDepsOf,\n materializeBackingTable,\n checkLookupMembership,\n buildLookupAltIndex,\n registerLookupRefEdges,\n buildLookupSnapshotRows,\n coerceLookupKey,\n resolveBackingRowKey,\n matchesReferencingValue,\n type DictReferencingCollection,\n type LookupDictCompat,\n type MaterializedBacking,\n} from '../../via/lookup/registry.js'\nimport { buildPresentForJoin } from '../../via/lookup/snapshot.js'\nimport type { LookupDescriptor } from '../../via/lookup/descriptor.js'\n\n/**\n * Backing options for `LookupStrategy.buildLookupHandle` — same shape as\n * `DictionaryOptions` (kept as a distinct alias since the \"lookup\" name is\n * the forward-looking one; `DictionaryOptions` stays the dict-tier name).\n */\nexport type LookupBackingOptions = DictionaryOptions\n\n/**\n * Options accepted by `LookupStrategy.buildLookupHandle`. Mirrors the\n * `LookupHandle` constructor verbatim, plus the two choke-point\n * participation hooks (`onDirty`/`onRecordMutated`) #647 (Task 4) wires —\n * both `undefined` in this task (pure move, no new call sites).\n */\nexport interface BuildLookupHandleOptions<Keys extends string = string> {\n readonly adapter: NoydbStore\n readonly compartmentName: string\n readonly dimensionName: string\n readonly keyring: UnlockedKeyring\n /**\n * The `reservedEnvelopes('_dict_')` capability (#629 Task 4) — the\n * handle's sanctioned crypto door onto its `_dict_<name>` collection.\n * Bound by the Vault to its own `getDEK`, the same per-collection-name\n * DEK resolver every other collection uses.\n */\n readonly reservedEnvelopes: ReturnType<ViaCryptoCtx['reservedEnvelopes']>\n readonly encrypted: boolean\n readonly ledger: LedgerStore | undefined\n readonly options: LookupBackingOptions\n readonly findAndUpdateReferences:\n | ((dimension: string, oldKey: string, newKey: string) => Promise<void>)\n | undefined\n readonly emitter: NoydbEventEmitter\n /**\n * #647 fix wave 1 — mints a version-ordered delete-marker envelope. Bound by the Vault to the\n * real `kernel/enclave` `buildDeleteMarker` function — `LookupHandle` (`via/lookup/**`)\n * may not import `kernel/enclave/` itself (Check 11/15), so this capability is injected the\n * same way `reservedEnvelopes` above is.\n */\n readonly buildDeleteMarker: (identity: { collection: string; id: string }, version: number, actor: string) => EncryptedEnvelope\n /** #650 Task 4 (#647) — choke-point participation hooks. */\n readonly onDirty?: ((collection: string, id: string, action: 'put' | 'delete', version: number) => Promise<void>) | undefined\n readonly onRecordMutated?: ((collection: string, id: string, action: 'put' | 'delete', version: number) => Promise<void>) | undefined\n /**\n * #650 Task 5 (#648) — the real reference check `LookupHandle.delete()`'s strict branch calls:\n * restrict throws `DictKeyInUseError` naming the referencing collection, cascade/nullify apply\n * their propagation. Bound by the Vault (never a `Collection`/keyring/DEK reach-around); a\n * no-op when the dimension has no declared lookup-referencing edges (today's dangling behavior\n * for undeclared refs is unaffected). Return value is discarded by the handle — callers who\n * need cascade/nullify counts (forget) go through `VaultLinks` directly.\n */\n readonly checkReferencesOnDelete?: ((key: string) => Promise<unknown>) | undefined\n /**\n * Used by the active strategy to satisfy the generic-key parameter on the\n * returned handle. The NO_LOOKUP stub never reads it. Mirrors\n * `BuildDictionaryHandleOptions._keyMarker` (`port/with/i18n-strategy.ts`).\n */\n // marker generic — runtime sees no value\n _keyMarker?: Keys\n}\n\nexport interface LookupStrategy {\n /**\n * Construct a typed `LookupHandle` for the named dimension. Throws under\n * `NO_LOOKUP`.\n */\n buildLookupHandle<Keys extends string = string>(\n opts: BuildLookupHandleOptions<Keys>,\n ): LookupHandle<Keys>\n}\n\nfunction notEnabled(op: string): Error {\n return new Error(\n `${op}: the NO_LOOKUP stub was reached, which should be unreachable today — there is no ` +\n '`lookupStrategy` `createNoydb({ ... })` option yet to select this stub over the real one; ' +\n '`vault.dictionary()` always resolves through `withLookup()` (see `via/i18n/active.ts`\\'s ' +\n 'delegation). This is forward scaffolding for a later task (mirrors `NO_I18N`\\'s shape) — if you ' +\n 'hit this, it indicates a bug, not a missing opt-in.',\n )\n}\n\n/**\n * No-lookup stub. Mirrors `NO_I18N.buildDictionaryHandle`'s shape, but unlike `NO_I18N` (wired as\n * `vault.ts`'s `opts.i18nStrategy ?? NO_I18N` default), nothing selects this stub today — there is\n * no `lookupStrategy` option on `createNoydb()`; `vault.dictionary()`'s only construction path\n * (`Vault.i18nStrategy.buildDictionaryHandle` → `withLookup().buildLookupHandle`) never reaches\n * here. Kept as forward scaffolding for a later task that wires an independent lookup opt-in.\n */\nexport const NO_LOOKUP: LookupStrategy = {\n buildLookupHandle() {\n throw notEnabled('vault.dictionary()')\n },\n}\n\n/** `_dict_*` (legacy dict tier) and `_lookup_*` (the phase-D reserved backing). */\nexport const LOOKUP_COLLECTION_PREFIXES = ['_dict_', '_lookup_'] as const\n\n/** Return true when a collection name is a reserved lookup-backing collection. */\nexport function isLookupCollectionName(name: string): boolean {\n return LOOKUP_COLLECTION_PREFIXES.some((prefix) => name.startsWith(prefix))\n}\n\n// Re-exported pure registry helpers (#650 Task 1) — `kernel/vault.ts`'s\n// thin delegators call these directly; small always-on functions, not\n// behind the tree-shake seam (same bundling class as `isLookupCollectionName`\n// above, just too large to duplicate inline like that one is).\nexport { enforceStaticDictOnPut, resolveDictSource, updateReferencingRecords }\nexport type { DictReferencingCollection }\n\n// #650 Task 4 (#647) — the reserved-collection naming helper `vault.ts`'s sync-registry\n// bookkeeping needs (mapping a declared dimension name to its `_dict_<name>` collection name).\nexport { dictCollectionName } from '../../via/lookup/handle.js'\n\n// #650 Task 2 — the alias-equivalence bridge (`resolveLabelFromMap` +\n// `collectLookupDictCompat`/`lookupToStaticDictCompat`) + the runtime\n// brand/shape predicates `via/compose.ts` needs to route `'lookup'`-branded\n// descriptors, mirroring `isI18nTextDescriptor`/`isDictKeyDescriptor` below.\nexport { resolveLabelFromMap, collectLookupDictCompat, lookupToStaticDictCompat }\nexport type { LookupDictCompat }\n\n// #653 — partial-sync reserved-dict expansion: maps a set of named collections to the\n// one-hop `_dict_*` deps their lookup fields reference, off `dictKeyFieldRegistry`.\nexport { reservedDictDepsOf }\n\n// #650 Task 3 — altKeys ingest normalization + open/closed vocabulary\n// governance: the declare/warm-time altIndex builder + the membership test\n// vault.ts's `membership`/`getAltIndex` closures delegate to.\nexport { materializeBackingTable, checkLookupMembership, buildLookupAltIndex }\nexport type { MaterializedBacking }\n\n// #650 Task 5 — registers a collection's lookup-fields' cross-collection 'ref' graph edges.\nexport { registerLookupRefEdges }\n\n// #650 Task 6 — the sync snapshot+locale seam (#626 retirement, spec §5):\n// `snapshotFor`'s vault-built row source + the combined presentForJoin\n// builder `kernel/collection-config.ts` calls to build the\n// `JoinableSource.presentForJoin` hook `kernel/query/join.ts` consumes.\nexport { buildLookupSnapshotRows, buildPresentForJoin }\nexport type { LookupSnapshot } from '../../via/lookup/snapshot.js'\n\n// #651 Task 3 — the ONE descriptor-keyed key-resolution core (guarded coercion +\n// backing-row-key resolve + referencing-value match) — every consumer (vault.ts,\n// with-shape/links/vault-facade.ts, kernel/via/dispatch.ts) routes through here,\n// never a bare `String()`, ending the dm12 dialect drift.\nexport { coerceLookupKey, resolveBackingRowKey, matchesReferencingValue }\n\n/** Runtime predicate for detecting a `LookupDescriptor` (any of the three tiers). */\nexport function isLookupDescriptor(x: unknown): x is LookupDescriptor {\n return (\n typeof x === 'object' &&\n x !== null &&\n (x as { _viaBrand?: unknown })._viaBrand === 'lookup'\n )\n}\n\n/** Runtime predicate for the bare enum tier (`backing:'static'`, no in-code `table` — no label source). */\nexport function isEnumDescriptor(x: unknown): x is LookupDescriptor {\n return isLookupDescriptor(x) && x.backing === 'static' && x.table === undefined\n}\n\n/**\n * Type-only re-exports — the kernel spine imports these descriptor/handle\n * types through the port instead of reaching into `via/lookup/*` or\n * `via/i18n/*` directly. `isolatedModules: true` erases these at\n * build time — no runtime coupling.\n */\nexport type { LookupHandle, DictEntry, DictionaryOptions } from '../../via/lookup/handle.js'\nexport type { LookupDescriptor, Vocabulary, LookupBacking, OnDelete } from '../../via/lookup/descriptor.js'\nexport type { LookupViaConfig } from '../../via/lookup/binding.js'\nexport type { DictKeyDescriptor, StaticDictDescriptor } from '../../via/i18n/dictionary.js'\n","// kernel/via/dispatch.ts — the batched, origin-aware sync/cutover/restore dispatch wave\n// (Via port phase C, #638 Task 4, fixes #621).\n//\n// `Collection._onRecordMutated`'s `sync-apply`/`cutover`/`restore` cases feed touched\n// (collection, id) pairs into a per-session `GraphBatch` (owned by `Vault._collectGraphTouch`)\n// instead of dispatching inline — the `local-write` path keeps its own byte-identical inline\n// dispatch (`wave` stays `undefined` there, per the spec's behavior lock). At batch-flush time\n// `runGraphDispatchWave` decrypts each touched record (id threaded into the decrypt, matching\n// the phase-B at-rest contract) and re-runs the SAME `dispatchDerivations`/\n// `dispatchMaterializedViews` the local-write path uses, sharing one `WaveContext` so N touched\n// records feeding the SAME rollup/MV target recompute exactly once (per-target dedup).\n// See design-history/2026-07-11-via-phase-c-design.md §3.\n\nimport type { ViaGraph } from './graph.js'\nimport type { Collection } from '../collection.js'\nimport type { EncryptedEnvelope } from '../types.js'\nimport { PeriodClosedError } from '../errors.js'\nimport { matchesReferencingValue } from '../../port/with/lookup-strategy.js'\n\n/** One deleted child's resolved rollup PARENT intent (#640) — ids + a field name only. A\n * resolved `parentId` is an id, same class as any touched record id — never a stored value. */\nexport interface RollupDeleteIntent {\n readonly into: string\n readonly parentId: string\n readonly field: string\n}\n\n/** One collection's batched touches this session (#640 widens the #638 `Set<string>` shape):\n * `puts` — the original semantics, unchanged; `deletes` — a deleted record's id mapped to its\n * resolved rollup-parent intents, captured PRE-invalidation by `Collection._onRecordMutated`'s\n * sync-apply delete case (the FK is only readable there — see `kernel/collection.ts\n * #_rollupDeleteIntents`). */\nexport interface GraphTouch {\n readonly puts: Set<string>\n readonly deletes: Map<string, readonly RollupDeleteIntent[]>\n}\n\n/** Per-session touched set — collection → its `GraphTouch`. Metadata only — ids (collection\n * names, record ids INCLUDING resolved rollup parent ids) and field names; NEVER record payload\n * or key material. A resolved parentId is an id, same class as the touched ids — not a stored\n * value. */\nexport type GraphBatch = Map<string, GraphTouch>\n\n/** Get-or-create `batch`'s `GraphTouch` entry for `collection` (#640) — shared by\n * `Vault._collectGraphTouch`/`_collectGraphDelete` so each stays a one-line call. */\nexport function touchFor(batch: GraphBatch, collection: string): GraphTouch {\n let t = batch.get(collection)\n if (!t) {\n t = { puts: new Set(), deletes: new Map() }\n batch.set(collection, t)\n }\n return t\n}\n\n/** #640 — sync, I/O-free: `deleted`'s resolved rollup PARENT intents (the FK is only readable\n * NOW, before the record is gone) — a pure function so `Collection._rollupDeleteIntents` stays\n * a one-line delegator under the kernel-surface ceiling. `registry` is `this.derivationSource\n * ?.registry()`; `collectionName` is `this.name` (the CHILD/`rollup.from` side). Generic over\n * the registry's own spec shape so this file never imports a `with-formula` type (port-layering\n * — via/dispatch.ts must not gain a with-* import). */\nexport function resolveRollupDeleteIntents<S extends { source: string; rollup?: { from: string; key: string; field: string } }>(\n registry: { strategiesForSource(name: string): ReadonlyArray<{ spec: S }> } | undefined,\n collectionName: string,\n deleted: Record<string, unknown>,\n): RollupDeleteIntent[] {\n if (!registry) return []\n const intents: RollupDeleteIntent[] = []\n for (const { spec } of registry.strategiesForSource(collectionName)) {\n if (!spec.rollup || spec.rollup.from !== collectionName) continue\n const kv = deleted[spec.rollup.key]\n if (typeof kv === 'string' || typeof kv === 'number') intents.push({ into: spec.source, parentId: String(kv), field: spec.rollup.field })\n }\n return intents\n}\n\n/** #640 — resolve a `RollupDeleteIntent` back to its registry `spec`. The wave's per-intent\n * driver needs `spec.rollup.compute`, which `GraphBatch`'s metadata-only pin forbids batching —\n * so it's re-resolved here, post-boundary, instead of carried across it. `undefined` if the\n * intent's originating strategy was unregistered between collect time and wave time (residual\n * gap, freshness-only). */\nexport function findRollupSpecForIntent<S extends { source: string; rollup?: { from: string; field: string } }>(\n registry: { strategiesForSource(name: string): ReadonlyArray<{ spec: S }> } | undefined,\n collectionName: string,\n intent: RollupDeleteIntent,\n): S | undefined {\n return registry?.strategiesForSource(collectionName).find((s) => s.spec.source === intent.into && s.spec.rollup?.field === intent.field && s.spec.rollup?.from === collectionName)?.spec\n}\n\n/** One dedup ledger for a single wave — a target is recomputed at most once (mark-on-check). */\nexport class WaveContext {\n private readonly _seen = new Set<string>()\n seen(targetKey: string): boolean {\n if (this._seen.has(targetKey)) return true\n this._seen.add(targetKey)\n return false\n }\n}\n\n/** The slice of `Vault` the wave needs: the shared graph (the #553 zero-cost skip) and cached-\n * collection lookup — never constructs, since a touched collection is, by construction,\n * already open (it just fired `_onRecordMutated`). */\nexport interface VaultLike {\n readonly graph: ViaGraph\n _getCollection(name: string): Collection<Record<string, unknown>> | undefined\n /** #640 (#644 item 3) — structured wave-error surfacing, additive to the existing console.warn. */\n _emit(event: string, payload: unknown): void\n}\n\n/**\n * Run ONE dispatch wave for a completed batch: for each touched (collection, id), decrypt the\n * applied envelope (id threaded), then run the SAME `dispatchDerivations` +\n * `dispatchMaterializedViews` the local-write path uses — with a shared `WaveContext` so N\n * touched records feeding the SAME target recompute once. #553: a collection with no graph\n * out-edges (e.g. money-only) is skipped before any decrypt/dispatch async work.\n */\nexport async function runGraphDispatchWave(vault: VaultLike, batch: GraphBatch): Promise<void> {\n const wave = new WaveContext()\n for (const [collectionName, touch] of batch) {\n if (vault.graph.dependentsOf(collectionName).length === 0) continue\n const coll = vault._getCollection(collectionName)\n if (!coll) continue\n for (const id of touch.puts) {\n try {\n // Decrypt is INSIDE the per-id isolation boundary (whole-branch review Important\n // finding, #638): an undecryptable synced envelope (`TamperedError`) must not\n // escape `_getStoredRecordForDispatch` and abort the wave — that would propagate\n // through `_flushGraphBatch` and reject the surrounding `SyncEngine.pull`/`push`\n // AFTER records were already applied + meta persisted, starving every other\n // touched target in the same batch.\n const stored = await coll._getStoredRecordForDispatch(id)\n if (!stored) continue\n await coll.dispatchDerivations(id, stored.record, stored.version, wave)\n await coll.dispatchMaterializedViews(id, stored.record, wave)\n } catch (err) {\n // #638 Task 5 review mandate: one touched record's recompute must not abort the\n // whole wave (starving co-batched healthy targets) or the pull/push it's nested\n // inside. `PeriodClosedError` never reaches here — `putDerivedOutput` already\n // intercepts it at every output-write call site and turns it into a skip+event.\n // Anything else (a genuine decrypt failure, a derive()/executor bug, a schema\n // violation on the output, ...) is surfaced — not silently swallowed — via the\n // SAME console.warn channel `dispatchDerivations`/the MV executor already use for\n // their own non-strict-mode output failures, then isolated to just this one id.\n // #644 item 3: ADDITIVELY (never in place of the warn) emit a structured event too,\n // so a listener doesn't have to scrape console output to react to a wave failure.\n console.warn(`[via-dispatch] wave recompute failed for ${collectionName}/${id}:`, err)\n vault._emit('derivation:wave-error', { collection: collectionName, id, error: err })\n }\n }\n // #640 — delete-kind touches: the deleted child's rollup-parent intents, resolved (sync,\n // pre-invalidation) at collect time by `Collection._rollupDeleteIntents`. Same per-id\n // isolation as the puts loop above. #658: the wave now ALSO heals MV rows and array-shape\n // derivation output rows for the deleted child — parity with the local-delete boundary\n // (`Collection._doDelete`'s `!internal` block, which already calls all three). Still never\n // routed through `dispatchDerivations` (the mutation-choke-point.test.ts:85-99 pin — sync-\n // applied deletes never RE-DERIVE); `dispatchMaterializedViewsOnDelete`/\n // `dispatchArrayDerivationsOnDelete` only need `id` (MV refresh recomputes+diffs; array-\n // derivation reads its per-source sidecar) and never call `derive()`, so the pin holds.\n for (const [id, intents] of touch.deletes) {\n try {\n await coll._recomputeDeletedRollups(intents, wave)\n // #658: record-shape same-id outputs are left untouched (eraseRecordShapeToo defaults\n // false), matching local delete — the user deletes those directly if wanted.\n // #658: TODO dedup MV refresh per wave — `dispatchMaterializedViewsOnDelete` doesn't\n // accept a `WaveContext` (unlike the put-path `dispatchMaterializedViews`), so N deleted\n // children of one eager MV in a batch each trigger a full refresh pass. Threading `wave`\n // through would touch collection.ts's zero-slack kernel-surface ceiling for a perf-only\n // win; correctness doesn't depend on it (idempotent per source-id) — left as a follow-up.\n await coll.dispatchMaterializedViewsOnDelete(id)\n await coll.dispatchArrayDerivationsOnDelete(id)\n } catch (err) {\n console.warn(`[via-dispatch] wave delete-recompute failed for ${collectionName}/${id}:`, err)\n vault._emit('derivation:wave-error', { collection: collectionName, id, error: err })\n }\n }\n }\n}\n\n/** A record's post-freeze source mutation, for the `'derivation:skipped-frozen'` event\n * and the optional audit-trail entry. See {@link putDerivedOutput}. */\nexport interface DerivationSkippedFrozen {\n readonly source: { readonly collection: string; readonly id: string }\n readonly target: { readonly collection: string; readonly id: string }\n readonly period: string\n readonly endDate: string\n}\n\n/** The minimal put-capable shape `putDerivedOutput` needs. Any `Collection<T>` structurally\n * satisfies this — its real `options` type is a superset of what's declared here. */\nexport interface CollectionLike {\n put(id: string, value: unknown, options?: { readonly source?: string }): Promise<void>\n}\n\nexport interface PutDerivedOutputCtx {\n readonly emit: (ev: string, p: unknown) => void\n readonly source: { readonly collection: string; readonly id: string }\n readonly audit?: ((e: DerivationSkippedFrozen) => Promise<void>) | undefined\n}\n\n/**\n * Attempt a dispatch-driven output write. On `PeriodClosedError` (the closed-period\n * `beforePut` gate — `freezePeriod`/`archivePeriod` add no separate gate, per seam map\n * Part 7): SKIP (no `_ts` stamped — the gate throws before any write happens), emit\n * `'derivation:skipped-frozen'` on the event bus (ALWAYS), and append an audit-trail entry\n * when the with-history ledger is active. Returns `'written' | 'skipped-frozen'`. Any OTHER\n * error propagates unchanged — this helper narrows exactly one error class. The SOURCE\n * write is never wrapped through this helper — only derived-output writes are (§7).\n */\nexport async function putDerivedOutput(\n outColl: CollectionLike, id: string, value: unknown,\n ctx: PutDerivedOutputCtx,\n options?: { readonly source?: string },\n): Promise<'written' | 'skipped-frozen'> {\n try {\n await outColl.put(id, value, options)\n return 'written'\n } catch (err) {\n if (!(err instanceof PeriodClosedError)) throw err\n // Reach-around for the target collection's private `name` — the SAME pattern\n // `with-formula/materialized-views/executor.ts`'s `listOutputIds` already uses to\n // read a `Collection`'s private `adapter`/`vault`/`name` fields from outside the class.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const targetCollection = (outColl as any).name as string\n const event: DerivationSkippedFrozen = {\n source: ctx.source,\n target: { collection: targetCollection, id },\n period: err.periodName,\n endDate: err.endDate,\n }\n ctx.emit('derivation:skipped-frozen', event)\n if (ctx.audit) await ctx.audit(event)\n return 'skipped-frozen'\n }\n}\n\n/** Structural (no static import — kernel spine may not statically reach a with-* service,\n * the S4 gate recipe `check-architecture.mjs`'s port-layering check enforces) shape of the\n * with-history `LedgerStore.append` seam this helper needs. */\ninterface AuditLedgerLike {\n append(input: {\n readonly op: 'lifecycle'\n readonly collection: string\n readonly id: string\n readonly version: number\n readonly actor: string\n readonly payloadHash: string\n readonly reason?: string\n }): Promise<unknown>\n}\n\n/** @internal — the optional with-history ledger audit hook for `putDerivedOutput`, present\n * only when the ledger is active (mirrors every other kernel event's `if (this.ledger)`\n * gate). Encoded as a `'lifecycle'` entry — the existing \"non-data audit event\" op (the\n * same convention `forget`'s JSON-summary-in-`reason` entry uses; `ledger/entry.ts:88-104`). */\nexport function ledgerAuditHook(\n ledger: AuditLedgerLike | undefined, actor: string,\n): ((e: DerivationSkippedFrozen) => Promise<void>) | undefined {\n if (!ledger) return undefined\n return async (e) => {\n await ledger.append({\n op: 'lifecycle', collection: e.target.collection, id: e.target.id, version: 0, actor, payloadHash: '',\n reason: JSON.stringify({ event: 'derivation-skipped-frozen', ...e }),\n })\n }\n}\n\n/** `recomputeRollup`/`dispatchRollupsOnDelete`'s per-target write outcome (#638 Task 6):\n * `'written'`/`'skipped-frozen'` mirror {@link putDerivedOutput}'s result; `'noop'` covers\n * no-parent/no-change/deduped-by-wave — nothing to report either way. */\nexport type RollupOutcome = 'written' | 'skipped-frozen' | 'noop'\n\n/** Mutable accumulator `forgetDerivedFanout` writes into, one per `Vault.forget()` call — keeps\n * the per-ref loop's call site to a single line under vault.ts's tight kernel-surface ceiling.\n * Maps 1:1 onto `ForgetResult`'s additive fields (`with-audit/forget/strategy.ts`). */\nexport interface ForgetFanoutStats {\n recordsErased: number\n aggregatesRecomputed: number\n readonly residueFrozen: string[]\n /** #650 Task 5 (#648) — referencing records tombstoned via a `'ref'` edge's `cascade` policy. */\n lookupReferencesCascaded: number\n /** #650 Task 5 (#648) — referencing fields cleared via a `'ref'` edge's `nullify` policy. */\n lookupReferencesNullified: number\n /** #650 Task 5 review (Important fix) — `'ref'` edges whose compare-key could NOT be resolved,\n * even from the LIVE pre-shred row (the backing row itself is unreadable) — propagation was\n * skipped for these, reported here so the skip is never silent. `backing:key:collection.field`\n * entries, one per un-propagated edge. */\n readonly lookupReferencesResidue: string[]\n /** #776/#782/#785 — `outputCollection:id` MV-output rows that survived erasure invalidation\n * (eager tombstone leg AND lazy/manual `invalidateMVAtRest`) despite belonging to the\n * forgotten subject, because the ownership stamp could not be decoded (undecodable under\n * the default DEK — e.g. elevated above tier 0 on a tiered output collection). Ownership\n * UNCONFIRMED. Never erased, but surfaced here rather than silently skipped. */\n readonly derivedResidueUndecodable: string[]\n /** #782/#785 — `outputCollection:id` MV-output rows that decoded and stamp-matched but whose\n * `_internalDelete` declined (the #718 tier-elevation gate). Ownership CONFIRMED, erasure\n * declined — a real silent survival, surfaced here rather than silently skipped. */\n readonly derivedResidueDeclined: string[]\n}\n\n/**\n * #622 — after `_writeTombstone(ref.id, actor)` erases the forgotten subject's own record, fan\n * out to its derived residue via the graph (spec §5): record-grain artifacts (MV rows,\n * array-shape derivation rows, same-id record-shape derivation copies) are ERASED through the\n * SAME `!internal` housekeeping-bypass machinery the ordinary delete path uses (no user\n * `onDelete` re-fires — the shred-is-not-a-domain-delete property `_writeTombstone` protects);\n * aggregate-grain rollups are RECOMPUTED without the forgotten contribution in open periods, or\n * skip+audit (via `putDerivedOutput`, already wired into the rollup/MV output paths) in frozen\n * ones. Mutates `stats` in place. `envelope` is `ref`'s PRE-tombstone envelope, decoded only if\n * a rollup edge is actually present — the #553 zero-cost-skip discipline: no decrypt for the\n * common case of a forgotten record with no aggregate-grain consumer, and no work at all when\n * `ref.collection` has no graph out-edges. `lookupCompareKeys` is the `'ref'` edges' compare-key\n * map, resolved from the LIVE row BEFORE any shred (`VaultLinks.checkLookupRefsRestrict`'s return\n * value — `Vault.forget()`'s pre-shred restrict check doubles as the live-resolve pass) — see\n * {@link applyLookupRefsFanout}.\n */\nexport async function forgetDerivedFanout(\n vault: VaultLike,\n ref: { readonly collection: string; readonly id: string },\n envelope: EncryptedEnvelope | null,\n stats: ForgetFanoutStats,\n lookupCompareKeys: ReadonlyMap<string, string | undefined>,\n): Promise<void> {\n const coll = vault._getCollection(ref.collection)\n\n // #761 item 4 — drive the MV arm off `dispatchMaterializedViewsOnDelete` UNCONDITIONALLY,\n // ABOVE the `edges` check below: `registry.edges()` drops the same-collection\n // partition-disjoint MV edge (registry.ts's `sources.length === 0 → continue`), so a\n // same-collection MV's source collection never appears in `vault.graph`'s derived-artifact\n // edges even though the MV IS registered — forget() would otherwise never reach it.\n // `dispatchMaterializedViewsOnDelete` self-guards O(1) via `mvsForSource` (a no-op when\n // this collection isn't an MV source), so this is safe to call unconditionally. Safe to\n // route through the eager executor's tombstone leg ONLY because that leg is now\n // stamp-scoped (#762) — before that fix this would have opened a NEW forget-time\n // data-loss path into the unscoped tombstone diff.\n if (coll) {\n const mv = await coll.dispatchMaterializedViewsOnDelete(ref.id)\n stats.recordsErased += mv.deleted\n stats.derivedResidueUndecodable.push(...mv.residueUndecodable)\n stats.derivedResidueDeclined.push(...mv.residueDeclined)\n }\n\n const edges = vault.graph.derivedArtifactsOf(ref.collection)\n if (edges.length === 0 || !coll) return\n\n // #650 Task 5 (#648) — 'ref' cascade/nullify propagate ADDITIVELY, here, AFTER the shred\n // (restrict already refused BEFORE any shred — the caller's pre-tombstone check, spec §4).\n // The I/O shell (loop shape, collection accessor) is duplicated, not imported, from\n // `VaultLinks.applyLookupRefsPropagation`/`checkLookupRefsRestrict` (with-shape/links/\n // vault-facade.ts) — the kernel spine may not statically import a with-* service\n // (port-layering, the #638 Task 5 via/dispatch.ts precedent); `vault._getCollection` is\n // cached-only while `VaultLinks`' accessor constructs. The pure match predicate itself is\n // shared through the port seam (#651 Task 3 — `matchesReferencingValue`, `port/with/\n // lookup-strategy.ts`), so only the shell, not the coercion logic, stays duplicated. A\n // referencing edge whose dimension uses a non-default `key` (matrix tier only) needs the\n // backing row's OWN value at that field, not its PUT-id — the row is ALREADY tombstoned by\n // now, so it's read from `lookupCompareKeys`, resolved by the caller from the LIVE row\n // BEFORE the shred (#650 Task 5 review, Important fix — eliminates the post-shred\n // envelope-decode dependency this used to have, which silently skipped propagation whenever\n // that decode failed).\n if (edges.some((e) => e.kind === 'ref')) {\n const { cascaded, nullified, residue } = await applyLookupRefsFanout(vault, ref.collection, ref.id, lookupCompareKeys)\n stats.lookupReferencesCascaded += cascaded\n stats.lookupReferencesNullified += nullified\n stats.lookupReferencesResidue.push(...residue)\n }\n\n if (edges.some((e) => e.kind === 'derivation')) {\n // #622 review Finding 1: count REAL erasures (dispatchArrayDerivationsOnDelete's own\n // `_internalDelete`-backed tally), not the derivation EDGE count — an edge exists whenever\n // this collection is ANY trigger (source/sources[]/triggerBy), but the same-id record-shape\n // guard only erases for `spec.source === this.name`, and `derive()` may never have produced\n // an output row (optional-skip) in the first place. Both cases must contribute 0, not +1.\n stats.recordsErased += await coll.dispatchArrayDerivationsOnDelete(ref.id, true)\n }\n\n if (envelope && edges.some((e) => e.kind === 'rollup')) {\n const priorRecord = await coll._decodeEnvelope(envelope, ref.id)\n if (priorRecord) {\n for (const r of await coll.dispatchRollupsOnDelete(ref.id, priorRecord)) {\n if (r.outcome === 'written') stats.aggregatesRecomputed += 1\n else if (r.outcome === 'skipped-frozen') stats.residueFrozen.push(`${r.into}:${r.parentId}`)\n }\n }\n }\n}\n\n/**\n * Apply `cascade`/`nullify` propagation for `backing`'s non-restrict `'ref'` edges — the\n * forget-path counterpart of `VaultLinks.applyLookupRefsPropagation` (I/O shell duplicated, not\n * imported, match predicate shared via the port — see {@link forgetDerivedFanout}'s call site\n * comment). `restrict` edges are skipped here: the\n * forget loop's `checkLookupRefsRestrict`-equivalent call already refused (or the reference no\n * longer existed) BEFORE `_writeTombstone` ran, so by the time this runs only cascade/nullify\n * remain to propagate. `compareKeys` is the non-`'id'`-`keyField` compare-value map, resolved by\n * the caller from the LIVE row BEFORE the shred (#650 Task 5 review, Important fix) — the live row\n * is already shredded by the time THIS function runs, so it can no longer resolve one itself. A\n * `keyField` absent from (or `undefined` in) the map means that live resolve failed too — the edge\n * is reported as residue instead of silently skipped (never a bare `continue` with no trace).\n */\nasync function applyLookupRefsFanout(\n vault: VaultLike,\n backing: string,\n key: string,\n compareKeys: ReadonlyMap<string, string | undefined>,\n): Promise<{ cascaded: number; nullified: number; residue: string[] }> {\n let cascaded = 0\n let nullified = 0\n const residue: string[] = []\n for (const { referencing, onDelete, keyField } of vault.graph.referencingEdgesOf(backing)) {\n if (onDelete === 'restrict') continue\n const compareKey = keyField === 'id' ? key : compareKeys.get(keyField)\n if (compareKey === undefined) {\n residue.push(`${backing}:${key}:${referencing.collection}.${referencing.field}`)\n continue\n }\n const coll = vault._getCollection(referencing.collection)\n if (!coll) continue\n const matches = (await coll.list()).filter((rec) => matchesReferencingValue(rec, referencing.field, compareKey))\n for (const rec of matches) {\n const id = rec['id'] as string | undefined\n if (id === undefined) continue\n if (onDelete === 'cascade') {\n await coll.delete(id)\n cascaded++\n } else if (onDelete === 'nullify') {\n await coll.put(id, { ...rec, [referencing.field]: null })\n nullified++\n }\n }\n }\n return { cascaded, nullified, residue }\n}\n\n/**\n * Value-equality for a single self-write reverse-denorm field. Scalars\n * compare by identity; objects by canonical JSON (denorm values should be\n * deterministically shaped). Used as the cycle guard — when every denorm\n * field already matches, no write is issued and the self-write recursion ends.\n */\nexport function selfWriteFieldEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false\n try {\n return JSON.stringify(a) === JSON.stringify(b)\n } catch {\n return false\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA+BO,SAAS,uBACd,cACA,QACM;AACN,MAAI,CAAC,gBAAgB,OAAO,KAAK,YAAY,EAAE,WAAW,EAAG;AAC7D,MAAI,CAAC,UAAU,OAAO,WAAW,SAAU;AAE3C,QAAM,MAAM;AACZ,aAAW,CAAC,OAAO,IAAI,KAAK,OAAO,QAAQ,YAAY,GAAG;AACxD,QAAI,KAAK,kBAAkB,MAAO;AAClC,UAAM,QAAQ,IAAI,IAAY,KAAK,IAAI;AACvC,UAAM,SAAS,UAAU,KAAK,KAAK;AACnC,eAAW,SAAS,QAAQ;AAC1B,UAAI,UAAU,UAAa,UAAU,KAAM;AAC3C,YAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AACnD,iBAAW,QAAQ,OAAO;AACxB,YAAI,OAAO,SAAS,SAAU;AAC9B,YAAI,CAAC,MAAM,IAAI,IAAI,GAAG;AACpB,gBAAM,IAAI,qBAAqB,KAAK,MAAM,OAAO,IAAI;AAAA,QACvD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAoBO,SAAS,kBACd,gBACA,OACA,yBACA,sBACA,qBACuB;AACvB,QAAM,eAAe,wBAAwB,IAAI,cAAc;AAC/D,MAAI,gBAAgB,SAAS,cAAc;AACzC,UAAM,OAAO,aAAa,KAAK;AAC/B,UAAM,OAA2C,OAAO,QAAQ,KAAK,KAAK,EAAE;AAAA,MAC1E,CAAC,CAAC,KAAK,MAAM,OAAO,EAAE,KAAK,QAAQ,GAAI,OAAkC;AAAA,IAC3E;AACA,UAAM,SAAyB;AAAA,MAC7B,WAA+B;AAC7B,eAAO;AAAA,MACT;AAAA,MACA,WAAW,IAAqB;AAC9B,eAAO,KAAK,KAAK,CAAC,MAAM,EAAE,KAAK,MAAM,EAAE;AAAA,MACzC;AAAA,IACF;AACA,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