@directive-run/core 1.14.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-utils.cjs +1 -1
- package/dist/adapter-utils.d.cts +2 -2
- package/dist/adapter-utils.d.ts +2 -2
- package/dist/adapter-utils.js +1 -1
- package/dist/{chunk-I722BZA5.js → chunk-3ETCZLAY.js} +3 -3
- package/dist/chunk-3ETCZLAY.js.map +1 -0
- package/dist/{chunk-Q2VZPURY.cjs → chunk-4MTC4BSK.cjs} +2 -2
- package/dist/chunk-4MTC4BSK.cjs.map +1 -0
- package/dist/{chunk-644QZVTT.js → chunk-F5JPF4YX.js} +3 -3
- package/dist/chunk-F5JPF4YX.js.map +1 -0
- package/dist/{chunk-X7G7UBXU.cjs → chunk-JGPPJV5P.cjs} +3 -3
- package/dist/chunk-JGPPJV5P.cjs.map +1 -0
- package/dist/{chunk-2FF6QGOA.js → chunk-O4GQEV4G.js} +2 -2
- package/dist/chunk-O4GQEV4G.js.map +1 -0
- package/dist/{chunk-ENZEHIL7.cjs → chunk-Q5UTBMX2.cjs} +3 -3
- package/dist/chunk-Q5UTBMX2.cjs.map +1 -0
- package/dist/{chunk-T4TRJEJN.cjs → chunk-RWFKUNF7.cjs} +2 -2
- package/dist/chunk-RWFKUNF7.cjs.map +1 -0
- package/dist/chunk-RWJV7QLM.js +3 -0
- package/dist/chunk-RWJV7QLM.js.map +1 -0
- package/dist/{chunk-NPX5EKPP.cjs → chunk-SUCLMJSZ.cjs} +3 -3
- package/dist/chunk-SUCLMJSZ.cjs.map +1 -0
- package/dist/{chunk-AV6S27PU.js → chunk-YYFRZJO2.js} +2 -2
- package/dist/chunk-YYFRZJO2.js.map +1 -0
- package/dist/{index-DErb8sV3.d.cts → index-D_oNDe4l.d.cts} +1 -1
- package/dist/{index-C8M6pj9H.d.ts → index-c5wGodzh.d.ts} +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/internals.cjs +1 -1
- package/dist/internals.d.cts +4 -4
- package/dist/internals.d.ts +4 -4
- package/dist/internals.js +1 -1
- package/dist/plugins/index.cjs +2 -2
- package/dist/plugins/index.cjs.map +1 -1
- package/dist/plugins/index.d.cts +2 -2
- package/dist/plugins/index.d.ts +2 -2
- package/dist/plugins/index.js +1 -1
- package/dist/plugins/index.js.map +1 -1
- package/dist/{plugins-BIzXaYbg.d.ts → plugins-BpNMkJRw.d.cts} +47 -8
- package/dist/{plugins-BIzXaYbg.d.cts → plugins-BpNMkJRw.d.ts} +47 -8
- package/dist/{predicate-BxQVf0ug.d.ts → predicate-BinuVL33.d.ts} +1 -1
- package/dist/{predicate-Bnx3LN7P.d.cts → predicate-DN1MnDbi.d.cts} +1 -1
- package/dist/system-MMCZKPI2.js +2 -0
- package/dist/{system-A6VYKLVF.js.map → system-MMCZKPI2.js.map} +1 -1
- package/dist/system-RHSYFDOB.cjs +2 -0
- package/dist/{system-CDJMD5O5.cjs.map → system-RHSYFDOB.cjs.map} +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/worker.cjs +1 -1
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +1 -1
- package/dist/worker.d.ts +1 -1
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-2FF6QGOA.js.map +0 -1
- package/dist/chunk-644QZVTT.js.map +0 -1
- package/dist/chunk-AV6S27PU.js.map +0 -1
- package/dist/chunk-ENZEHIL7.cjs.map +0 -1
- package/dist/chunk-I722BZA5.js.map +0 -1
- package/dist/chunk-NPX5EKPP.cjs.map +0 -1
- package/dist/chunk-Q2VZPURY.cjs.map +0 -1
- package/dist/chunk-R2GHSCTR.js +0 -3
- package/dist/chunk-R2GHSCTR.js.map +0 -1
- package/dist/chunk-T4TRJEJN.cjs.map +0 -1
- package/dist/chunk-X7G7UBXU.cjs.map +0 -1
- package/dist/system-A6VYKLVF.js +0 -2
- package/dist/system-CDJMD5O5.cjs +0 -2
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/system-proxies.ts","../src/core/system-module-transform.ts","../src/core/system.ts"],"names":["SEPARATOR","NODE_INSPECT_CUSTOM","buildHardenedSnapshot","config","snapshot","key","createHardenedProxy","_","prop","BLOCKED_PROPS","value","moduleFactsProxyCache","namespacedFactsProxyCache","namespacedDeriveProxyCache","moduleDeriveProxyCache","crossModuleFactsProxyCache","moduleEventsProxyCache","createModuleFactsProxy","facts","namespace","namespaceCache","cached","proxy","dev_true_default","nonJsonType","detectNonJsonValueType","warnNonJsonFactAssignment","createNamespacedFactsProxy","modulesMap","getModuleNames","createCrossModuleFactsProxy","selfNamespace","depNamespaces","cacheKey","depNamesSet","allKeys","createModuleDeriveProxy","derive","createNamespacedDeriveProxy","createNamespacedEventsProxy","engine","moduleEventsProxy","eventName","payload","toInternalKey","rest","denormalizeFlatKeys","flatData","result","sepIndex","ns","local","createScopedFactsProxy","hasCrossModuleDeps","prefixKey","isAlreadyPrefixed","prefixPredicateSpec","spec","out","clause","fact","freezeSpec","src","combinator","list","child","prefixPivot","targetNamespace","EMPTY_DEP_SET","flattened","k","v","normalizePredicateDefs","mod","constraints","changed","next","raw","def","obj","c","isTemplate","fn","evaluateTemplate","isPredicate","memoized","memoizePredicate","events","hasHandler","hasPatch","handler","event","applyPatch","effects","nonEmpty","rec","prefixSchema","prefixInit","moduleFactsProxy","prefixDerive","isObj","isDerivationWithMeta","meta","wrapper","factsProxy","deriveProxy","prefixEventHandlers","prefixConstraints","constraint","constraintDef","isWhenFn","dep","prefixResolvers","resolver","wrapCtx","ctx","resolverDef","req","reqs","prefixEffects","effect","effectDef","prev","prevProxy","prefixHistory","snapshotModulesSet","e","prefixModuleDefinition","options","rawMod","topologicalSort","namespaces","namespacesSet","visited","visiting","path","visit","cycleStart","cycle","depNamespace","collectNamespaceKeys","keys","createSystem","createSingleModuleSystem","namedOptions","mods","createNamespacedSystem","moduleNamespaces","historyConfig","name","orderedNamespaces","initOrder","explicitOrder","missingModules","history","trace","errorBoundary","applyZeroConfigDefaults","moduleNamesCache","flatModules","m","hydratedFacts","applyNamespacedFacts","namespacedFacts","isPrototypeSafe","createEngine","namespaceKeysMap","namespacedFactsProxy","namespacedDeriveProxy","namespacedEventsProxy","tickInterval","tickMs","system","loader","tickEventKey","derivationId","ids","listener","internalIds","id","callback","predicate","internalOptions","moduleDef","flat","bindEnginePassthroughs","warnIfNotStarted","overridableMethods","method","eventsProxy"],"mappings":"8LAuBO,IAAMA,CAAAA,CAAY,IAAA,CAgCnBC,EAAAA,CAAsB,MAAA,CAAO,IAAI,4BAA4B,CAAA,CASnE,SAASC,EAAAA,CAAsBC,EAAsC,CACnE,GAAI,CAACA,CAAAA,CAAO,QACV,OAAO,EAAC,CAEV,IAAMC,EAAoC,EAAC,CAC3C,IAAA,IAAWC,CAAAA,IAAOF,EAAO,OAAA,EAAQ,CAC/BC,CAAAA,CAASC,CAAG,EAAIF,CAAAA,CAAO,GAAA,CAAIE,CAAG,CAAA,CAGhC,OAAOD,CACT,CA2BA,SAASE,CAAAA,CAAsCH,CAAAA,CAAgC,CAC7E,OAAO,IAAI,MAAM,EAAC,CAAQ,CACxB,GAAA,CAAII,EAAGC,CAAAA,CAAuB,CAC5B,GAAI,OAAOA,GAAS,QAAA,CAGlB,OAAIA,CAAAA,GAASP,EAAAA,CACJ,IAAMC,EAAAA,CAAsBC,CAAM,CAAA,CAE3C,MAAA,CAEF,GAAI,CAAAM,CAAAA,CAAc,GAAA,CAAID,CAAI,EAI1B,OAAOL,CAAAA,CAAO,GAAA,CAAIK,CAAI,CACxB,CAAA,CACA,GAAA,CAAID,CAAA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AAOA,CAAAA,CAAU,KAAA,CACjB,OAAA,CAASA,CAAAA,CAAU,OACrB,CAAC,EACH,CAEF,CAAA,CAEA,OAAAE,EAAAA,CAAuBb,CAAAA,CAAQpI,CAAM,CAAA,CACrCkJ,EAAAA,CAAiBd,CAAM,CAAA,CAEhBA,CACT","file":"chunk-644QZVTT.js","sourcesContent":["/**\n * Proxy factory functions for system-level namespace translation.\n *\n * Extracted from system.ts to reduce file size. All functions are pure\n * proxy factories — they create proxies that translate between unprefixed\n * module keys and prefixed internal keys (e.g., `token` ↔ `auth::token`).\n *\n * @internal\n */\n\nimport isDevelopment from \"#is-development\";\nimport {\n BLOCKED_PROPS,\n detectNonJsonValueType,\n warnNonJsonFactAssignment,\n} from \"./tracking.js\";\nimport type { ModulesMap } from \"./types.js\";\n\n/**\n * Namespace separator for internal key prefixing (e.g., \"auth::token\").\n *\n * @internal\n */\nexport const SEPARATOR = \"::\";\n\n// ============================================================================\n// Hardened Proxy Factory\n// ============================================================================\n\n/**\n * Configuration for creating a hardened proxy with consistent security traps.\n *\n * @internal\n */\ninterface HardenedProxyConfig {\n /** Return the value for a string property access */\n get: (prop: string) => unknown;\n /** Handle property assignment. Omit for read-only proxies (returns false). */\n set?: (prop: string, value: unknown) => boolean;\n /** Check if a string property exists */\n has?: (prop: string) => boolean;\n /** Return all own keys for enumeration */\n ownKeys?: () => string[];\n /** Handle property deletion. Omit to reject deletions. */\n delete?: (prop: string) => boolean;\n}\n\n/**\n * Symbol used by Node.js's `util.inspect` (and vitest's pretty-format)\n * to ask an object for a custom inspection representation. Returning a\n * plain-object snapshot here avoids reflective walks on the proxy that\n * crash printers (e.g. `printComplexValue` reading `val.constructor.name`).\n *\n * @internal\n */\nconst NODE_INSPECT_CUSTOM = Symbol.for(\"nodejs.util.inspect.custom\");\n\n/**\n * Build a plain-object snapshot from a hardened proxy config. Used as the\n * inspection hook so that printers see real keys/values instead of trapping\n * on the proxy.\n *\n * @internal\n */\nfunction buildHardenedSnapshot(config: HardenedProxyConfig): unknown {\n if (!config.ownKeys) {\n return {};\n }\n const snapshot: Record<string, unknown> = {};\n for (const key of config.ownKeys()) {\n snapshot[key] = config.get(key);\n }\n\n return snapshot;\n}\n\n/**\n * Create a proxy with consistent security hardening.\n *\n * Every proxy created by this factory includes:\n * - Symbol access returns `undefined` (except the inspection hook below)\n * - `Symbol.for('nodejs.util.inspect.custom')` returns a function that\n * produces a plain-object snapshot, so vitest pretty-format / Node's\n * `util.inspect` / `console.log` render the proxy correctly without\n * tripping on reflective walks (e.g. `printComplexValue` reading\n * `val.constructor.name`).\n * - `Symbol.toPrimitive` is intentionally NOT set: the get trap returns\n * `undefined` for it so JS falls back to default `toString`/`valueOf`\n * coercion. Returning a snapshot object here would `TypeError` because\n * the protocol requires a primitive return.\n * - BLOCKED_PROPS (`__proto__`, `constructor`, `prototype`) rejected\n * - `defineProperty` returns `false`\n * - `getPrototypeOf` returns `null`\n * - `setPrototypeOf` returns `false`\n *\n * Note: per the Risk reviewer we deliberately do NOT add a `toJSON` shim —\n * that would change `JSON.stringify(proxy)` semantics for users who already\n * rely on the existing shape.\n *\n * @internal\n */\nfunction createHardenedProxy<T extends object>(config: HardenedProxyConfig): T {\n return new Proxy({} as T, {\n get(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n // Inspection hook: return a snapshot function so printers\n // don't walk the proxy reflectively (which crashes pretty-format).\n if (prop === NODE_INSPECT_CUSTOM) {\n return () => buildHardenedSnapshot(config);\n }\n return undefined;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n\n return config.get(prop);\n },\n set(_, prop: string | symbol, value: unknown) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return config.set ? config.set(prop, value) : false;\n },\n has(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return config.has ? config.has(prop) : false;\n },\n deleteProperty(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return config.delete ? config.delete(prop) : false;\n },\n ownKeys() {\n return config.ownKeys ? config.ownKeys() : [];\n },\n getOwnPropertyDescriptor(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n if (config.has && typeof prop === \"string\" && config.has(prop)) {\n return { configurable: true, enumerable: true };\n }\n\n return undefined;\n },\n defineProperty() {\n return false;\n },\n getPrototypeOf() {\n return null;\n },\n setPrototypeOf() {\n return false;\n },\n });\n}\n\n// ============================================================================\n// Proxy Cache (Performance)\n// ============================================================================\n\n/**\n * WeakMap to cache module facts proxies. Keyed by the facts store object.\n * Inner map is keyed by namespace string.\n */\nconst moduleFactsProxyCache = new WeakMap<\n Record<string, unknown>,\n Map<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache namespaced facts proxies.\n */\nconst namespacedFactsProxyCache = new WeakMap<\n Record<string, unknown>,\n Record<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache namespaced derive proxies.\n */\nconst namespacedDeriveProxyCache = new WeakMap<\n Record<string, unknown>,\n Record<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache module derive proxies.\n */\nconst moduleDeriveProxyCache = new WeakMap<\n Record<string, unknown>,\n Map<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache cross-module facts proxies.\n * Keyed by facts store, then by \"selfNamespace|depKeys\" string.\n */\nconst crossModuleFactsProxyCache = new WeakMap<\n Record<string, unknown>,\n Map<string, Record<string, Record<string, unknown>>>\n>();\n\n/**\n * WeakMap to cache module events proxies.\n */\nconst moduleEventsProxyCache = new WeakMap<\n // biome-ignore lint/suspicious/noExplicitAny: Engine type for cache key\n any,\n Map<string, Record<string, (payload?: Record<string, unknown>) => void>>\n>();\n\n// ============================================================================\n// Module Facts Proxy\n// ============================================================================\n\n/**\n * Create a proxy for a single module's facts (used in init, event handlers).\n * Translates unprefixed keys to prefixed: `token` → `auth::token`\n *\n * Proxies are cached per facts store and namespace for performance.\n *\n * @param facts - The flat facts store\n * @param namespace - The module namespace for key prefixing\n * @returns A proxy that translates property access to prefixed keys\n *\n * @internal\n */\nexport function createModuleFactsProxy(\n facts: Record<string, unknown>,\n namespace: string,\n): Record<string, unknown> {\n // Check cache first\n let namespaceCache = moduleFactsProxyCache.get(facts);\n if (namespaceCache) {\n const cached = namespaceCache.get(namespace);\n if (cached) {\n return cached;\n }\n } else {\n namespaceCache = new Map();\n moduleFactsProxyCache.set(facts, namespaceCache);\n }\n\n const proxy = createHardenedProxy<Record<string, unknown>>({\n get: (prop) => {\n // Reserved properties bypass namespace prefixing (used by engine internals)\n if (prop === \"$store\" || prop === \"$snapshot\") {\n return facts[prop];\n }\n\n return facts[`${namespace}${SEPARATOR}${prop}`];\n },\n set: (prop, value) => {\n // Dev-mode: warn (once per path/type) when assigning non-JSON values\n // that break reactivity. See `warnNonJsonFactAssignment` in tracking.ts.\n if (isDevelopment) {\n const nonJsonType = detectNonJsonValueType(value);\n if (nonJsonType) {\n warnNonJsonFactAssignment(`${namespace}.${prop}`, nonJsonType);\n }\n }\n\n facts[`${namespace}${SEPARATOR}${prop}`] = value;\n\n return true;\n },\n has: (prop) => `${namespace}${SEPARATOR}${prop}` in facts,\n delete: (prop) => {\n delete facts[`${namespace}${SEPARATOR}${prop}`];\n\n return true;\n },\n });\n\n namespaceCache.set(namespace, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Namespaced Facts Proxy\n// ============================================================================\n\n/**\n * Create a nested proxy for namespaced facts access.\n * `facts.auth.token` → reads `auth::token` from flat store\n *\n * Uses Set for O(1) namespace lookups and caches the outer proxy.\n *\n * @param facts - The flat facts store\n * @param modulesMap - Map of module namespaces to module definitions\n * @param getModuleNames - Function returning current module names (supports dynamic registration)\n * @returns A proxy that delegates to per-module facts proxies\n *\n * @internal\n */\nexport function createNamespacedFactsProxy(\n facts: Record<string, unknown>,\n modulesMap: ModulesMap,\n getModuleNames: () => string[],\n): Record<string, Record<string, unknown>> {\n // Check cache first\n const cached = namespacedFactsProxyCache.get(facts);\n if (cached) {\n return cached;\n }\n\n const proxy = createHardenedProxy<Record<string, Record<string, unknown>>>({\n get: (namespace) => {\n if (!Object.hasOwn(modulesMap, namespace)) {\n return undefined;\n }\n\n return createModuleFactsProxy(facts, namespace);\n },\n has: (namespace) => Object.hasOwn(modulesMap, namespace),\n ownKeys: () => getModuleNames(),\n });\n\n namespacedFactsProxyCache.set(facts, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Cross-Module Facts Proxy\n// ============================================================================\n\n/**\n * Create a proxy for cross-module facts access with \"self\" for own module.\n * `facts.self.users` → reads own module's facts\n * `facts.auth.token` → reads dependency module's facts\n *\n * Used when a module has crossModuleDeps defined.\n *\n * @param facts - The flat facts store\n * @param selfNamespace - The namespace of the module that owns this proxy\n * @param depNamespaces - Array of declared dependency namespaces\n * @returns A proxy that provides `self` and declared dependency access\n *\n * @internal\n */\nexport function createCrossModuleFactsProxy(\n facts: Record<string, unknown>,\n selfNamespace: string,\n depNamespaces: string[],\n): Record<string, Record<string, unknown>> {\n // depNamespaces comes from Object.keys() which has stable order per module,\n // so join is sufficient (no need to sort)\n const cacheKey = `${selfNamespace}|${depNamespaces.join(\",\")}`;\n\n // Check cache first\n let namespaceCache = crossModuleFactsProxyCache.get(facts);\n if (namespaceCache) {\n const cached = namespaceCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n } else {\n namespaceCache = new Map();\n crossModuleFactsProxyCache.set(facts, namespaceCache);\n }\n\n const depNamesSet = new Set(depNamespaces);\n const allKeys = [\"self\", ...depNamespaces];\n\n const proxy = createHardenedProxy<Record<string, Record<string, unknown>>>({\n get: (key) => {\n // \"self\" maps to own module's namespace\n if (key === \"self\") {\n return createModuleFactsProxy(facts, selfNamespace);\n }\n\n // Check if it's a declared dependency\n if (depNamesSet.has(key)) {\n return createModuleFactsProxy(facts, key);\n }\n\n // Dev-mode warning for undeclared cross-module access\n if (isDevelopment) {\n console.warn(\n `[Directive] Module \"${selfNamespace}\" accessed undeclared cross-module property \"${key}\". ` +\n `Add it to crossModuleDeps or use \"facts.self.${key}\" for own module facts.`,\n );\n }\n\n return undefined;\n },\n has: (key) => key === \"self\" || depNamesSet.has(key),\n ownKeys: () => allKeys,\n });\n\n namespaceCache.set(cacheKey, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Module Derive Proxy\n// ============================================================================\n\n/**\n * Create a proxy for a single module's derivations.\n * Translates unprefixed keys to prefixed: `status` → `auth::status`\n *\n * Proxies are cached per derive store and namespace for performance.\n *\n * @param derive - The flat derivations store\n * @param namespace - The module namespace for key prefixing\n * @returns A read-only proxy that translates property access to prefixed keys\n *\n * @internal\n */\nexport function createModuleDeriveProxy(\n derive: Record<string, unknown>,\n namespace: string,\n): Record<string, unknown> {\n // Check cache first\n let namespaceCache = moduleDeriveProxyCache.get(derive);\n if (namespaceCache) {\n const cached = namespaceCache.get(namespace);\n if (cached) {\n return cached;\n }\n } else {\n namespaceCache = new Map();\n moduleDeriveProxyCache.set(derive, namespaceCache);\n }\n\n const proxy = createHardenedProxy<Record<string, unknown>>({\n get: (prop) => derive[`${namespace}${SEPARATOR}${prop}`],\n has: (prop) => `${namespace}${SEPARATOR}${prop}` in derive,\n });\n\n namespaceCache.set(namespace, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Namespaced Derive Proxy\n// ============================================================================\n\n/**\n * Create a nested proxy for namespaced derivations access.\n * `derive.auth.status` → reads `auth::status` from flat derive\n *\n * Uses Set for O(1) namespace lookups and caches the outer proxy.\n *\n * @param derive - The flat derivations store\n * @param modulesMap - Map of module namespaces to module definitions\n * @param getModuleNames - Function returning current module names\n * @returns A read-only proxy that delegates to per-module derive proxies\n *\n * @internal\n */\nexport function createNamespacedDeriveProxy(\n derive: Record<string, unknown>,\n modulesMap: ModulesMap,\n getModuleNames: () => string[],\n): Record<string, Record<string, unknown>> {\n // Check cache first\n const cached = namespacedDeriveProxyCache.get(derive);\n if (cached) {\n return cached;\n }\n\n const proxy = createHardenedProxy<Record<string, Record<string, unknown>>>({\n get: (namespace) => {\n if (!Object.hasOwn(modulesMap, namespace)) {\n return undefined;\n }\n\n return createModuleDeriveProxy(derive, namespace);\n },\n has: (namespace) => Object.hasOwn(modulesMap, namespace),\n ownKeys: () => getModuleNames(),\n });\n\n namespacedDeriveProxyCache.set(derive, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Namespaced Events Proxy\n// ============================================================================\n\n/**\n * Create a nested proxy for namespaced events access.\n * `events.auth.login({ token })` → dispatches `{ type: \"auth::login\", token }`\n *\n * Uses Set for O(1) namespace lookups and caches proxies for performance.\n *\n * @param engine - The engine instance (used for dispatch)\n * @param modulesMap - Map of module namespaces to module definitions\n * @param getModuleNames - Function returning current module names\n * @returns A read-only proxy that returns event dispatcher functions per namespace\n *\n * @internal\n */\nexport function createNamespacedEventsProxy(\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n engine: any,\n modulesMap: ModulesMap,\n getModuleNames: () => string[],\n): Record<string, Record<string, (payload?: Record<string, unknown>) => void>> {\n // Get or create the namespace cache for this engine\n let namespaceCache = moduleEventsProxyCache.get(engine);\n if (!namespaceCache) {\n namespaceCache = new Map();\n moduleEventsProxyCache.set(engine, namespaceCache);\n }\n\n return createHardenedProxy<\n Record<string, Record<string, (payload?: Record<string, unknown>) => void>>\n >({\n get: (namespace) => {\n if (!Object.hasOwn(modulesMap, namespace)) {\n return undefined;\n }\n\n // Check cache for this namespace's event proxy\n const cached = namespaceCache!.get(namespace);\n if (cached) {\n return cached;\n }\n\n // Create and cache the module events proxy\n const moduleEventsProxy = createHardenedProxy<\n Record<string, (payload?: Record<string, unknown>) => void>\n >({\n get: (eventName) => {\n return (payload?: Record<string, unknown>) => {\n engine.dispatch({\n type: `${namespace}${SEPARATOR}${eventName}`,\n ...payload,\n });\n };\n },\n });\n\n namespaceCache!.set(namespace, moduleEventsProxy);\n\n return moduleEventsProxy;\n },\n has: (namespace) => Object.hasOwn(modulesMap, namespace),\n ownKeys: () => getModuleNames(),\n });\n}\n\n// ============================================================================\n// Key Conversion Helpers\n// ============================================================================\n\n/**\n * Convert a namespaced key (e.g., \"auth.status\") to internal prefixed format (\"auth::status\").\n * If the key is already in prefixed format, returns it unchanged.\n *\n * @param key - The key to convert (dot-separated or already prefixed)\n * @returns The internal prefixed key\n *\n * @example\n * toInternalKey(\"auth.status\") // → \"auth::status\"\n * toInternalKey(\"auth::status\") // → \"auth::status\" (unchanged)\n * toInternalKey(\"status\") // → \"status\" (unchanged)\n *\n * @internal\n */\nexport function toInternalKey(key: string): string {\n // If key contains a dot, convert to separator format\n if (key.includes(\".\")) {\n const [namespace, ...rest] = key.split(\".\");\n\n return `${namespace}${SEPARATOR}${rest.join(SEPARATOR)}`;\n }\n // Already in internal format or simple key\n\n return key;\n}\n\n// ============================================================================\n// Snapshot Helpers\n// ============================================================================\n\n/**\n * Convert flat internal keys (e.g., `\"auth::token\"`) to nested namespaced\n * format (e.g., `{ auth: { token: ... } }`).\n *\n * Keys without a separator are grouped under `_root`.\n *\n * @param flatData - Object with internal prefixed keys\n * @returns Nested object grouped by namespace\n *\n * @internal\n */\nexport function denormalizeFlatKeys(\n flatData: Record<string, unknown>,\n): Record<string, Record<string, unknown>> {\n const result: Record<string, Record<string, unknown>> = {};\n\n for (const [key, value] of Object.entries(flatData)) {\n const sepIndex = key.indexOf(SEPARATOR);\n if (sepIndex > 0) {\n const ns = key.slice(0, sepIndex);\n const local = key.slice(sepIndex + SEPARATOR.length);\n if (!result[ns]) {\n result[ns] = {};\n }\n result[ns][local] = value;\n } else {\n if (!result._root) {\n result._root = {};\n }\n result._root[key] = value;\n }\n }\n\n return result;\n}\n","/**\n * Module transformation for namespaced systems.\n *\n * Converts a module's unprefixed keys to prefixed internal format\n * (e.g., `token` → `auth::token`). Used by both the initial system\n * setup loop and `registerModule()`.\n *\n * @internal\n */\n\nimport isDevelopment from \"#is-development\";\nimport { freezeSpec } from \"../utils/utils.js\";\nimport {\n applyPatch,\n evaluateTemplate,\n isPredicate,\n isTemplate,\n memoizePredicate,\n} from \"./predicate.js\";\nimport {\n SEPARATOR,\n createCrossModuleFactsProxy,\n createModuleDeriveProxy,\n createModuleFactsProxy,\n} from \"./system-proxies.js\";\nimport type { ModuleDef, ModuleSchema } from \"./types.js\";\nimport { isDerivationWithMeta } from \"./types/meta.js\";\n\n/**\n * The flat engine module format produced by prefixModuleDefinition.\n * Ready to be passed to createEngine or engine.registerModule.\n *\n * @internal\n */\nexport interface FlatModuleDefinition {\n id: string;\n schema: Record<string, unknown>;\n requirements: Record<string, unknown>;\n init: ((facts: Record<string, unknown>) => void) | undefined;\n derive: Record<string, unknown> | undefined;\n events: Record<string, unknown> | undefined;\n effects: Record<string, unknown> | undefined;\n constraints: Record<string, unknown> | undefined;\n resolvers: Record<string, unknown> | undefined;\n hooks: ModuleDef<ModuleSchema>[\"hooks\"];\n meta?: ModuleDef<ModuleSchema>[\"meta\"];\n history: { snapshotEvents?: string[] };\n}\n\n/**\n * Options for prefixModuleDefinition.\n *\n * @internal\n */\nexport interface PrefixModuleOptions {\n /** The module to transform */\n mod: ModuleDef<ModuleSchema>;\n /** The namespace to prefix keys with */\n namespace: string;\n /** Set of modules to snapshot (null = all). Used for history filtering. */\n snapshotModulesSet: Set<string> | null;\n}\n\n/**\n * Create a facts proxy appropriate for the module's cross-module configuration.\n * Returns a cross-module proxy when deps are declared, otherwise a module proxy.\n *\n * @internal\n */\nfunction createScopedFactsProxy(\n facts: Record<string, unknown>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> {\n return hasCrossModuleDeps\n ? createCrossModuleFactsProxy(facts, namespace, depNamespaces)\n : createModuleFactsProxy(facts, namespace);\n}\n\n/** Prefix a key with the namespace separator */\nfunction prefixKey(namespace: string, key: string): string {\n return `${namespace}${SEPARATOR}${key}`;\n}\n\n/** True if a key already includes the namespace separator (cross-module ref). */\nfunction isAlreadyPrefixed(key: string): boolean {\n return key.includes(SEPARATOR);\n}\n\n/**\n * Rewrite a data-form predicate spec so its top-level fact-key references\n * point at the namespaced flat keyspace (e.g. `phase` → `traffic::phase`).\n *\n * Recurses into `$all` / `$any` / `$not` combinators. Array-of-clauses form\n * has each `fact` field rewritten. Object form keys are rewritten, with\n * `$`-operator keys and already-prefixed keys passed through unchanged.\n *\n * Recognizes **namespace pivot** keys — a top-level key that equals `\"self\"`\n * or any declared cross-module dep namespace name is unwrapped one level:\n * its child predicate's keys are then prefixed with the appropriate\n * namespace. So `{ self: { phase: \"red\" } }` in module `traffic` becomes\n * `{ \"traffic::phase\": \"red\" }`, and `{ auth: { token: { $exists: true } } }`\n * with declared dep `auth` becomes `{ \"auth::token\": { $exists: true } }`.\n *\n * Operator keys (`$eq`, `$gte`, etc.) inside the nested object pass through\n * unchanged.\n *\n * Returns a frozen, structurally-identical spec.\n */\nfunction prefixPredicateSpec(\n spec: unknown,\n selfNamespace: string,\n depNamespaces: ReadonlySet<string>,\n): unknown {\n if (Array.isArray(spec)) {\n const out = spec.map((clause) => {\n if (\n clause &&\n typeof clause === \"object\" &&\n typeof (clause as { fact?: unknown }).fact === \"string\"\n ) {\n const fact = (clause as { fact: string }).fact;\n if (isAlreadyPrefixed(fact)) {\n return clause;\n }\n\n return { ...clause, fact: prefixKey(selfNamespace, fact) };\n }\n\n return clause;\n });\n freezeSpec(out);\n\n return out;\n }\n\n if (!spec || typeof spec !== \"object\") {\n return spec;\n }\n\n const src = spec as Record<string, unknown>;\n\n if (\"$all\" in src || \"$any\" in src) {\n const combinator = \"$all\" in src ? \"$all\" : \"$any\";\n const list = src[combinator] as unknown[];\n const out: Record<string, unknown> = {\n [combinator]: list.map((child) =>\n prefixPredicateSpec(child, selfNamespace, depNamespaces),\n ),\n };\n freezeSpec(out);\n\n return out;\n }\n if (\"$not\" in src) {\n const out = {\n $not: prefixPredicateSpec(src.$not, selfNamespace, depNamespaces),\n };\n freezeSpec(out);\n\n return out;\n }\n\n /**\n * Re-prefix one level of a pivot's nested predicate against a target\n * namespace. The child shape is the same as the parent spec — combinators,\n * array form, or `{ key: value }` map — so we recurse with a swapped\n * `selfNamespace`. The pivot's own depNamespaces are not re-checked one\n * level deeper (cross-module pivots cannot themselves contain further\n * cross-module pivots).\n */\n function prefixPivot(child: unknown, targetNamespace: string): unknown {\n return prefixPredicateSpec(child, targetNamespace, EMPTY_DEP_SET);\n }\n\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(src)) {\n if (key.startsWith(\"$\") || isAlreadyPrefixed(key)) {\n out[key] = src[key];\n continue;\n }\n if (key === \"self\") {\n // Namespace pivot — flatten one level against the self namespace.\n const child = src[key];\n if (child && typeof child === \"object\") {\n const flattened = prefixPivot(child, selfNamespace);\n if (\n flattened &&\n typeof flattened === \"object\" &&\n !Array.isArray(flattened)\n ) {\n for (const [k, v] of Object.entries(\n flattened as Record<string, unknown>,\n )) {\n out[k] = v;\n }\n continue;\n }\n }\n // Fall through to default behavior if child isn't a usable object.\n }\n if (depNamespaces.has(key)) {\n // Namespace pivot — flatten one level against the declared dep namespace.\n const child = src[key];\n if (child && typeof child === \"object\") {\n const flattened = prefixPivot(child, key);\n if (\n flattened &&\n typeof flattened === \"object\" &&\n !Array.isArray(flattened)\n ) {\n for (const [k, v] of Object.entries(\n flattened as Record<string, unknown>,\n )) {\n out[k] = v;\n }\n continue;\n }\n }\n // Fall through to default behavior if child isn't a usable object.\n }\n out[prefixKey(selfNamespace, key)] = src[key];\n }\n freezeSpec(out);\n\n return out;\n}\n\n/** Shared empty set used when recursing into a pivot (no nested pivots). */\nconst EMPTY_DEP_SET: ReadonlySet<string> = new Set<string>();\n\n/**\n * Convert any data-form definition arm in a module to its function-shape\n * equivalent, leaving the namespace prefixing to the existing per-arm\n * prefixers. Returns a shallow-copied module — the caller's input is never\n * mutated.\n *\n * - Constraint `when`: data spec → prefixed spec (still data) so the\n * constraints manager normalizes it against the flat keyspace and\n * `getWhenSpec()` returns a spec consistent with that keyspace.\n * - Derivation `compute`: data spec → bare `(facts) => value` function so the\n * per-arm prefixer can wrap it with a module-scoped proxy.\n * - Event `patch`: data spec → `{ handler, meta }` form so the event\n * prefixer's existing handler branch wraps it with a module-scoped proxy.\n * - Effect `on`: data spec → prefixed spec so the effects manager extracts\n * prefixed deps and gates against the flat snapshot.\n */\nfunction normalizePredicateDefs(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n): ModuleDef<ModuleSchema> {\n // Cross-module dep namespaces declared by this module — used by\n // prefixPredicateSpec to detect namespace pivots like `auth` in\n // `when: { auth: { token: { $exists: true } } }`.\n const depNamespaces: ReadonlySet<string> = mod.crossModuleDeps\n ? new Set(Object.keys(mod.crossModuleDeps))\n : EMPTY_DEP_SET;\n\n let constraints = mod.constraints;\n if (constraints) {\n let changed = false;\n const next: Record<string, unknown> = {};\n for (const [key, raw] of Object.entries(constraints)) {\n const def = raw as { when?: unknown };\n if (def.when !== undefined && typeof def.when !== \"function\") {\n next[key] = {\n ...def,\n when: prefixPredicateSpec(def.when, namespace, depNamespaces),\n };\n changed = true;\n continue;\n }\n next[key] = raw;\n }\n if (changed) {\n constraints = next as typeof constraints;\n }\n }\n\n let derive = mod.derive;\n if (derive) {\n let changed = false;\n const next: Record<string, unknown> = {};\n for (const [key, raw] of Object.entries(derive)) {\n const obj =\n raw && typeof raw === \"object\" && Object.hasOwn(raw, \"compute\")\n ? (raw as { compute: unknown; meta?: unknown })\n : null;\n if (!obj) {\n next[key] = raw;\n continue;\n }\n\n const c = obj.compute;\n if (typeof c === \"function\") {\n next[key] = raw;\n continue;\n }\n\n if (isTemplate(c)) {\n freezeSpec(c);\n const fn = (facts: unknown) =>\n evaluateTemplate(c, facts as Record<string, unknown>);\n next[key] = obj.meta ? { compute: fn, meta: obj.meta } : fn;\n changed = true;\n continue;\n }\n\n if (isPredicate(c)) {\n freezeSpec(c as object);\n const memoized = memoizePredicate(c as object);\n const fn = (facts: unknown) =>\n memoized(facts as Record<string, unknown>);\n next[key] = obj.meta ? { compute: fn, meta: obj.meta } : fn;\n changed = true;\n continue;\n }\n\n next[key] = raw;\n }\n if (changed) {\n derive = next as typeof derive;\n }\n }\n\n let events = mod.events;\n if (events) {\n let changed = false;\n const next: Record<string, unknown> = {};\n for (const [key, raw] of Object.entries(events)) {\n if (raw && typeof raw === \"object\") {\n const hasHandler = Object.hasOwn(raw, \"handler\");\n const hasPatch = Object.hasOwn(raw, \"patch\");\n\n // Both forms provided — mirror engine.ts unwrapEventDefinitions:\n // dev-warn once at registration so namespaced authors see the same\n // diagnostic as the single-module path. Keep the existing implicit\n // behavior of preferring the handler (skip patch conversion).\n if (hasHandler && hasPatch && isDevelopment) {\n console.warn(\n `[Directive] event \"${key}\": both \\`handler\\` and \\`patch\\` provided — using \\`handler\\` (patch is ignored).`,\n );\n }\n\n if (hasPatch && !hasHandler) {\n const obj = raw as {\n patch: { $set: Record<string, unknown> };\n meta?: unknown;\n };\n freezeSpec(obj.patch);\n const handler = (\n facts: Record<string, unknown>,\n event: Record<string, unknown> | undefined,\n ) =>\n applyPatch(\n obj.patch as Parameters<typeof applyPatch>[0],\n facts,\n event ?? {},\n );\n next[key] = obj.meta ? { handler, meta: obj.meta } : handler;\n changed = true;\n continue;\n }\n }\n next[key] = raw;\n }\n if (changed) {\n events = next as typeof events;\n }\n }\n\n let effects = mod.effects;\n if (effects) {\n let changed = false;\n const next: Record<string, unknown> = {};\n for (const [key, raw] of Object.entries(effects)) {\n const def = raw as { on?: unknown };\n if (def.on !== undefined && isPredicate(def.on)) {\n next[key] = {\n ...def,\n on: prefixPredicateSpec(def.on, namespace, depNamespaces),\n };\n changed = true;\n continue;\n }\n next[key] = raw;\n }\n if (changed) {\n effects = next as typeof effects;\n }\n }\n\n if (\n constraints === mod.constraints &&\n derive === mod.derive &&\n events === mod.events &&\n effects === mod.effects\n ) {\n return mod;\n }\n\n return { ...mod, constraints, derive, events, effects };\n}\n\n/** Return a non-empty record or undefined */\nfunction nonEmpty<T extends Record<string, unknown>>(rec: T): T | undefined {\n return Object.keys(rec).length > 0 ? rec : undefined;\n}\n\n/** Prefix schema fact keys */\nfunction prefixSchema(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(mod.schema.facts)) {\n result[prefixKey(namespace, key)] = value;\n }\n\n return result;\n}\n\n/** Create a prefixed init function */\nfunction prefixInit(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n): ((facts: Record<string, unknown>) => void) | undefined {\n if (!mod.init) {\n return undefined;\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Facts proxy type coercion\n return (facts: any) => {\n const moduleFactsProxy = createModuleFactsProxy(facts, namespace);\n // biome-ignore lint/suspicious/noExplicitAny: Module init type coercion\n (mod.init as any)(moduleFactsProxy);\n };\n}\n\n/** Prefix derivation keys and wrap derivation functions with scoped proxies */\nfunction prefixDerive(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.derive) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, raw] of Object.entries(mod.derive)) {\n const isObj = isDerivationWithMeta(raw);\n const fn = isObj ? raw.compute : raw;\n const meta = isObj ? raw.meta : undefined;\n\n const wrapper = (facts: unknown, derive: unknown) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n const deriveProxy = createModuleDeriveProxy(\n derive as Record<string, unknown>,\n namespace,\n );\n // biome-ignore lint/suspicious/noExplicitAny: Derive function type coercion\n return (fn as any)(factsProxy, deriveProxy);\n };\n\n // Pass through as { compute, meta } so derivationsManager can unwrap\n result[prefixKey(namespace, key)] = meta\n ? { compute: wrapper, meta }\n : wrapper;\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix event handler keys and wrap handlers with module-scoped proxies */\nfunction prefixEventHandlers(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n): Record<string, unknown> | undefined {\n if (!mod.events) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, raw] of Object.entries(mod.events)) {\n // Unwrap { handler, meta } form\n const isObj =\n typeof raw === \"object\" && raw !== null && Object.hasOwn(raw, \"handler\");\n const handler = isObj ? (raw as { handler: Function }).handler : raw;\n const meta = isObj ? (raw as { meta?: unknown }).meta : undefined;\n\n const wrapper = (facts: unknown, event: unknown) => {\n const moduleFactsProxy = createModuleFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n );\n // biome-ignore lint/suspicious/noExplicitAny: Event handler type coercion\n (handler as any)(moduleFactsProxy, event);\n };\n\n // Pass through as { handler, meta } so engine can extract meta\n result[prefixKey(namespace, key)] = meta\n ? { handler: wrapper, meta }\n : wrapper;\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix constraint keys and wrap when/require with scoped proxies */\nfunction prefixConstraints(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.constraints) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, constraint] of Object.entries(mod.constraints)) {\n const constraintDef = constraint as {\n when: ((facts: unknown) => boolean | Promise<boolean>) | unknown;\n require: unknown | ((facts: unknown) => unknown);\n priority?: number;\n async?: boolean;\n timeout?: number;\n deps?: string[];\n after?: string[];\n owns?: readonly string[];\n };\n\n const isWhenFn = typeof constraintDef.when === \"function\";\n\n result[prefixKey(namespace, key)] = {\n ...constraintDef,\n deps: constraintDef.deps?.map((dep) => prefixKey(namespace, dep)),\n after: constraintDef.after?.map((dep) =>\n dep.includes(SEPARATOR) ? dep : prefixKey(namespace, dep),\n ),\n // RFC-0003: prefix `owns` fact keys so clobber-detection compares\n // against the namespaced fact slots that the resolver actually writes.\n // Without this, the bound proxy's `owned.has(prop)` check fails for\n // every namespaced owned write and the entire clobber-detection\n // feature silently no-ops in any namespaced system.\n owns: constraintDef.owns?.map((k) =>\n k.includes(SEPARATOR) ? k : prefixKey(namespace, k),\n ),\n // Data-form `when` was rewritten with prefixed keys in\n // `normalizePredicateDefs`, so the constraints manager can normalize\n // it against the flat keyspace. Only function-form `when` needs the\n // module-scoped proxy wrapper.\n when: isWhenFn\n ? (facts: unknown) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n\n return (\n constraintDef.when as (\n facts: unknown,\n ) => boolean | Promise<boolean>\n )(factsProxy);\n }\n : constraintDef.when,\n require:\n typeof constraintDef.require === \"function\"\n ? (facts: unknown) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n\n return (constraintDef.require as (facts: unknown) => unknown)(\n factsProxy,\n );\n }\n : constraintDef.require,\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix resolver keys and wrap resolve/resolveBatch/resolveBatchWithResults with scoped proxies */\nfunction prefixResolvers(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.resolvers) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, resolver] of Object.entries(mod.resolvers)) {\n const resolverDef = resolver as {\n requirement: string;\n resolve?: (\n req: unknown,\n ctx: { facts: unknown; signal: AbortSignal },\n ) => Promise<void>;\n resolveBatch?: (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => Promise<void>;\n resolveBatchWithResults?: (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => Promise<unknown>;\n key?: (req: unknown) => string;\n retry?: unknown;\n timeout?: number;\n };\n\n /** Wrap resolver ctx.facts with the module-scoped proxy */\n function wrapCtx(ctx: { facts: unknown; signal: AbortSignal }): {\n facts: unknown;\n signal: AbortSignal;\n } {\n return {\n facts: createScopedFactsProxy(\n ctx.facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n ),\n signal: ctx.signal,\n };\n }\n\n result[prefixKey(namespace, key)] = {\n ...resolverDef,\n ...(resolverDef.resolve && {\n resolve: async (\n req: unknown,\n ctx: { facts: unknown; signal: AbortSignal },\n ) => {\n await resolverDef.resolve!(req, wrapCtx(ctx));\n },\n }),\n ...(resolverDef.resolveBatch && {\n resolveBatch: async (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => {\n await resolverDef.resolveBatch!(reqs, wrapCtx(ctx));\n },\n }),\n ...(resolverDef.resolveBatchWithResults && {\n resolveBatchWithResults: async (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => {\n return resolverDef.resolveBatchWithResults!(reqs, wrapCtx(ctx));\n },\n }),\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix effect keys and wrap run functions with scoped proxies */\nfunction prefixEffects(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.effects) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, effect] of Object.entries(mod.effects)) {\n const effectDef = effect as {\n // biome-ignore lint/suspicious/noExplicitAny: Effect run function type\n run: (facts: any, prev: any) => void | Promise<void>;\n deps?: string[];\n };\n\n result[prefixKey(namespace, key)] = {\n ...effectDef,\n // biome-ignore lint/suspicious/noExplicitAny: Effect run function wrapper\n run: (facts: any, prev: any) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n const prevProxy = prev\n ? createScopedFactsProxy(\n prev as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n )\n : undefined;\n\n return effectDef.run(factsProxy, prevProxy);\n },\n deps: effectDef.deps?.map((dep) => prefixKey(namespace, dep)),\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Compute history config with prefixed snapshot events */\nfunction prefixHistory(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n snapshotModulesSet: Set<string> | null,\n): { snapshotEvents?: string[] } {\n return {\n snapshotEvents:\n snapshotModulesSet && !snapshotModulesSet.has(namespace)\n ? [] // Module excluded from snapshots\n : mod.history?.snapshotEvents?.map((e: string) =>\n prefixKey(namespace, e),\n ),\n };\n}\n\n/**\n * Transform a module definition by prefixing all keys with a namespace.\n *\n * Handles: facts, derivations, events schema, init, derive, events handlers,\n * constraints (with deps/after), resolvers, and effects.\n *\n * @returns A flat module definition ready for the engine\n *\n * @internal\n */\nexport function prefixModuleDefinition(\n options: PrefixModuleOptions,\n): FlatModuleDefinition {\n const { mod: rawMod, namespace, snapshotModulesSet } = options;\n\n // Normalize data-form definition arms before namespace prefixing so the\n // per-arm prefixers can assume function-shaped definitions (where they\n // wrap with module-scoped proxies) or already-prefixed data specs (where\n // the managers compile against the flat keyspace).\n const mod = normalizePredicateDefs(rawMod, namespace);\n\n // Compute cross-module deps info once (used by derive, constraints, effects)\n const hasCrossModuleDeps = !!(\n mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0\n );\n const depNamespaces = hasCrossModuleDeps\n ? Object.keys(mod.crossModuleDeps!)\n : [];\n\n return {\n id: mod.id,\n schema: prefixSchema(mod, namespace),\n requirements: mod.schema.requirements ?? {},\n init: prefixInit(mod, namespace),\n derive: prefixDerive(mod, namespace, hasCrossModuleDeps, depNamespaces),\n events: prefixEventHandlers(mod, namespace),\n effects: prefixEffects(mod, namespace, hasCrossModuleDeps, depNamespaces),\n constraints: prefixConstraints(\n mod,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n ),\n resolvers: prefixResolvers(\n mod,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n ),\n hooks: mod.hooks,\n meta: mod.meta,\n history: prefixHistory(mod, namespace, snapshotModulesSet),\n };\n}\n","/**\n * System - The top-level API for creating a Directive runtime\n *\n * A system combines modules with plugins and configuration.\n * Modules are passed as an object with namespaced access:\n *\n * @example\n * ```typescript\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n *\n * system.facts.auth.token // Namespaced facts\n * system.derive.data.userCount // Namespaced derivations\n * system.events.auth.login() // Namespaced events\n * ```\n */\n\nimport isDevelopment from \"#is-development\";\nimport { isPrototypeSafe } from \"../utils/utils.js\";\nimport { createEngine } from \"./engine.js\";\nimport { prefixModuleDefinition } from \"./system-module-transform.js\";\nimport {\n SEPARATOR,\n createNamespacedDeriveProxy,\n createNamespacedEventsProxy,\n createNamespacedFactsProxy,\n denormalizeFlatKeys,\n toInternalKey,\n} from \"./system-proxies.js\";\nimport { BLOCKED_PROPS } from \"./tracking.js\";\nimport type {\n CreateSystemOptionsNamed,\n CreateSystemOptionsSingle,\n ErrorBoundaryConfig,\n HistoryOption,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n SingleModuleSystem,\n TraceOption,\n} from \"./types.js\";\n\n// ============================================================================\n// Topological Sort for Module Dependencies\n// ============================================================================\n\n/**\n * Perform topological sort on modules based on crossModuleDeps.\n * Returns module namespaces in dependency order (dependencies first).\n *\n * @throws Error if circular dependency detected\n */\nfunction topologicalSort<Modules extends ModulesMap>(\n modulesMap: Modules,\n): Array<keyof Modules & string> {\n const namespaces = Object.keys(modulesMap) as Array<keyof Modules & string>;\n const namespacesSet = new Set<string>(namespaces);\n const visited = new Set<string>();\n const visiting = new Set<string>(); // For cycle detection\n const result: Array<keyof Modules & string> = [];\n const path: string[] = []; // Reuse array to avoid O(n²) memory\n\n function visit(namespace: string): void {\n if (visited.has(namespace)) return;\n\n // Cycle detection\n if (visiting.has(namespace)) {\n const cycleStart = path.indexOf(namespace);\n const cycle = [...path.slice(cycleStart), namespace].join(\" → \");\n throw new Error(\n `[Directive] Circular dependency detected: ${cycle}. ` +\n \"Modules cannot have circular crossModuleDeps. \" +\n \"Break the cycle by removing one of the cross-module references.\",\n );\n }\n\n visiting.add(namespace);\n path.push(namespace);\n\n // Visit dependencies first\n const mod = modulesMap[namespace];\n if (mod?.crossModuleDeps) {\n for (const depNamespace of Object.keys(mod.crossModuleDeps)) {\n if (namespacesSet.has(depNamespace)) {\n visit(depNamespace);\n }\n }\n }\n\n path.pop();\n visiting.delete(namespace);\n visited.add(namespace);\n result.push(namespace as keyof Modules & string);\n }\n\n for (const namespace of namespaces) {\n visit(namespace);\n }\n\n return result;\n}\n\n/**\n * Build the list of internal prefixed keys (facts + derivations) for a module namespace.\n * Used by subscribe/subscribeModule to map namespaces to their engine keys.\n */\nfunction collectNamespaceKeys(\n namespace: string,\n mod: ModuleDef<ModuleSchema>,\n): string[] {\n const keys: string[] = [];\n for (const key of Object.keys(mod.schema.facts)) {\n keys.push(`${namespace}${SEPARATOR}${key}`);\n }\n if (mod.schema.derivations) {\n for (const key of Object.keys(mod.schema.derivations)) {\n keys.push(`${namespace}${SEPARATOR}${key}`);\n }\n }\n\n return keys;\n}\n\n// ============================================================================\n// createSystem\n// ============================================================================\n\n/**\n * Create a Directive system.\n *\n * Supports two modes:\n * - **Single module**: Use `module` prop for direct access without namespace\n * - **Multiple modules**: Use `modules` prop for namespaced access\n *\n * @remarks\n * The system is the top-level runtime object. It owns the reconciliation loop,\n * manages plugins, and exposes reactive accessors for facts, derivations, and events.\n * Call `system.start()` to begin the lifecycle (init → ready → running → settled).\n *\n * @param options - System configuration with either `module` (single) or `modules` (namespaced)\n * @returns A fully-typed {@link System} instance with reactive accessors\n *\n * @example Single module (direct access)\n * ```ts\n * const system = createSystem({ module: counterModule });\n * system.facts.count // Direct access\n * system.events.increment() // Direct events\n * ```\n *\n * @example Multiple modules (namespaced access)\n * ```ts\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n * system.facts.auth.token // Namespaced access\n * system.events.auth.login() // Namespaced events\n * ```\n *\n * @public\n */\nexport function createSystem<S extends ModuleSchema>(\n options: CreateSystemOptionsSingle<S>,\n): SingleModuleSystem<S>;\nexport function createSystem<const Modules extends ModulesMap>(\n options: CreateSystemOptionsNamed<Modules>,\n): NamespacedSystem<Modules>;\n/** @internal Implementation overload — see public overloads above. */\nexport function createSystem<\n S extends ModuleSchema,\n Modules extends ModulesMap,\n>(\n options: CreateSystemOptionsSingle<S> | CreateSystemOptionsNamed<Modules>,\n): SingleModuleSystem<S> | NamespacedSystem<Modules> {\n // Single module mode (module prop)\n if (\"module\" in options) {\n if (!options.module) {\n throw new Error(\n \"[Directive] createSystem requires a module. Got: \" +\n typeof options.module,\n );\n }\n return createSingleModuleSystem(\n options as CreateSystemOptionsSingle<S>,\n ) as SingleModuleSystem<S>;\n }\n\n // Namespaced mode (modules prop)\n const namedOptions = options as CreateSystemOptionsNamed<Modules>;\n\n // Validate not an array\n if (Array.isArray(namedOptions.modules)) {\n throw new Error(\n \"[Directive] createSystem expects modules as an object, not an array.\\n\\n\" +\n \"Instead of:\\n\" +\n \" createSystem({ modules: [authModule, dataModule] })\\n\\n\" +\n \"Use:\\n\" +\n \" createSystem({ modules: { auth: authModule, data: dataModule } })\\n\\n\" +\n \"Or for a single module:\\n\" +\n \" createSystem({ module: counterModule })\",\n );\n }\n\n // Detect single ModuleDef accidentally passed to `modules:` instead of `module:`\n const mods = namedOptions.modules as Record<string, unknown>;\n if (mods && typeof mods === \"object\" && \"id\" in mods && \"schema\" in mods) {\n throw new Error(\n \"[Directive] A single module was passed to `modules:`. \" +\n \"For a single module, use `module:` instead:\\n\\n\" +\n \" createSystem({ module: myModule })\\n\\n\" +\n \"For multiple modules, wrap in an object:\\n\" +\n \" createSystem({ modules: { myName: myModule } })\",\n );\n }\n\n return createNamespacedSystem(namedOptions) as NamespacedSystem<Modules>;\n}\n\n// ============================================================================\n// Internal Implementation\n// ============================================================================\n\nfunction createNamespacedSystem<Modules extends ModulesMap>(\n options: CreateSystemOptionsNamed<Modules>,\n): NamespacedSystem<Modules> {\n const modulesMap = options.modules;\n const moduleNamespaces = new Set(Object.keys(modulesMap));\n\n // Build snapshot module filter set (null = all modules snapshot)\n const historyConfig =\n typeof options.history === \"object\" ? options.history : null;\n const snapshotModulesSet = historyConfig?.snapshotModules\n ? new Set(historyConfig.snapshotModules)\n : null;\n\n // Validate tickMs if provided\n if (options.tickMs !== undefined && options.tickMs <= 0) {\n throw new Error(\"[Directive] tickMs must be a positive number\");\n }\n\n // Dev-mode: Validate crossModuleDeps reference existing modules\n if (isDevelopment) {\n for (const [namespace, mod] of Object.entries(modulesMap)) {\n if (mod.crossModuleDeps) {\n for (const depNamespace of Object.keys(mod.crossModuleDeps)) {\n if (depNamespace === namespace) {\n console.warn(\n `[Directive] Module \"${namespace}\" references itself in crossModuleDeps. ` +\n `Use \"facts.self\" to access own module's facts instead.`,\n );\n } else if (!moduleNamespaces.has(depNamespace)) {\n console.warn(\n `[Directive] Module \"${namespace}\" declares crossModuleDeps.${depNamespace}, ` +\n `but no module with namespace \"${depNamespace}\" exists in the system. ` +\n `Available modules: ${[...moduleNamespaces].join(\", \")}`,\n );\n }\n }\n }\n }\n }\n\n // Dev-mode: Validate snapshotModules references existing modules\n if (isDevelopment && historyConfig?.snapshotModules) {\n for (const name of historyConfig.snapshotModules) {\n if (!moduleNamespaces.has(name)) {\n console.warn(\n `[Directive] history.snapshotModules entry \"${name}\" doesn't match any module. ` +\n `Available modules: ${[...moduleNamespaces].join(\", \")}`,\n );\n }\n }\n }\n\n // Determine module initialization order\n let orderedNamespaces: Array<keyof Modules & string>;\n const initOrder = options.initOrder ?? \"auto\";\n\n if (Array.isArray(initOrder)) {\n // Explicit order provided - validate it includes all modules\n const explicitOrder = initOrder as Array<keyof Modules & string>;\n const missingModules = Object.keys(modulesMap).filter(\n (ns) => !explicitOrder.includes(ns as keyof Modules & string),\n );\n if (missingModules.length > 0) {\n throw new Error(\n `[Directive] initOrder is missing modules: ${missingModules.join(\", \")}. ` +\n \"All modules must be included in the explicit order.\",\n );\n }\n orderedNamespaces = explicitOrder;\n } else if (initOrder === \"declaration\") {\n // Use object key order (current behavior)\n orderedNamespaces = Object.keys(modulesMap) as Array<\n keyof Modules & string\n >;\n } else {\n // \"auto\" - use topological sort based on crossModuleDeps\n orderedNamespaces = topologicalSort(modulesMap);\n }\n\n // Apply zero-config defaults if enabled\n const { history, trace, errorBoundary } = applyZeroConfigDefaults(options);\n\n // Validate module names and schema keys don't contain the separator\n for (const namespace of Object.keys(modulesMap)) {\n if (namespace.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Module name \"${namespace}\" contains the reserved separator \"${SEPARATOR}\". ` +\n `Module names cannot contain \"${SEPARATOR}\".`,\n );\n }\n const mod = modulesMap[namespace];\n if (mod) {\n for (const key of Object.keys(mod.schema.facts)) {\n if (key.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Schema key \"${key}\" in module \"${namespace}\" contains the reserved separator \"${SEPARATOR}\". ` +\n `Schema keys cannot contain \"${SEPARATOR}\".`,\n );\n }\n }\n }\n }\n\n // Cached module names array, shared by all namespaced proxies.\n // Set to null on registerModule to lazily recompute.\n const moduleNamesCache: { names: string[] | null } = { names: null };\n function getModuleNames(): string[] {\n if (moduleNamesCache.names === null) {\n moduleNamesCache.names = Object.keys(modulesMap);\n }\n\n return moduleNamesCache.names;\n }\n\n // Transform modules to flat format with prefixed keys\n // auth.token → auth::token internally\n // Process in dependency order (determined above)\n const flatModules = orderedNamespaces\n .map((namespace) => {\n const mod = modulesMap[namespace];\n if (!mod) return null; // TypeScript guard - should never happen\n\n return prefixModuleDefinition({\n mod,\n namespace,\n snapshotModulesSet,\n });\n })\n .filter((m): m is NonNullable<typeof m> => m !== null);\n\n // Dev-mode warning: tickMs set without tick event handler\n if (isDevelopment && options.tickMs && options.tickMs > 0) {\n const hasTickHandler = flatModules.some(\n (m) =>\n m.events &&\n Object.keys(m.events).some((k) => k.endsWith(`${SEPARATOR}tick`)),\n );\n if (!hasTickHandler) {\n console.warn(\n `[Directive] tickMs is set to ${options.tickMs}ms but no module defines a \"tick\" event handler.`,\n );\n }\n }\n\n // Store for hydrated facts (set by hydrate(), applied during init)\n let hydratedFacts: Record<string, Record<string, unknown>> | null = null;\n\n // Engine reference (set after creation, used by applyNamespacedFacts)\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n let engine: any = null;\n\n /**\n * Apply namespaced facts to the engine's flat store.\n * Converts { auth: { token: \"x\" } } to { \"auth::token\": \"x\" }\n * Includes prototype pollution protection.\n */\n function applyNamespacedFacts(\n namespacedFacts: Record<string, Record<string, unknown>>,\n ): void {\n for (const [namespace, facts] of Object.entries(namespacedFacts)) {\n // Skip blocked property names\n if (BLOCKED_PROPS.has(namespace)) {\n if (isDevelopment) {\n console.warn(\n `[Directive] initialFacts/hydrate contains blocked namespace \"${namespace}\". Skipping.`,\n );\n }\n continue;\n }\n\n if (!moduleNamespaces.has(namespace)) {\n if (isDevelopment) {\n console.warn(\n `[Directive] initialFacts/hydrate contains unknown namespace \"${namespace}\". ` +\n `Available modules: ${[...moduleNamespaces].join(\", \")}`,\n );\n }\n continue;\n }\n\n // Validate facts object for prototype pollution\n if (facts && typeof facts === \"object\" && !isPrototypeSafe(facts)) {\n throw new Error(\n `[Directive] initialFacts/hydrate for namespace \"${namespace}\" contains potentially ` +\n \"dangerous keys (__proto__, constructor, or prototype). This may indicate a \" +\n \"prototype pollution attack.\",\n );\n }\n\n for (const [key, value] of Object.entries(facts)) {\n // Skip blocked keys\n if (BLOCKED_PROPS.has(key)) continue;\n (engine.facts as Record<string, unknown>)[\n `${namespace}${SEPARATOR}${key}`\n ] = value;\n }\n }\n }\n\n // Create engine with flat modules\n engine = createEngine({\n // biome-ignore lint/suspicious/noExplicitAny: Module format conversion\n modules: flatModules as any,\n plugins: options.plugins,\n history,\n trace,\n errorBoundary,\n tickMs: options.tickMs,\n cloud: options.cloud,\n // Callback to apply initialFacts/hydrate during init phase (after module inits, before reconcile)\n onAfterModuleInit: () => {\n // Apply initialFacts first\n if (options.initialFacts) {\n applyNamespacedFacts(\n options.initialFacts as Record<string, Record<string, unknown>>,\n );\n }\n // Apply hydrated facts second (takes precedence)\n if (hydratedFacts) {\n applyNamespacedFacts(hydratedFacts);\n hydratedFacts = null;\n }\n },\n });\n\n // Build namespace → internal keys map (for subscribeModule / wildcard support)\n const namespaceKeysMap = new Map<string, string[]>();\n for (const namespace of Object.keys(modulesMap)) {\n const mod = modulesMap[namespace];\n if (!mod) continue;\n namespaceKeysMap.set(namespace, collectNamespaceKeys(namespace, mod));\n }\n\n // Create namespaced proxies for external access\n const namespacedFactsProxy = createNamespacedFactsProxy(\n engine.facts as unknown as Record<string, unknown>,\n modulesMap,\n getModuleNames,\n );\n const namespacedDeriveProxy = createNamespacedDeriveProxy(\n engine.derive as unknown as Record<string, unknown>,\n modulesMap,\n getModuleNames,\n );\n const namespacedEventsProxy = createNamespacedEventsProxy(\n engine,\n modulesMap,\n getModuleNames,\n );\n\n // Build the namespaced system\n let tickInterval: ReturnType<typeof setInterval> | null = null;\n const tickMs = options.tickMs;\n\n const system: NamespacedSystem<Modules> = {\n _mode: \"namespaced\",\n facts: namespacedFactsProxy,\n history: engine.history,\n derive: namespacedDeriveProxy,\n events: namespacedEventsProxy,\n constraints: engine.constraints,\n effects: engine.effects,\n resolvers: engine.resolvers,\n\n async hydrate(\n loader: () =>\n | Promise<Record<string, Record<string, unknown>>>\n | Record<string, Record<string, unknown>>,\n ) {\n if (engine.isRunning) {\n throw new Error(\n \"[Directive] hydrate() must be called before start(). \" +\n \"The system is already running.\",\n );\n }\n\n const result = await loader();\n if (result && typeof result === \"object\") {\n hydratedFacts = result;\n }\n },\n\n initialize(): void {\n engine.initialize();\n },\n\n start(): void {\n // Engine.start() runs module inits, then applies initialFacts/hydrate via callback\n engine.start();\n\n if (tickMs && tickMs > 0) {\n // Find the first module with a tick event and dispatch to it\n let tickEventKey: string | undefined;\n for (const m of flatModules) {\n if (m?.events) {\n tickEventKey = Object.keys(m.events).find((k) =>\n k.endsWith(`${SEPARATOR}tick`),\n );\n if (tickEventKey) break;\n }\n }\n if (tickEventKey) {\n const key = tickEventKey;\n tickInterval = setInterval(() => {\n engine.dispatch({ type: key });\n }, tickMs);\n }\n }\n },\n\n stop(): void {\n if (tickInterval) {\n clearInterval(tickInterval);\n tickInterval = null;\n }\n engine.stop();\n },\n\n destroy(): void {\n this.stop();\n engine.destroy();\n },\n\n dispatch(event: { type: string; [key: string]: unknown }) {\n engine.dispatch(event);\n },\n\n /**\n * Read a derivation value using namespaced syntax.\n * Accepts \"namespace.key\" format.\n *\n * @example\n * system.read(\"auth.status\") // → \"authenticated\"\n * system.read(\"data.count\") // → 5\n */\n read<T = unknown>(derivationId: string): T {\n return engine.read(toInternalKey(derivationId));\n },\n\n /**\n * Subscribe to derivation changes using namespaced syntax.\n * Accepts \"namespace.key\" format.\n * Supports wildcard \"namespace.*\" to subscribe to all keys in a module.\n *\n * @example\n * system.subscribe([\"auth.status\", \"data.count\"], () => {\n * console.log(\"Auth or data changed\");\n * });\n *\n * @example Wildcard\n * system.subscribe([\"game.*\", \"chat.*\"], () => render());\n */\n subscribe(ids: string[], listener: () => void): () => void {\n const internalIds: string[] = [];\n for (const id of ids) {\n if (id.endsWith(\".*\")) {\n const ns = id.slice(0, -2);\n const keys = namespaceKeysMap.get(ns);\n if (keys) {\n internalIds.push(...keys);\n } else if (isDevelopment) {\n console.warn(\n `[Directive] subscribe wildcard \"${id}\" — namespace \"${ns}\" not found.`,\n );\n }\n } else {\n internalIds.push(toInternalKey(id));\n }\n }\n return engine.subscribe(internalIds, listener);\n },\n\n /**\n * Subscribe to ALL fact and derivation changes in a module namespace.\n * Shorthand for subscribing to every key in a module.\n *\n * @example\n * const unsub = system.subscribeModule(\"game\", () => render());\n */\n subscribeModule(namespace: string, listener: () => void): () => void {\n const keys = namespaceKeysMap.get(namespace);\n if (!keys || keys.length === 0) {\n if (isDevelopment) {\n console.warn(\n `[Directive] subscribeModule(\"${namespace}\") — namespace not found. ` +\n `Available: ${[...namespaceKeysMap.keys()].join(\", \")}`,\n );\n }\n return () => {};\n }\n return engine.subscribe(keys, listener);\n },\n\n /**\n * Watch a fact or derivation for changes using namespaced syntax.\n * The key is auto-detected -- works with both fact keys and derivation keys.\n * Accepts \"namespace.key\" format.\n *\n * @example\n * system.watch(\"auth.token\", (newVal, oldVal) => { ... }) // fact\n * system.watch(\"auth.status\", (newVal, oldVal) => { ... }) // derivation\n */\n watch<T = unknown>(\n id: string,\n callback: (newValue: T, previousValue: T | undefined) => void,\n options?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n ): () => void {\n return engine.watch(toInternalKey(id), callback, options);\n },\n\n /**\n * Returns a promise that resolves when the predicate becomes true.\n * The predicate receives namespaced facts (e.g., facts.auth.token).\n */\n when(\n predicate: (facts: Record<string, unknown>) => boolean,\n options?: { timeout?: number },\n ): Promise<void> {\n // Wrap predicate to provide namespaced facts view\n return engine.when(\n () =>\n predicate(namespacedFactsProxy as unknown as Record<string, unknown>),\n options,\n );\n },\n\n /**\n * Get a distributable snapshot with namespaced key translation.\n * Accepts \"namespace.key\" format in options (e.g., \"auth.effectivePlan\").\n * Returns data with namespaced keys (e.g., { auth: { effectivePlan: ... } }).\n */\n getDistributableSnapshot<T = Record<string, unknown>>(options?: {\n includeDerivations?: string[];\n excludeDerivations?: string[];\n includeFacts?: string[];\n ttlSeconds?: number;\n metadata?: Record<string, unknown>;\n includeVersion?: boolean;\n }): {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n } {\n // Translate namespaced keys to internal format\n const internalOptions = {\n ...options,\n includeDerivations: options?.includeDerivations?.map(toInternalKey),\n excludeDerivations: options?.excludeDerivations?.map(toInternalKey),\n includeFacts: options?.includeFacts?.map(toInternalKey),\n };\n\n const snapshot = engine.getDistributableSnapshot(internalOptions);\n\n // Transform data keys from internal format (auth::status) to namespaced format (auth: { status })\n return {\n ...snapshot,\n data: denormalizeFlatKeys(\n snapshot.data as Record<string, unknown>,\n ) as T,\n };\n },\n\n /**\n * Watch for changes to distributable snapshot derivations.\n * Accepts \"namespace.key\" format in options.\n * Callback receives data with namespaced keys.\n */\n watchDistributableSnapshot<T = Record<string, unknown>>(\n options: {\n includeDerivations?: string[];\n excludeDerivations?: string[];\n includeFacts?: string[];\n ttlSeconds?: number;\n metadata?: Record<string, unknown>;\n includeVersion?: boolean;\n },\n callback: (snapshot: {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n }) => void,\n ): () => void {\n // Translate namespaced keys to internal format\n const internalOptions = {\n ...options,\n includeDerivations: options?.includeDerivations?.map(toInternalKey),\n excludeDerivations: options?.excludeDerivations?.map(toInternalKey),\n includeFacts: options?.includeFacts?.map(toInternalKey),\n };\n\n return engine.watchDistributableSnapshot(\n internalOptions,\n (snapshot: {\n data: Record<string, unknown>;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n }) => {\n // Transform data keys from internal format to namespaced format\n callback({\n ...snapshot,\n data: denormalizeFlatKeys(\n snapshot.data as Record<string, unknown>,\n ) as T,\n });\n },\n );\n },\n registerModule(\n namespace: string,\n moduleDef: ModuleDef<ModuleSchema>,\n ): void {\n // Validate namespace\n if (moduleNamespaces.has(namespace)) {\n throw new Error(\n `[Directive] Module namespace \"${namespace}\" already exists. ` +\n \"Cannot register a duplicate namespace.\",\n );\n }\n if (namespace.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Module name \"${namespace}\" contains the reserved separator \"${SEPARATOR}\".`,\n );\n }\n if (BLOCKED_PROPS.has(namespace)) {\n throw new Error(\n `[Directive] Module name \"${namespace}\" is a blocked property.`,\n );\n }\n\n // Validate schema keys\n for (const key of Object.keys(moduleDef.schema.facts)) {\n if (key.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Schema key \"${key}\" in module \"${namespace}\" contains the reserved separator \"${SEPARATOR}\".`,\n );\n }\n }\n\n const mod = moduleDef;\n\n // Transform module definition with namespace prefixing\n const flat = prefixModuleDefinition({\n mod,\n namespace,\n snapshotModulesSet,\n });\n\n // Register namespace\n moduleNamespaces.add(namespace);\n (modulesMap as Record<string, ModuleDef<ModuleSchema>>)[namespace] = mod;\n // Invalidate cached module names so proxies see the new namespace\n moduleNamesCache.names = null;\n\n // Update namespace keys map\n namespaceKeysMap.set(namespace, collectNamespaceKeys(namespace, mod));\n\n // Delegate to engine's registerModule\n // biome-ignore lint/suspicious/noExplicitAny: Engine registerModule type\n (engine as any).registerModule(flat);\n },\n\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing for NamespacedSystem\n } as any;\n\n bindEnginePassthroughs(system, engine);\n warnIfNotStarted(system);\n\n return system;\n}\n\n// ============================================================================\n// Shared Helpers (deduplication between single-module and namespaced systems)\n// ============================================================================\n\n/**\n * Apply zero-config defaults to system options (history, trace, errorBoundary).\n * Returns the resolved values; does not mutate the options object.\n */\nfunction applyZeroConfigDefaults(options: {\n zeroConfig?: boolean;\n history?: HistoryOption;\n trace?: TraceOption;\n errorBoundary?: ErrorBoundaryConfig;\n}): {\n history: HistoryOption | undefined;\n trace: TraceOption | undefined;\n errorBoundary: ErrorBoundaryConfig | undefined;\n} {\n let history: HistoryOption | undefined = options.history;\n const trace: TraceOption | undefined = options.trace;\n let errorBoundary: ErrorBoundaryConfig | undefined = options.errorBoundary;\n\n if (options.zeroConfig) {\n const isDev = isDevelopment;\n\n history = history ?? isDev;\n\n errorBoundary = {\n onConstraintError: \"skip\",\n onResolverError: \"skip\",\n onEffectError: \"skip\",\n onDerivationError: \"skip\",\n ...options.errorBoundary,\n };\n }\n\n return { history, trace, errorBoundary };\n}\n\n/**\n * Bind shared engine passthrough properties and methods onto a system object.\n * These are identical between single-module and namespaced systems.\n *\n * For methods that namespaced systems override (dispatch, read, subscribe,\n * watch, when, getDistributableSnapshot, watchDistributableSnapshot),\n * only binds them if not already defined on the system object.\n */\nfunction bindEnginePassthroughs(\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n system: any,\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n engine: any,\n): void {\n Object.defineProperties(system, {\n trace: {\n get() {\n return engine.trace;\n },\n enumerable: true,\n configurable: true,\n },\n meta: {\n value: engine.meta,\n enumerable: true,\n configurable: true,\n },\n isRunning: {\n get() {\n return engine.isRunning;\n },\n enumerable: true,\n configurable: true,\n },\n isSettled: {\n get() {\n return engine.isSettled;\n },\n enumerable: true,\n configurable: true,\n },\n isInitialized: {\n get() {\n return engine.isInitialized;\n },\n enumerable: true,\n configurable: true,\n },\n isReady: {\n get() {\n return engine.isReady;\n },\n enumerable: true,\n configurable: true,\n },\n });\n\n system.whenReady = engine.whenReady.bind(engine);\n system.batch = engine.batch.bind(engine);\n system.onSettledChange = engine.onSettledChange.bind(engine);\n system.onHistoryChange = engine.onHistoryChange.bind(engine);\n system.inspect = engine.inspect.bind(engine);\n system.settle = engine.settle.bind(engine);\n system.explain = engine.explain.bind(engine);\n system.getSnapshot = engine.getSnapshot.bind(engine);\n system.restore = engine.restore.bind(engine);\n system.observe = engine.observe.bind(engine);\n\n // Direct engine passthroughs — only bind if not already defined\n // (namespaced systems override these with key-translating versions)\n const overridableMethods = [\n \"dispatch\",\n \"read\",\n \"subscribe\",\n \"watch\",\n \"when\",\n \"getDistributableSnapshot\",\n \"watchDistributableSnapshot\",\n ] as const;\n for (const method of overridableMethods) {\n if (!(method in system)) {\n system[method] = engine[method].bind(engine);\n }\n }\n}\n\n/**\n * Emit a dev-mode warning if system.start() is never called.\n */\nfunction warnIfNotStarted(\n // biome-ignore lint/suspicious/noExplicitAny: System type\n system: any,\n): void {\n if (\n isDevelopment &&\n (typeof process === \"undefined\" || process.env?.NODE_ENV !== \"test\")\n ) {\n setTimeout(() => {\n if (!system.isRunning && !system.isInitialized) {\n console.warn(\n \"[Directive] System created but start() was never called. \" +\n \"Constraints, resolvers, and effects will not run until you call system.start().\",\n );\n }\n }, 0);\n }\n}\n\n// Proxy helpers and key conversion utilities are in system-proxies.ts\n\n// ============================================================================\n// Single Module System\n// ============================================================================\n\n/**\n * Create a system with a single module (no namespacing).\n * Facts, derivations, and events are accessed directly.\n */\nfunction createSingleModuleSystem<S extends ModuleSchema>(\n options: CreateSystemOptionsSingle<S>,\n): SingleModuleSystem<S> {\n const mod = options.module;\n\n // Validate module is provided\n if (!mod) {\n throw new Error(\n \"[Directive] createSystem requires a module. Got: \" + typeof mod,\n );\n }\n\n // Validate tickMs if provided\n if (options.tickMs !== undefined && options.tickMs <= 0) {\n throw new Error(\"[Directive] tickMs must be a positive number\");\n }\n\n // Validate initialFacts for prototype pollution\n if (options.initialFacts && !isPrototypeSafe(options.initialFacts)) {\n throw new Error(\n \"[Directive] initialFacts contains potentially dangerous keys \" +\n \"(__proto__, constructor, or prototype). This may indicate a \" +\n \"prototype pollution attack.\",\n );\n }\n\n // Dev-mode warnings\n if (isDevelopment) {\n // Warn if crossModuleDeps is defined (ignored in single module mode)\n if (mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0) {\n console.warn(\n \"[Directive] Single module mode ignores crossModuleDeps. \" +\n \"Use multiple modules if cross-module access is needed: \" +\n \"createSystem({ modules: { ... } })\",\n );\n }\n\n // Warn if tickMs set without tick event handler\n if (options.tickMs && options.tickMs > 0) {\n const hasTickHandler = mod.events && \"tick\" in mod.events;\n if (!hasTickHandler) {\n console.warn(\n `[Directive] tickMs is set to ${options.tickMs}ms but module has no \"tick\" event handler.`,\n );\n }\n }\n\n // Warn if snapshotModules is set (has no effect in single-module mode)\n const singleHistoryConfig =\n typeof options.history === \"object\" ? options.history : null;\n if (singleHistoryConfig?.snapshotModules) {\n console.warn(\n \"[Directive] history.snapshotModules has no effect in single-module mode. \" +\n \"Use history.snapshotEvents on the module definition instead, or switch to \" +\n \"createSystem({ modules: { ... } }) for multi-module filtering.\",\n );\n }\n }\n\n // Apply zero-config defaults if enabled\n const { history, trace, errorBoundary } = applyZeroConfigDefaults(options);\n\n // Store for hydrated facts\n let hydratedFacts: Record<string, unknown> | null = null;\n\n // Engine reference\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n let engine: any = null;\n\n // Create engine with the module directly (no prefixing needed)\n engine = createEngine({\n modules: [\n {\n id: mod.id,\n schema: mod.schema.facts,\n requirements: mod.schema.requirements,\n init: mod.init,\n derive: mod.derive,\n events: mod.events,\n effects: mod.effects,\n constraints: mod.constraints,\n resolvers: mod.resolvers,\n hooks: mod.hooks,\n meta: mod.meta,\n history: mod.history,\n },\n // biome-ignore lint/suspicious/noExplicitAny: Module format\n ] as any,\n plugins: options.plugins,\n history,\n trace,\n errorBoundary,\n tickMs: options.tickMs,\n cloud: options.cloud,\n onAfterModuleInit: () => {\n // Apply initialFacts (already validated for prototype safety above)\n if (options.initialFacts) {\n for (const [key, value] of Object.entries(options.initialFacts)) {\n if (BLOCKED_PROPS.has(key)) continue;\n (engine.facts as Record<string, unknown>)[key] = value;\n }\n }\n // Apply hydrated facts (takes precedence)\n if (hydratedFacts) {\n if (!isPrototypeSafe(hydratedFacts)) {\n if (isDevelopment) {\n console.warn(\n \"[Directive] hydrate() data contains potentially dangerous keys. Skipping.\",\n );\n }\n } else {\n for (const [key, value] of Object.entries(hydratedFacts)) {\n if (BLOCKED_PROPS.has(key)) continue;\n (engine.facts as Record<string, unknown>)[key] = value;\n }\n }\n hydratedFacts = null;\n }\n },\n });\n\n // Create events proxy for direct access\n const eventsProxy = new Proxy(\n {} as Record<string, (payload?: Record<string, unknown>) => void>,\n {\n get(_, eventName: string | symbol) {\n if (typeof eventName === \"symbol\") {\n return undefined;\n }\n if (BLOCKED_PROPS.has(eventName)) {\n return undefined;\n }\n\n return (payload?: Record<string, unknown>) => {\n engine.dispatch({ type: eventName, ...payload });\n };\n },\n has(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return mod.events ? prop in mod.events : false;\n },\n ownKeys() {\n return mod.events ? Object.keys(mod.events) : [];\n },\n getOwnPropertyDescriptor(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n if (mod.events && prop in mod.events) {\n return { configurable: true, enumerable: true };\n }\n\n return undefined;\n },\n set() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n defineProperty() {\n return false;\n },\n getPrototypeOf() {\n return null;\n },\n setPrototypeOf() {\n return false;\n },\n },\n );\n\n // Build the single module system\n let tickInterval: ReturnType<typeof setInterval> | null = null;\n const tickMs = options.tickMs;\n\n const system: SingleModuleSystem<S> = {\n _mode: \"single\",\n facts: engine.facts,\n history: engine.history,\n derive: engine.derive,\n events: eventsProxy as SingleModuleSystem<S>[\"events\"],\n constraints: engine.constraints,\n effects: engine.effects,\n resolvers: engine.resolvers,\n\n async hydrate(\n loader: () => Promise<Record<string, unknown>> | Record<string, unknown>,\n ) {\n if (engine.isRunning) {\n throw new Error(\n \"[Directive] hydrate() must be called before start(). \" +\n \"The system is already running.\",\n );\n }\n\n const result = await loader();\n if (result && typeof result === \"object\") {\n hydratedFacts = result as Record<string, unknown>;\n }\n },\n\n initialize(): void {\n engine.initialize();\n },\n\n start(): void {\n engine.start();\n\n if (tickMs && tickMs > 0) {\n const hasTickHandler = mod.events && \"tick\" in mod.events;\n if (hasTickHandler) {\n tickInterval = setInterval(() => {\n engine.dispatch({ type: \"tick\" });\n }, tickMs);\n }\n }\n },\n\n stop(): void {\n if (tickInterval) {\n clearInterval(tickInterval);\n tickInterval = null;\n }\n engine.stop();\n },\n\n destroy(): void {\n this.stop();\n engine.destroy();\n },\n\n registerModule(moduleDef: ModuleDef<ModuleSchema>): void {\n // biome-ignore lint/suspicious/noExplicitAny: Engine registerModule type\n (engine as any).registerModule({\n id: moduleDef.id,\n schema: moduleDef.schema.facts,\n requirements: moduleDef.schema.requirements,\n init: moduleDef.init,\n derive: moduleDef.derive,\n events: moduleDef.events,\n effects: moduleDef.effects,\n constraints: moduleDef.constraints,\n resolvers: moduleDef.resolvers,\n hooks: moduleDef.hooks,\n history: moduleDef.history,\n });\n },\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing\n } as any;\n\n bindEnginePassthroughs(system, engine);\n warnIfNotStarted(system);\n\n return system;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/plugins/audit-ledger/sink.ts","../src/plugins/audit-ledger/hash.ts","../src/plugins/audit-ledger/predicate-redact.ts","../src/plugins/audit-ledger/types.ts","../src/plugins/audit-ledger/verify.ts","../src/plugins/audit-ledger/index.ts"],"names":["parseRangeBound","v","t","matchesFilter","entry","filter","a","b","start","end","memorySink","opts","capacity","entries","truncateHandler","dropped","limit","out","i","e","n","path","opts2","id","tombstoneFactory","count","handler","LEDGER_INTERNAL_TOKEN","freezeEntry","key","clause","syncHash","hashObject","hashForEntry","replaceAtPath","root","dottedPath","value","segs","part","m","m2","cur","seg","lastSeg","redactWhenSpec","spec","capturePII","piiTaggedFacts","cloned","walkPredicate","factPath","op","_operand","operandPath","HASH_ALGO","verify","sink","erasedSeqsSet","prevHash","prevEntry","entryIsTombstone","prevIsTombstone","candidates","forged","tombstoneEntry","result","createAuditLedger","userRedact","seq","lastHashCache","system","unobserve","whenSpecCache","whenSourceCache","refreshWhenSpecCache","inspect","constraints","mergedDefs","c","def","whenFn","refreshPIITags","meta","tagged","redactValue","redactClauses","clauses","mutated","inner","emit","partial","finalEntry","onEvent","event","whenSpec","whenSourceHash","emittingTruncate","attach","sys","droppedSeq","droppedCount","detach","plugin","type","snapshot","from","to","stripInternal","clone","stripInternalAll","needsClone","snap","erasedAt","tombstone","filterShape","markerEntry"],"mappings":"wEAiBA,SAASA,CAAAA,CAAgBC,CAAAA,CAAmC,CAC1D,GAAIA,CAAAA,YAAa,KAAM,OAAOA,CAAAA,CAAE,OAAA,EAAQ,CACxC,GAAI,OAAOA,GAAM,QAAA,CAAU,CACzB,GAAI,CAAC,MAAA,CAAO,QAAA,CAASA,CAAC,CAAA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ACtC,CAAA,CACA,KAAA,EAAQ,CACN3D,CAAAA,CAAK,KAAA,EAAM,CACXY,EAAM,CAAA,CACNC,CAAAA,CAAgB,KAClB,CAAA,CACA,OAAA,EAAU,CACRgC,CAAAA,EAAO,CACP7C,CAAAA,CAAK,OAAA,GACP,CACF,CACF","file":"chunk-AV6S27PU.js","sourcesContent":["/**\n * `memorySink()` — bounded ring-buffer implementation of\n * `AuditLedgerSink`. Drops the oldest entry past `capacity`\n * (default 10,000), exposes a truncation hook so the ledger plugin\n * can emit a `system.truncated` marker before the shift, and\n * supports in-place tombstone erasure for GDPR Art. 17.\n *\n * Pure storage layer — no hash chain awareness, no PII redaction.\n * The plugin in `./index.ts` owns those concerns and routes them\n * through this sink via `write()` / `erase()`.\n */\n\nimport type { AuditEntry, AuditLedgerSink, QueryFilter } from \"./types.js\";\n\nconst DEFAULT_MEMORY_CAPACITY = 10_000;\nconst DEFAULT_QUERY_LIMIT = 1000;\n\nfunction parseRangeBound(v: string | number | Date): number {\n if (v instanceof Date) return v.getTime();\n if (typeof v === \"number\") {\n if (!Number.isFinite(v)) {\n throw new Error(\n `[Directive] audit-ledger: changedBetween bound must be a finite number, ISO string, or Date.`,\n );\n }\n\n return v;\n }\n if (typeof v === \"string\") {\n const t = Date.parse(v);\n if (!Number.isFinite(t)) {\n throw new Error(\n `[Directive] audit-ledger: changedBetween bound \"${v}\" is not a parseable ISO date string.`,\n );\n }\n\n return t;\n }\n throw new Error(\n `[Directive] audit-ledger: changedBetween bound must be a number, ISO string, or Date.`,\n );\n}\n\nexport function matchesFilter(entry: AuditEntry, filter: QueryFilter): boolean {\n if (filter.kind) {\n const kinds = Array.isArray(filter.kind) ? filter.kind : [filter.kind];\n if (!kinds.includes(entry.kind)) return false;\n }\n if (filter.factPath !== undefined) {\n // Exact match — no LIKE wildcards. (SEC M2)\n if (entry.kind === \"fact.change\") {\n if (entry.key !== filter.factPath) return false;\n } else if (entry.kind === \"resolver.write.rejected\") {\n if (entry.fact !== filter.factPath) return false;\n } else {\n return false;\n }\n }\n if (filter.constraintId !== undefined) {\n if (entry.kind !== \"constraint.evaluate\") return false;\n if (entry.constraintId !== filter.constraintId) return false;\n }\n if (filter.changedBetween) {\n const [a, b] = filter.changedBetween;\n const start = parseRangeBound(a);\n const end = parseRangeBound(b);\n if (entry.ts < start || entry.ts > end) return false;\n }\n\n return true;\n}\n\n/**\n * In-memory bounded ring-buffer sink. Drops oldest entries past\n * `capacity` (default 10,000). Use this as the default sink for dev,\n * tests, and StackBlitz demos.\n */\nexport function memorySink(\n opts: { capacity?: number } = {},\n): AuditLedgerSink {\n const capacity = opts.capacity ?? DEFAULT_MEMORY_CAPACITY;\n let entries: AuditEntry[] = [];\n let truncateHandler:\n | ((droppedSeq: number, droppedCount: number) => void)\n | null = null;\n\n const sink: AuditLedgerSink = {\n write(entry) {\n if (entries.length >= capacity) {\n // (M23) About to overflow — notify the owner BEFORE the shift\n // so the dropped seq is still known. The handler may push an\n // entry of its own (a truncation marker), which will itself\n // push us over capacity; we shift one for one until we're back\n // at capacity (handlers must be O(1) writers — typically one).\n const dropped = entries[0]!;\n truncateHandler?.(dropped.seq, 1);\n entries.shift();\n }\n entries.push(entry);\n // If the handler wrote a marker (entries.length now > capacity),\n // drop one more from the head to keep us at capacity exactly.\n while (entries.length > capacity) {\n entries.shift();\n }\n },\n query(filter) {\n const limit = filter.limit ?? DEFAULT_QUERY_LIMIT;\n const out: AuditEntry[] = [];\n for (let i = entries.length - 1; i >= 0; i--) {\n const e = entries[i]!;\n if (matchesFilter(e, filter)) {\n out.push(e);\n if (out.length >= limit) break;\n }\n }\n\n return out;\n },\n recent(n) {\n const start = Math.max(0, entries.length - n);\n\n return entries.slice(start);\n },\n forFact(path, opts2 = {}) {\n return this.query({ factPath: path, limit: opts2.limit });\n },\n forConstraint(id, opts2 = {}) {\n return this.query({ constraintId: id, limit: opts2.limit });\n },\n toJSON() {\n return { entries: entries.slice(), capturedAt: Date.now() };\n },\n clear() {\n entries = [];\n },\n destroy() {\n entries = [];\n truncateHandler = null;\n },\n erase(filter, tombstoneFactory) {\n let count = 0;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i]!;\n if (matchesFilter(e, filter)) {\n entries[i] = tombstoneFactory(e);\n count++;\n }\n }\n\n return count;\n },\n onTruncate(handler) {\n truncateHandler = handler;\n },\n };\n\n return sink;\n}\n","/**\n * Hash chain primitives — canonicalization, djb2 dispatch, depth-2\n * freeze, and the in-module tombstone sentinel.\n *\n * `LEDGER_INTERNAL_TOKEN` is the heart of the tombstone-forgery defense\n * (N7). It MUST live in this single file and MUST NOT be re-exported\n * from the folder's public surface (`./index.ts`). The only external\n * surface that touches it is `verify()` and the tombstone factory in\n * `index.ts`, both of which import it directly from this module.\n *\n * Hash chain: each entry stores `prevHash` — the djb2 (`hashObject`)\n * hash of the previous entry's stable-stringified payload. Tampering\n * with any entry's payload breaks the next entry's `prevHash` link —\n * visible in `verify()`. v1 ships sync djb2 only; `verify({ strong: true })`\n * is reserved for v2 (SHA-256) and throws today.\n */\n\nimport { hashObject } from \"../../utils/utils.js\";\nimport type { AuditEntry } from \"./types.js\";\n\n/**\n * Private sentinel stamped onto tombstone entries by {@link createAuditLedger.erase}.\n * Never exported from the folder's barrel, never serialized — `verify()`\n * checks for it before accepting a `system.entry-erased` entry as a\n * legitimate chain break.\n *\n * (N7) Without this, a caller holding a raw `AuditLedgerSink` reference\n * could write `{ kind: \"system.entry-erased\", … }` directly into the\n * sink to mask real tampering as legitimate erasure. The sentinel\n * raises the bar so only the in-process ledger plugin (which lives in\n * this folder's closure) can mint a valid tombstone.\n *\n * @internal — DO NOT re-export from `./index.ts` or `./types.ts`.\n */\nexport const LEDGER_INTERNAL_TOKEN: unique symbol = Symbol(\n \"directive.audit-ledger.internal\",\n);\n\n/**\n * Depth-2 freeze: freeze the entry, freeze each top-level value, and\n * freeze each clause in `whenExplain`. Cycle-safe + cheap; prevents\n * in-process payload mutation that would forge the chain. (C3)\n */\nexport function freezeEntry(entry: AuditEntry): AuditEntry {\n for (const key of Object.keys(entry)) {\n const v = (entry as unknown as Record<string, unknown>)[key];\n if (v !== null && typeof v === \"object\") {\n if (Array.isArray(v) && key === \"whenExplain\") {\n for (const clause of v) {\n if (clause !== null && typeof clause === \"object\") {\n Object.freeze(clause);\n }\n }\n }\n Object.freeze(v);\n }\n }\n Object.freeze(entry);\n\n return entry;\n}\n\n// ============================================================================\n// Hash chain — canonicalization\n// ============================================================================\n//\n// `syncHash(entry)` calls `hashObject(entry)` which calls\n// `stableStringify(entry)` — every entry shape (seq, ts, kind, prevHash,\n// hashAlgo, ...payload) is canonicalized via key-sorted JSON, then\n// djb2-hashed to a 32-bit hex string.\n//\n// - Fast, sync, isomorphic Node/Bun/Deno/browser.\n// - Tamper-DETECTION against accidental + light adversarial probing.\n// - Collision-prone against a determined attacker, by design (32 bits).\n//\n// Any future change to the canonicalization or hash function breaks\n// existing exports, so each entry carries `hashAlgo: \"djb2-1\"`. Verifiers\n// must check that tag matches what they expect.\n//\n// `verify({ strong: true })` is reserved for v2 (SHA-256 chain via Web\n// Crypto). It throws today — there is no silent fallback. v1 ships sync\n// djb2 only.\n\nfunction syncHash(entry: AuditEntry): string {\n // stableStringify guarantees same hash across runtimes regardless of\n // key insertion order (architecture review #11, security review C1).\n return hashObject(entry);\n}\n\n/**\n * Dispatch to the right hash function based on the entry's `hashAlgo`\n * discriminator. v1 has a single arm (`djb2-1`); the switch is in\n * place so v2 can add `\"sha256-1\"` without touching call sites. (N5)\n *\n * v2 promise: when SHA-256 lands, this becomes `case \"sha256-1\": return\n * await asyncSha256(entry);` — verify() will become async accordingly.\n */\nexport function hashForEntry(entry: AuditEntry): string {\n switch (entry.hashAlgo) {\n case \"djb2-1\":\n return syncHash(entry);\n default:\n throw new Error(\n `[Directive] audit-ledger: unknown hashAlgo \"${String((entry as { hashAlgo: unknown }).hashAlgo)}\" on entry seq=${entry.seq}. Cannot verify chain integrity. Known algorithms: \"djb2-1\".`,\n );\n }\n}\n","/**\n * PII operand redaction for cached predicate specs.\n *\n * Cached `whenSpec` operand pointers (e.g. `{ email: { $eq:\n * \"alice@x.com\" } }`) flow into every `constraint.evaluate` entry —\n * without scrubbing, the email would land in the audit trail in\n * plaintext on every evaluation. (C2)\n *\n * `redactWhenSpec` deep-clones the spec, walks it via `walkPredicate`,\n * and replaces operand values at PII-tagged fact paths with\n * `\"[redacted]\"`. Best-effort: if the spec contains anything\n * non-JSON-serialisable, we return the original (the caller has\n * already snapshotted the reference).\n */\n\nimport { walkPredicate } from \"../../core/predicate.js\";\n\n/**\n * Navigate `root` to `dottedPath` (`foo.bar.$eq`, `foo[0].value`) and\n * replace the value at the leaf. Used by `redactWhenSpec` to scrub\n * PII operands in cached predicate specs. Best-effort: silently no-ops\n * if the path doesn't resolve (caller already cloned the spec).\n */\nfunction replaceAtPath(root: unknown, dottedPath: string, value: unknown): void {\n if (root === null || typeof root !== \"object\") return;\n // Split on \".\" but treat \"[N]\" segments as array indices.\n // E.g. \"[0].value\" → [\"[0]\", \"value\"], \"foo.bar[1]\" → [\"foo\", \"bar[1]\"].\n const segs: Array<string | number> = [];\n for (const part of dottedPath.split(\".\")) {\n if (!part) continue;\n // Pull leading `[N]` if present.\n const m = part.match(/^\\[(\\d+)\\](.*)$/);\n if (m) {\n segs.push(Number(m[1]));\n if (m[2]) segs.push(m[2].replace(/^\\./, \"\"));\n continue;\n }\n // Trailing `[N]` on the segment.\n const m2 = part.match(/^([^[]+)\\[(\\d+)\\](.*)$/);\n if (m2) {\n segs.push(m2[1]!);\n segs.push(Number(m2[2]));\n if (m2[3]) segs.push(m2[3].replace(/^\\./, \"\"));\n continue;\n }\n segs.push(part);\n }\n\n let cur: unknown = root;\n for (let i = 0; i < segs.length - 1; i++) {\n const seg = segs[i]!;\n if (cur === null || typeof cur !== \"object\") return;\n cur = (cur as Record<string | number, unknown>)[seg];\n }\n if (cur === null || typeof cur !== \"object\") return;\n const lastSeg = segs[segs.length - 1];\n if (lastSeg === undefined) return;\n (cur as Record<string | number, unknown>)[lastSeg] = value;\n}\n\n/**\n * Walk a predicate spec and replace operands at PII-tagged fact paths\n * with `\"[redacted]\"`. Returns the input as-is when redaction is\n * disabled (`capturePII: true`) or no PII tags are registered;\n * otherwise returns a deep clone with the leaf values rewritten. (C2)\n */\nexport function redactWhenSpec(\n spec: unknown,\n capturePII: boolean,\n piiTaggedFacts: ReadonlySet<string>,\n): unknown {\n if (capturePII || piiTaggedFacts.size === 0) return spec;\n if (spec === null || typeof spec !== \"object\") return spec;\n\n // Deep-clone so we don't mutate the user's source predicate. JSON\n // round-trip handles plain objects + arrays cheaply; predicates are\n // already JSON-safe (validatePredicate enforces this).\n let cloned: unknown;\n try {\n cloned = JSON.parse(JSON.stringify(spec));\n } catch {\n // Spec contained something non-serializable; bail rather than crash.\n return spec;\n }\n\n walkPredicate(cloned, {\n operator(factPath, op, _operand, operandPath) {\n if (!piiTaggedFacts.has(factPath)) return;\n // Navigate cloned tree to operandPath and replace value.\n replaceAtPath(cloned, operandPath, \"[redacted]\");\n void op;\n },\n literal(factPath) {\n if (!piiTaggedFacts.has(factPath)) return;\n // Replace bare-value leaf at this factPath.\n replaceAtPath(cloned, factPath, \"[redacted]\");\n },\n });\n\n return cloned;\n}\n","/**\n * Audit-ledger type definitions — entry shapes, sink interface, query\n * filter, verify result, and plugin options. Pure types + the two\n * schema-version constants (`HASH_ALGO`, `SCHEMA_VERSION`) that are\n * referenced by the entry shape.\n *\n * Kept free of runtime imports so the hash/freeze/sink modules can pull\n * types from here without a cycle.\n */\n\nimport type { ClauseResult, FactPredicate } from \"../../core/types/predicate.js\";\nimport type {\n ModuleSchema,\n Plugin,\n} from \"../../core/types.js\";\n\n// ============================================================================\n// Version stamps\n// ============================================================================\n\n/** Hash algorithm tag — bumped if canonicalization or hash function changes. */\nexport const HASH_ALGO = \"djb2-1\" as const;\n\n/**\n * Entry schema version. Bumped if `AuditEntry` field shape changes in\n * a way that breaks back-compat parsers. Persisted on every entry so\n * exports remain self-describing across library upgrades. (F-5)\n */\nexport const SCHEMA_VERSION = 1 as const;\n\n// ============================================================================\n// AuditEntry types\n// ============================================================================\n\nexport type AuditEntryKind =\n | \"constraint.evaluate\"\n | \"resolver.write.rejected\"\n | \"fact.change\"\n | \"resolver.complete\"\n | \"resolver.error\"\n | \"system.init\"\n | \"system.start\"\n | \"system.stop\"\n | \"system.destroy\"\n | \"system.snapshot\"\n | \"system.history.navigate\"\n | \"system.truncated\"\n | \"system.entry-erased\"\n | \"system.subject-erased\";\n\n/**\n * Internal sentinel symbol type. The actual symbol VALUE lives in\n * `hash.ts` and is never exported from this folder's public surface —\n * but the TYPE must be referenceable here so `AuditEntryBase` can\n * declare the optional `__internal` field.\n *\n * We use `symbol` rather than `typeof LEDGER_INTERNAL_TOKEN` because\n * importing the symbol value into types.ts would either re-export it\n * (defeating the defense) or create a circular import. The runtime\n * check in `verify()` compares against the actual symbol reference.\n */\ntype LedgerInternalSentinel = symbol;\n\ninterface AuditEntryBase {\n /** Monotonic sequence number, starting at 0. */\n readonly seq: number;\n /** Wall-clock timestamp (ms epoch). */\n readonly ts: number;\n /** Discriminator. */\n readonly kind: AuditEntryKind;\n /** Hash of the previous entry's full payload. null on the genesis entry. */\n readonly prevHash: string | null;\n /**\n * Hash algorithm tag identifying the canonicalization + hash\n * function in use. Bumped if the algorithm or canonical form\n * changes, so exports remain verifiable across versions.\n */\n readonly hashAlgo: typeof HASH_ALGO;\n /**\n * Entry schema version — bumped if any `AuditEntry` field shape\n * changes in a way that breaks back-compat. Pair with `hashAlgo`\n * when migrating older exports. (F-5)\n */\n readonly schemaVersion: typeof SCHEMA_VERSION;\n /**\n * Private sentinel — present (and equal to the in-module token) only\n * on legitimate tombstones minted by `ledger.erase()`. Filtered out\n * of all public read paths (`query`, `recent`, `toJSON`, etc.) so\n * consumers never see or copy it. (N7)\n *\n * NOT serialized. NOT exported. Forging this from outside the module\n * is impossible without the symbol reference; `verify()` rejects any\n * `system.entry-erased` entry that lacks it.\n *\n * @internal\n */\n readonly __internal?: LedgerInternalSentinel;\n}\n\nexport type AuditEntry =\n | (AuditEntryBase & {\n kind: \"constraint.evaluate\";\n constraintId: string;\n active: boolean;\n /** Cached at ledger start from `system.inspect().constraints[].whenSpec`. Refreshed on `register()`/`assign()`/`unregister()`. May be undefined for function-form constraints (see `whenSource`). PII operands redacted unless `capturePII: true`. */\n whenSpec?: FactPredicate<unknown>;\n whenExplain?: readonly ClauseResult[];\n /**\n * For function-form constraints (no `whenSpec`), a tamper-evident\n * identity for the function. We DO NOT capture the raw source —\n * closures routinely reference secrets, API keys, or PII (e.g.\n * `if (apiKey === \"sk-live-xxx\")`) and a preview would leak them\n * into the audit log. Instead, we capture a djb2 hash of the\n * stringified function (`hashObject(String(fn))`). Auditors can\n * detect \"the function changed between deploys\" by comparing\n * hashes across entries, without ever seeing the function body.\n *\n * Informational only — NOT replayable. (N5, M22)\n */\n whenSource?: { kind: \"function\"; sourceHash: string };\n })\n | (AuditEntryBase & {\n kind: \"resolver.write.rejected\";\n rejection: \"rejection\" | \"summary\";\n resolverId: string;\n requirementId: string;\n reason: string;\n fact?: string;\n expected?: unknown;\n actual?: unknown;\n dropped?: number;\n })\n | (AuditEntryBase & {\n kind: \"fact.change\";\n key: string;\n prior: unknown;\n next: unknown;\n })\n | (AuditEntryBase & {\n kind: \"resolver.complete\";\n resolverId: string;\n requirementId: string;\n duration: number;\n })\n | (AuditEntryBase & {\n kind: \"resolver.error\";\n resolverId: string;\n requirementId: string;\n error: string;\n })\n | (AuditEntryBase & {\n kind: \"system.init\" | \"system.start\" | \"system.stop\" | \"system.destroy\";\n })\n | (AuditEntryBase & {\n kind: \"system.snapshot\";\n snapshotId: number;\n trigger: string;\n })\n | (AuditEntryBase & {\n kind: \"system.history.navigate\";\n from: number;\n to: number;\n })\n | (AuditEntryBase & {\n kind: \"system.truncated\";\n droppedSeq: number;\n droppedCount: number;\n })\n | (AuditEntryBase & {\n kind: \"system.entry-erased\";\n originalKind: AuditEntryKind;\n erasedAt: number;\n })\n | (AuditEntryBase & {\n kind: \"system.subject-erased\";\n /**\n * djb2 hash of the filter (via `hashObject(filter)`). PII-safe —\n * the raw filter values never land in the ledger. Pair with\n * `filterShape` to see which filter fields were used. (N2)\n */\n filterHash: string;\n /**\n * Stripped-values shape of the filter — captures WHICH fields were\n * present without recording their values. (N2)\n */\n filterShape: {\n factPath: boolean;\n constraintId: boolean;\n kind: AuditEntryKind | readonly AuditEntryKind[] | undefined;\n changedBetween: \"[range]\" | undefined;\n };\n erased: number;\n });\n\n// ============================================================================\n// Sink interface\n// ============================================================================\n\nexport interface QueryFilter {\n /** Exact-match fact path. */\n factPath?: string;\n /** Filter by constraint id. */\n constraintId?: string;\n /** Filter by entry kind. */\n kind?: AuditEntryKind | readonly AuditEntryKind[];\n /** Time range as `[startMs, endMs]`, ISO strings, or epoch numbers. */\n changedBetween?: [string | number | Date, string | number | Date];\n /** Maximum entries returned. Default 1000. */\n limit?: number;\n}\n\n/**\n * Verify result — chain valid OR a break with full context for tamper visualization.\n *\n * Erased entries (via `ledger.erase()`) appear as legitimate chain breaks —\n * `verify()` reports them in `erasedSeqs` and continues the walk from the\n * tombstone's own hash. Real tamper still surfaces as `valid: false`.\n *\n * Forged tombstones (a caller writes `kind: \"system.entry-erased\"`\n * directly via `sink.write()` to mask tamper as erasure) are detected:\n * legitimate tombstones carry an in-module sentinel that forgeries\n * cannot mint, so `verify()` reports them as tamper. (N7)\n */\nexport type VerifyResult =\n | {\n valid: true;\n entryCount: number;\n /**\n * Seq numbers of entries legitimately broken by `erase()`\n * tombstones. NOT timestamps — each entry pairs this seq with\n * the per-entry `system.entry-erased.erasedAt` (ms epoch) for\n * the timestamp. Empty unless the chain contains erasures.\n * (N1 + M1; renamed from `erasedAt` in R3)\n */\n erasedSeqs?: number[];\n }\n | {\n valid: false;\n brokenAt: number;\n expectedHash: string;\n actualHash: string;\n entry: AuditEntry;\n /**\n * Human-readable reason for the break — populated for cases\n * where the cause is more specific than \"hash mismatch\" (e.g.\n * tombstone forgery detected via missing sentinel).\n */\n reason?: string;\n };\n\nexport interface AuditLedgerSink {\n write(entry: AuditEntry): void;\n query(filter: QueryFilter): readonly AuditEntry[];\n recent(n: number): readonly AuditEntry[];\n forFact(path: string, opts?: { limit?: number }): readonly AuditEntry[];\n forConstraint(id: string, opts?: { limit?: number }): readonly AuditEntry[];\n toJSON(): { entries: readonly AuditEntry[]; capturedAt: number };\n clear(): void;\n destroy(): void;\n /**\n * Replace matching entries with marker entries IN PLACE (preserving seq +\n * prevHash so the hash chain still verifies — the marker is a\n * tombstone in chain terms; the chain break is what makes erasure\n * visible to `verify()`). v1 implementation matches on the same\n * `QueryFilter` shape used by `query()`. Returns the count of entries\n * replaced.\n *\n * WARNING: erases only from this sink. Any external copies (toJSON\n * exports, downstream pipelines) must be erased separately.\n */\n erase?(filter: QueryFilter, markerEntryFactory: (e: AuditEntry) => AuditEntry): number;\n /**\n * Optional hook fired by the sink BEFORE shifting the oldest entry\n * out of a bounded ring buffer. The ledger plugin uses this to emit\n * a `system.truncated` marker so an auditor sees that the log was\n * truncated and where. (M23)\n */\n onTruncate?(handler: (droppedSeq: number, droppedCount: number) => void): void;\n}\n\n// ============================================================================\n// Plugin options + public API surface\n// ============================================================================\n\nexport interface AuditLedgerOptions {\n /** Sink to write entries to. Default: in-memory ring buffer (capacity 10k). */\n sink?: AuditLedgerSink;\n /**\n * Whether to capture raw fact values (`prior`/`next` on fact.change,\n * `actual` in whenExplain). Default `false` — PII-tagged facts are\n * redacted by default. Set `true` to opt out of redaction.\n */\n capturePII?: boolean;\n /**\n * Optional caller-supplied redactor. Runs AFTER the default\n * pii-tag-based redaction. Useful for additional sanitization.\n */\n redact?: (entry: AuditEntry) => AuditEntry;\n}\n\nexport interface AuditLedger {\n /** The plugin to pass to `createSystem({ plugins: [...] })`. */\n readonly plugin: Plugin<ModuleSchema>;\n /** Query entries matching the filter. */\n query(filter?: QueryFilter): readonly AuditEntry[];\n /** Most recent N entries (chronological). */\n recent(n: number): readonly AuditEntry[];\n /** All entries that touch this fact path (exact match). */\n forFact(path: string, opts?: { limit?: number }): readonly AuditEntry[];\n /** All entries for this constraint id. */\n forConstraint(id: string, opts?: { limit?: number }): readonly AuditEntry[];\n /** Full ledger snapshot for export / serialization. */\n toJSON(): { entries: readonly AuditEntry[]; capturedAt: number };\n /**\n * Walk the hash chain genesis → tip. Returns `{ valid: true }` iff\n * every entry's `prevHash` matches the (sync, djb2-based) hash of\n * the previous entry. On break, returns the index of the first\n * broken link plus the expected vs actual hashes — feed into a\n * \"TAMPERED\" visualization.\n *\n * Erased entries (via `ledger.erase()`) appear as legitimate chain\n * breaks — `verify()` reports them in `erasedSeqs` and continues\n * the walk from the tombstone's actual hash. Real tamper still\n * surfaces as `valid: false`. (N1 + M1)\n *\n * Forged tombstones — `kind: \"system.entry-erased\"` entries written\n * directly via `sink.write()` to mask tamper — are detected as\n * forgery. Legitimate tombstones carry an in-module sentinel that\n * forgeries cannot mint. (N7)\n *\n * v1 ships sync djb2 only. `verify({ strong: true })` is reserved\n * for v2 (SHA-256) and THROWS today — there is no silent fallback.\n * Call `verify()` (no args) for tamper detection.\n */\n verify(opts?: { strong?: boolean }): VerifyResult;\n /**\n * Per-subject erasure (GDPR Art. 17 stub). Replaces matching entries\n * in this sink with `system.entry-erased` tombstones (preserving\n * seq + prevHash so verify() can resync), then appends a chained\n * `system.subject-erased` marker entry that summarises the erasure.\n *\n * Returns `{ erased, markerEntry }` — `markerEntry` is the chained\n * `system.subject-erased` summary (the N per-entry tombstones live\n * in the sink, not on the return value). (M7)\n *\n * When `erased === 0` (filter matched nothing), `markerEntry` is\n * `null` and no marker is emitted into the chain — avoids polluting\n * the audit trail with empty \"erased: 0\" records. (MAJOR-3)\n *\n * WARNING: v1 erases only from THIS sink. External copies (toJSON\n * exports, downstream pipelines, persisted backups) must be erased\n * separately. (C8)\n */\n erase(filter: QueryFilter): {\n erased: number;\n markerEntry: AuditEntry | null;\n };\n /** Empty the sink. */\n clear(): void;\n /** Unsubscribe + drop the sink. */\n destroy(): void;\n}\n","/**\n * `verify()` — walk the hash chain genesis → tip, surfacing the first\n * broken link (or accepting it as a legitimate erasure tombstone).\n *\n * Erased entries appear as legitimate breaks — their payload changed\n * so the NEXT entry's `prevHash` no longer matches. `verify()`\n * recognises a `system.entry-erased` entry bearing the in-module\n * sentinel and resyncs the walk from the tombstone's own hash.\n *\n * Forged tombstones — `kind: \"system.entry-erased\"` written directly\n * via `sink.write()` to mask real tamper — lack the sentinel and are\n * reported as `valid: false` with a `reason` describing the forgery. (N7)\n */\n\nimport { LEDGER_INTERNAL_TOKEN, hashForEntry } from \"./hash.js\";\nimport type { AuditEntry, AuditLedgerSink, VerifyResult } from \"./types.js\";\n\nexport function verify(\n sink: AuditLedgerSink,\n opts?: { strong?: boolean },\n): VerifyResult {\n // (C1) v1 ships sync djb2 only. Strong (SHA-256) verify is\n // reserved for v2 and must NOT silently no-op — the previous\n // implementation returned `{ valid: true }` regardless of the\n // chain's actual state, which lied to callers.\n if (opts?.strong === true) {\n throw new Error(\n \"[Directive] verify({ strong: true }) is reserved for v2 — v1 ships sync djb2 chain only. Use verify() (sync) for tamper detection.\",\n );\n }\n\n const { entries } = sink.toJSON();\n if (entries.length === 0) {\n return { valid: true, entryCount: 0 };\n }\n\n // Sync walk — catches anything the djb2 chain would see.\n // (N1 + M1) Erased-entry tombstones (kind: \"system.entry-erased\")\n // legitimately break the chain — the tombstone's payload differs\n // from the original entry it replaced, so the NEXT entry's\n // prevHash no longer matches. When we detect a break whose\n // PREVIOUS entry is a tombstone (or the broken entry itself is\n // one), record the seq and resync the walk from the tombstone's\n // own hash.\n //\n // (N7) Only tombstones bearing the internal sentinel are\n // recognised. A forged tombstone — `kind: \"system.entry-erased\"`\n // written directly via `sink.write()` to mask real tamper —\n // lacks the in-module symbol and is reported as tamper.\n //\n // Use a Set to dedupe — adjacent tombstones can otherwise be\n // recorded twice (once when the tombstone itself is the broken\n // entry, once when the next iteration sees its predecessor was\n // also a tombstone).\n const erasedSeqsSet = new Set<number>();\n let prevHash: string | null = null;\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i]!;\n if (entry.prevHash !== prevHash) {\n // Legitimate break? Either:\n // (a) the entry itself is the tombstone, or\n // (b) the previous entry was the tombstone whose payload\n // was rewritten by erase().\n const prevEntry = i > 0 ? entries[i - 1]! : null;\n const entryIsTombstone = entry.kind === \"system.entry-erased\";\n const prevIsTombstone = prevEntry?.kind === \"system.entry-erased\";\n\n if (entryIsTombstone || prevIsTombstone) {\n // (N7) Verify the SENTINEL on whichever entry(ies) claim\n // tombstone status. Missing sentinel ⇒ forgery ⇒ tamper.\n const candidates: AuditEntry[] = [];\n if (entryIsTombstone) candidates.push(entry);\n if (prevIsTombstone && prevEntry !== null) {\n candidates.push(prevEntry);\n }\n const forged = candidates.find(\n (e) =>\n (e as AuditEntry & { __internal?: unknown }).__internal !==\n LEDGER_INTERNAL_TOKEN,\n );\n if (forged) {\n return {\n valid: false,\n brokenAt: i,\n expectedHash: prevHash ?? \"<genesis>\",\n actualHash: entry.prevHash ?? \"<genesis>\",\n entry: forged,\n reason:\n \"tombstone forgery detected — missing internal sentinel. A 'system.entry-erased' entry was written via sink.write() rather than ledger.erase(); rejected as tamper.\",\n };\n }\n // Legitimate erasure — record the tombstone's seq and\n // resync the walk by hashing this entry as our new pointer\n // for the next iteration.\n const tombstoneEntry = entryIsTombstone ? entry : prevEntry!;\n erasedSeqsSet.add(tombstoneEntry.seq);\n prevHash = hashForEntry(entry);\n\n continue;\n }\n\n return {\n valid: false,\n brokenAt: i,\n expectedHash: prevHash ?? \"<genesis>\",\n actualHash: entry.prevHash ?? \"<genesis>\",\n entry,\n };\n }\n prevHash = hashForEntry(entry);\n }\n\n const result: {\n valid: true;\n entryCount: number;\n erasedSeqs?: number[];\n } = {\n valid: true,\n entryCount: entries.length,\n };\n if (erasedSeqsSet.size > 0) {\n result.erasedSeqs = [...erasedSeqsSet].sort((a, b) => a - b);\n }\n\n return result;\n}\n","/**\n * createAuditLedger — append-only, queryable, hash-chained\n * (djb2; SHA-256 reserved for v2) audit of every state change. For\n * forensics and \"show me why this user got that decision.\"\n *\n * Captures (per observation event):\n *\n * - `constraint.evaluate` → { whenSpec, whenExplain, active, whenSource? }\n * - `resolver.write.rejected` (rejection + summary kinds)\n * - `fact.change` → { key, prior, next }\n * - `resolver.complete` → { resolverId, requirementId, duration }\n * - `system.init` / `system.start` / `system.stop` / `system.destroy`\n * - `system.snapshot` / `system.history.navigate` (lifecycle markers)\n * - `system.truncated` (ring-buffer overflow marker)\n * - `system.entry-erased` / `system.subject-erased` (GDPR Art.17 stub)\n *\n * PII redaction: by default, fact keys whose meta carries the `pii`\n * tag (via `system.meta.byTag(\"pii\")`) have their values replaced with\n * `\"[redacted]\"` in `whenExplain.actual`, `fact.change.prior`,\n * `fact.change.next`, and the cached `whenSpec` operands. Opt out with\n * `capturePII: true`.\n *\n * Folder layout:\n * types.ts — public type surface + version stamps\n * hash.ts — djb2 dispatch + freeze helper + INTERNAL TOKEN\n * sink.ts — memorySink() ring buffer\n * predicate-redact.ts — PII-aware redactWhenSpec\n * verify.ts — tombstone-aware chain walk\n * index.ts (this) — createAuditLedger factory + plugin wiring\n */\n\nimport type { ClauseResult, FactPredicate } from \"../../core/types/predicate.js\";\nimport type {\n ModuleSchema,\n ObservationEvent,\n Plugin,\n System,\n} from \"../../core/types.js\";\nimport { hashObject } from \"../../utils/utils.js\";\nimport { LEDGER_INTERNAL_TOKEN, freezeEntry, hashForEntry } from \"./hash.js\";\nimport { redactWhenSpec } from \"./predicate-redact.js\";\nimport { memorySink } from \"./sink.js\";\nimport type {\n AuditEntry,\n AuditLedger,\n AuditLedgerOptions,\n VerifyResult,\n} from \"./types.js\";\nimport { HASH_ALGO, SCHEMA_VERSION } from \"./types.js\";\nimport { verify as verifyChain } from \"./verify.js\";\n\n// Re-export the public surface. `LEDGER_INTERNAL_TOKEN` is intentionally\n// NOT included — the tombstone-forgery defense depends on its\n// unguessability from outside this folder. (N7)\nexport { memorySink } from \"./sink.js\";\nexport type {\n AuditEntry,\n AuditEntryKind,\n AuditLedger,\n AuditLedgerOptions,\n AuditLedgerSink,\n QueryFilter,\n VerifyResult,\n} from \"./types.js\";\n\n/**\n * Create an audit ledger that subscribes to the given system's\n * observation stream. Returns a `Plugin` to install + a query/verify\n * API for the ledger.\n *\n * @example\n * ```ts\n * import { createAuditLedger } from \"@directive-run/core/plugins\";\n *\n * const ledger = createAuditLedger();\n * const system = createSystem({ module, plugins: [ledger.plugin] });\n * system.start();\n *\n * // Six months later — auditor asks \"what changed cart-total in March?\"\n * ledger.query({\n * factPath: \"cartTotal\",\n * changedBetween: [\"2026-03-01\", \"2026-04-01\"],\n * });\n *\n * // Verify nobody tampered with the ledger\n * const verdict = await ledger.verify();\n * if (!verdict.valid) {\n * console.error(\"Tamper at entry\", verdict.brokenAt);\n * }\n * ```\n */\nexport function createAuditLedger(\n opts: AuditLedgerOptions = {},\n): AuditLedger {\n const sink = opts.sink ?? memorySink();\n const capturePII = opts.capturePII ?? false;\n const userRedact = opts.redact;\n\n let seq = 0;\n let lastHashCache: string | null = null; // Cache hash of last-written entry payload\n\n let system: System<ModuleSchema> | null = null;\n let unobserve: (() => void) | null = null;\n\n /**\n * Cache of constraint.id → whenSpec (snapshotted at start, refreshed\n * on register/assign/unregister). Spec is already PII-redacted at\n * cache time, so the operand pointer that flows into every\n * `constraint.evaluate` entry can never leak. (C2)\n */\n const whenSpecCache = new Map<string, FactPredicate<unknown>>();\n\n /**\n * Cache of constraint.id → sourceHash for function-form constraints.\n * (N5, M22)\n *\n * We hash the stringified function rather than store any preview of\n * its source. Closures frequently reference secrets in scope\n * (`apiKey`, `dbPassword`, customer PII pulled from outer state) and\n * a preview would land those in the audit trail in plaintext. The\n * hash is a tamper-evident identity — auditors can verify \"this\n * constraint's source has not changed across these entries\" without\n * ever seeing the source itself.\n */\n const whenSourceCache = new Map<string, string>();\n\n /** Cache of PII-tagged fact paths. */\n const piiTaggedFacts = new Set<string>();\n\n function refreshWhenSpecCache(): void {\n whenSpecCache.clear();\n whenSourceCache.clear();\n if (!system) return;\n try {\n const inspect = (\n system as {\n inspect?: () => {\n constraints?: Array<{\n id: string;\n whenSpec?: unknown;\n when?: unknown;\n }>;\n };\n }\n ).inspect;\n if (typeof inspect !== \"function\") return;\n const inspection = inspect();\n const constraints = inspection?.constraints ?? [];\n // Best-effort access to merged constraint defs for function-form\n // source capture. Not exposed via the public type; we feature-detect.\n const mergedDefs = (\n system as {\n $internal?: {\n mergedConstraints?: Record<string, { when?: unknown }>;\n };\n }\n ).$internal?.mergedConstraints;\n for (const c of constraints) {\n if (c.whenSpec !== undefined) {\n // Redact PII operands at cache time so the cached pointer\n // flowing into evaluate entries is already safe. (C2)\n whenSpecCache.set(\n c.id,\n redactWhenSpec(\n c.whenSpec,\n capturePII,\n piiTaggedFacts,\n ) as FactPredicate<unknown>,\n );\n } else {\n // No whenSpec means function-form `when:` (or no when at\n // all). Capture a HASH of the function source rather than\n // the source itself — closures may reference secrets in\n // scope, and any preview would leak them into the audit\n // trail. (N5, M22)\n const def = mergedDefs?.[c.id];\n const whenFn = def && typeof def.when === \"function\" ? def.when : undefined;\n if (whenFn) {\n whenSourceCache.set(c.id, hashObject(String(whenFn)));\n } else if (c.when !== undefined && typeof c.when === \"function\") {\n whenSourceCache.set(c.id, hashObject(String(c.when)));\n } else {\n // Function-form constraint we couldn't reach the source\n // of. Mark it so audit entries still surface the form.\n // We hash the marker string for consistency with the\n // sourceHash field shape.\n whenSourceCache.set(c.id, hashObject(\"[function]\"));\n }\n }\n }\n } catch {\n // System not yet ready — skip silently.\n }\n }\n\n function refreshPIITags(): void {\n piiTaggedFacts.clear();\n if (capturePII || !system) return;\n try {\n const meta = (system as { meta?: { byTag?: (tag: string) => Array<{ id: string }> } }).meta;\n if (!meta || typeof meta.byTag !== \"function\") return;\n const tagged = meta.byTag(\"pii\") ?? [];\n for (const m of tagged) {\n piiTaggedFacts.add(m.id);\n }\n } catch {\n // No meta accessor — skip.\n }\n }\n\n function redactValue(factPath: string, value: unknown): unknown {\n if (capturePII) return value;\n if (piiTaggedFacts.has(factPath)) return \"[redacted]\";\n\n return value;\n }\n\n function redactClauses(\n clauses: ClauseResult[] | undefined,\n ): ClauseResult[] | undefined {\n if (!clauses) return clauses;\n if (capturePII || piiTaggedFacts.size === 0) return clauses;\n let mutated = false;\n const out: ClauseResult[] = clauses.map((c) => {\n if (piiTaggedFacts.has(c.path)) {\n mutated = true;\n return { ...c, actual: \"[redacted]\" };\n }\n // Recurse into combinator children.\n if (c.children) {\n const inner = redactClauses(c.children);\n if (inner !== c.children) {\n mutated = true;\n return { ...c, children: inner };\n }\n }\n\n return c;\n });\n\n return mutated ? out : clauses;\n }\n\n /**\n * `partial` is the entry-specific payload (no seq/ts/prevHash). It's\n * typed as `Record<string, unknown>` because TS's distributed Omit\n * over the AuditEntry discriminated union doesn't compose cleanly;\n * runtime construction is safe because each call site passes a\n * known-shape literal.\n *\n * Entries are deeply-frozen at write time (depth 2 — top-level\n * values + whenExplain clauses) so that downstream consumers cannot\n * mutate payloads in place and forge the chain. (C3)\n */\n function emit(partial: Record<string, unknown>): AuditEntry {\n const entry = {\n ...partial,\n seq: seq++,\n ts: Date.now(),\n prevHash: lastHashCache,\n hashAlgo: HASH_ALGO,\n schemaVersion: SCHEMA_VERSION,\n } as AuditEntry;\n\n const finalEntry = userRedact ? userRedact(entry) : entry;\n freezeEntry(finalEntry);\n sink.write(finalEntry);\n\n // Sync hash of this entry — stashed as the next entry's prevHash.\n // Whole entry is hashed (including its own prevHash field) so\n // verify() can rebuild the chain deterministically.\n lastHashCache = hashForEntry(finalEntry);\n\n return finalEntry;\n }\n\n function onEvent(event: ObservationEvent): void {\n switch (event.type) {\n case \"constraint.evaluate\": {\n const whenSpec = whenSpecCache.get(event.id);\n const whenSourceHash = whenSourceCache.get(event.id);\n const partial: Record<string, unknown> = {\n kind: \"constraint.evaluate\",\n constraintId: event.id,\n active: event.active,\n whenExplain: redactClauses(event.whenExplain),\n };\n if (whenSpec !== undefined) {\n partial.whenSpec = whenSpec;\n } else if (whenSourceHash !== undefined) {\n // Function-form constraint — sourceHash is informational and\n // NOT replayable. We deliberately do NOT include any source\n // preview because closures may reference secrets in scope. (N5, M22)\n partial.whenSource = {\n kind: \"function\",\n sourceHash: whenSourceHash,\n };\n }\n emit(partial);\n break;\n }\n case \"fact.change\":\n emit({\n kind: \"fact.change\",\n key: event.key,\n prior: redactValue(event.key, event.prev),\n next: redactValue(event.key, event.next),\n });\n break;\n case \"resolver.write.rejected\":\n if (event.kind === \"summary\") {\n emit({\n kind: \"resolver.write.rejected\",\n rejection: \"summary\",\n resolverId: event.resolver,\n requirementId: event.requirementId,\n reason: event.reason,\n dropped: event.dropped,\n });\n } else {\n emit({\n kind: \"resolver.write.rejected\",\n rejection: \"rejection\",\n resolverId: event.resolver,\n requirementId: event.requirementId,\n reason: event.reason,\n fact: event.fact,\n expected: redactValue(event.fact, event.expected),\n actual: redactValue(event.fact, event.actual),\n });\n }\n break;\n case \"resolver.complete\":\n emit({\n kind: \"resolver.complete\",\n resolverId: event.resolver,\n requirementId: event.requirementId,\n duration: event.duration,\n });\n break;\n case \"resolver.error\":\n emit({\n kind: \"resolver.error\",\n resolverId: event.resolver,\n requirementId: event.requirementId,\n error: String(event.error),\n });\n break;\n case \"system.init\":\n case \"system.start\":\n case \"system.stop\":\n case \"system.destroy\":\n emit({ kind: event.type });\n break;\n default:\n // Other observation events ignored in v1 (derivation.compute,\n // requirement.created/met/canceled, effect.run/error,\n // reconcile.start/end). They're available via .observe()\n // directly if a consumer wants them.\n break;\n }\n }\n\n /**\n * Re-entrance guard for the truncation handler. The marker entry is\n * itself a write that may trigger another shift; without this we'd\n * recurse and overflow. (M23)\n */\n let emittingTruncate = false;\n\n function attach(sys: System<ModuleSchema>): void {\n system = sys;\n refreshPIITags();\n refreshWhenSpecCache();\n unobserve = sys.observe(onEvent);\n // Wire up the truncation marker — fires BEFORE the sink drops the\n // oldest entry, so the dropped seq is still known. The guard\n // prevents the marker's own write from recursing back through the\n // capacity overflow path. (M23)\n sink.onTruncate?.((droppedSeq, droppedCount) => {\n if (emittingTruncate) return;\n emittingTruncate = true;\n try {\n emit({\n kind: \"system.truncated\",\n droppedSeq,\n droppedCount,\n });\n } finally {\n emittingTruncate = false;\n }\n });\n }\n\n function detach(): void {\n if (unobserve) {\n unobserve();\n unobserve = null;\n }\n system = null;\n whenSpecCache.clear();\n whenSourceCache.clear();\n piiTaggedFacts.clear();\n }\n\n const plugin: Plugin<ModuleSchema> = {\n name: \"audit-ledger\",\n onInit(sys) {\n attach(sys as System<ModuleSchema>);\n },\n onStop() {\n // Keep the sink populated so query() works after stop, but\n // drop the subscription to avoid leaks.\n if (unobserve) {\n unobserve();\n unobserve = null;\n }\n },\n onDestroy() {\n detach();\n },\n onDefinitionRegister(type, id) {\n if (type === \"constraint\") refreshWhenSpecCache();\n if (type === \"constraint\" || type === \"resolver\" || type === \"effect\") {\n // Re-pull PII tags too — a dynamically-registered fact (rare)\n // could have brought new meta.\n refreshPIITags();\n }\n void id;\n },\n onDefinitionAssign(type, id) {\n // (C4) Constraint assigned a new spec — refresh the cache so the\n // NEXT evaluate emits the new whenSpec, not the stale one.\n if (type === \"constraint\") refreshWhenSpecCache();\n void id;\n },\n onDefinitionUnregister(type, id) {\n if (type === \"constraint\") refreshWhenSpecCache();\n void id;\n },\n onSnapshot(snapshot) {\n // (M9) Capture history snapshot as a lifecycle marker. Snapshot\n // contents (facts) are NOT included to keep the entry small and\n // avoid duplicating PII through a different channel.\n emit({\n kind: \"system.snapshot\",\n snapshotId: snapshot.id,\n trigger: snapshot.trigger,\n });\n },\n onHistoryNavigate(from, to) {\n // (M9) Capture time-travel navigation as a lifecycle marker.\n emit({\n kind: \"system.history.navigate\",\n from,\n to,\n });\n },\n };\n\n /**\n * Strip the internal sentinel from an entry before it reaches a\n * public read path. Returns a shallow clone with `__internal`\n * removed — keeps the (frozen) live entry intact for verify() while\n * making sure consumers never see the symbol. (N7)\n */\n function stripInternal(entry: AuditEntry): AuditEntry {\n if (\n (entry as AuditEntry & { __internal?: unknown }).__internal === undefined\n ) {\n return entry;\n }\n const clone = { ...entry } as AuditEntry & { __internal?: unknown };\n delete clone.__internal;\n\n return clone as AuditEntry;\n }\n\n function stripInternalAll(\n entries: readonly AuditEntry[],\n ): readonly AuditEntry[] {\n // Avoid allocating a new array unless at least one entry carries\n // the sentinel — the common case (no tombstones) is a no-op.\n let needsClone = false;\n for (const e of entries) {\n if ((e as AuditEntry & { __internal?: unknown }).__internal !== undefined) {\n needsClone = true;\n break;\n }\n }\n if (!needsClone) {\n return entries;\n }\n\n return entries.map(stripInternal);\n }\n\n return {\n plugin,\n query: (filter = {}) => stripInternalAll(sink.query(filter)),\n recent: (n) => stripInternalAll(sink.recent(n)),\n forFact: (path, opts2) => stripInternalAll(sink.forFact(path, opts2)),\n forConstraint: (id, opts2) =>\n stripInternalAll(sink.forConstraint(id, opts2)),\n toJSON: () => {\n const snap = sink.toJSON();\n\n return {\n entries: stripInternalAll(snap.entries),\n capturedAt: snap.capturedAt,\n };\n },\n verify(opts?: { strong?: boolean }): VerifyResult {\n return verifyChain(sink, opts);\n },\n erase(filter) {\n // (C8) Replace matching entries with tombstones IN PLACE, keeping\n // seq + prevHash + hashAlgo so verify() can resync the chain.\n const erasedAt = Date.now();\n let count = 0;\n if (typeof sink.erase === \"function\") {\n count = sink.erase(filter, (e) => {\n // Build a tombstone preserving the immutable chain fields.\n // Carry SCHEMA_VERSION from the original so a fresh tombstone\n // doesn't claim to be at a newer schema than the entry it\n // replaced. (F-5)\n //\n // (N7) Stamp the in-module sentinel so `verify()` can tell\n // this tombstone apart from a forgery written via\n // `sink.write({ kind: \"system.entry-erased\", … })`. The\n // sentinel is stripped from every public read path.\n const tombstone = {\n seq: e.seq,\n ts: e.ts,\n kind: \"system.entry-erased\" as const,\n prevHash: e.prevHash,\n hashAlgo: e.hashAlgo,\n schemaVersion:\n (e as AuditEntry & { schemaVersion?: typeof SCHEMA_VERSION })\n .schemaVersion ?? SCHEMA_VERSION,\n originalKind: e.kind,\n erasedAt,\n __internal: LEDGER_INTERNAL_TOKEN,\n } as AuditEntry;\n // CAUTION: replacing the payload changes the entry's hash —\n // which means the NEXT entry's prevHash will no longer match.\n // verify() recognises `system.entry-erased` as a legitimate\n // chain break and reports it in `erasedSeqs` rather than as\n // tamper. (N1 + M1)\n freezeEntry(tombstone);\n\n return tombstone;\n });\n }\n // (MAJOR-3) Skip the `system.subject-erased` marker when nothing\n // matched the filter — emitting an \"erased: 0\" marker pollutes\n // the chain with noise and confuses auditors looking for real\n // erasures.\n if (count === 0) {\n return { erased: 0, markerEntry: null };\n }\n // (N2) Don't store the raw filter — PII can land in the values\n // (e.g. `factPath: \"alice@x.com\"`). Capture a hash + a shape\n // descriptor so an auditor sees WHICH fields were used without\n // exposing the values.\n const filterShape = {\n factPath: filter.factPath !== undefined,\n constraintId: filter.constraintId !== undefined,\n kind: filter.kind,\n changedBetween:\n filter.changedBetween !== undefined\n ? (\"[range]\" as const)\n : undefined,\n };\n // Emit a single chained `system.subject-erased` marker — recorded\n // AFTER the erasure so auditors see what was removed and why.\n const markerEntry = emit({\n kind: \"system.subject-erased\",\n filterHash: hashObject(filter),\n filterShape,\n erased: count,\n });\n\n return { erased: count, markerEntry };\n },\n clear() {\n sink.clear();\n seq = 0;\n lastHashCache = null;\n },\n destroy() {\n detach();\n sink.destroy();\n },\n };\n}\n"]}
|