@directive-run/core 1.23.0 → 1.23.1
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/{chunk-WVP3GOY2.js → chunk-C3FW27S5.js} +2 -2
- package/dist/chunk-C3FW27S5.js.map +1 -0
- package/dist/{chunk-PJIIBQTK.js → chunk-QR2756CJ.js} +2 -2
- package/dist/{chunk-PJIIBQTK.js.map → chunk-QR2756CJ.js.map} +1 -1
- package/dist/{chunk-AFPLATPV.js → chunk-SERVIHA3.js} +3 -3
- package/dist/{chunk-AFPLATPV.js.map → chunk-SERVIHA3.js.map} +1 -1
- package/dist/{chunk-FCCJUQB2.cjs → chunk-UDSP7U54.cjs} +3 -3
- package/dist/{chunk-FCCJUQB2.cjs.map → chunk-UDSP7U54.cjs.map} +1 -1
- package/dist/{chunk-WKGNK4QK.cjs → chunk-UQZ2SMGS.cjs} +2 -2
- package/dist/{chunk-WKGNK4QK.cjs.map → chunk-UQZ2SMGS.cjs.map} +1 -1
- package/dist/{chunk-XKXTRVJF.cjs → chunk-WU4AXN3P.cjs} +2 -2
- package/dist/chunk-WU4AXN3P.cjs.map +1 -0
- package/dist/{index-n8oQmdOZ.d.ts → index-Bz6DOdDN.d.ts} +3 -3
- package/dist/{index-DpvgHVHR.d.cts → index-Cpgj4byM.d.cts} +3 -3
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/internals.cjs +1 -1
- package/dist/internals.js +1 -1
- package/dist/plugins/index.cjs +2 -2
- package/dist/plugins/index.d.cts +1 -1
- package/dist/plugins/index.d.ts +1 -1
- package/dist/plugins/index.js +1 -1
- package/dist/system-T6EZ6EYN.js +2 -0
- package/dist/{system-HOP37Z4V.js.map → system-T6EZ6EYN.js.map} +1 -1
- package/dist/system-V7B4YUIR.cjs +2 -0
- package/dist/{system-VZUHL56W.cjs.map → system-V7B4YUIR.cjs.map} +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.js +1 -1
- package/dist/worker.cjs +1 -1
- package/dist/worker.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-WVP3GOY2.js.map +0 -1
- package/dist/chunk-XKXTRVJF.cjs.map +0 -1
- package/dist/system-HOP37Z4V.js +0 -2
- package/dist/system-VZUHL56W.cjs +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/rules-diff.ts","../src/core/doctor.ts","../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":["toRulesMap","raw","inner","out","entry","e","KNOWN_OPS","COMBINATORS","isPlainObject","v","isOperatorObject","keys","sawKnown","k","flattenPredicate","spec","pathPrefix","clause","c","child","i","key","value","path","op","operand","isNumeric","directionFor","before","after","widthBefore","widthAfter","diffRules","options","sortedIds","constraints","summary","id","b","a","hasB","hasA","clauses","changes","sortChanges","diffClauses","stableStringify","flatB","flatA","keyOf","mapB","mapA","allKeys","direction","x","y","p","xo","yo","COMPARABLE_OPS","compareValues","da","db","deepEqual","ka","kb","compareClauses","cand","exi","candSet","exiSet","inter","candLow","candHi","exiLow","exiHi","cmp","isExistingConstraint","doctor","candidate","existing","candidateLeaves","candidateByPath","leaf","existingList","contradictions","warnings","exiLeaves","candLeaves","verdict","finding","candidatePaths","l","abortOn","bind","parseRangeBound","t","matchesFilter","filter","start","end","memorySink","opts","capacity","entries","truncateHandler","dropped","limit","n","opts2","tombstoneFactory","count","handler","LEDGER_INTERNAL_TOKEN","freezeEntry","syncHash","hashObject","hashForEntry","replaceAtPath","root","dottedPath","segs","part","m","m2","cur","seg","lastSeg","redactWhenSpec","capturePII","piiTaggedFacts","cloned","walkPredicate","factPath","_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","mergedDefs","def","whenFn","refreshPIITags","meta","tagged","redactValue","redactClauses","mutated","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":"qHA8FO,SAASA,CAAAA,CAAWC,CAAAA,CAA6C,CACtE,IAAMC,CAAAA,CACJD,CAAAA,EACA,OAAOA,CAAAA,EAAQ,QAAA,EACf,CAAC,KAAA,CAAM,OAAA,CAAQA,CAAG,CAAA,EAClB,aAAA,GAAiBA,CAAAA,CACZA,CAAAA,CAAiC,WAAA,CAClCA,CAAAA,CAEN,GAAI,KAAA,CAAM,OAAA,CAAQC,CAAK,CAAA,CAAG,CACxB,IAAMC,CAAAA,CAA+B,EAAC,CACtC,IAAA,IAAWC,CAAAA,IAASF,CAAAA,CAAO,CACzB,GAAI,CAACE,CAAAA,EAAS,OAAOA,CAAAA,EAAU,QAAA,EAAY,EAAE,IAAA,GAAQA,CAAAA,CAAAA,CACnD,MAAM,IAAI,KAAA,CACR,yEACF,CAAA,CAEF,IAAMC,CAAAA,CAAID,CAAAA,CACV,GAAI,OAAOC,CAAAA,CAAE,EAAA,EAAO,QAAA,CAClB,MAAM,IAAI,KAAA,CACR,yDACF,CAAA,CAEFF,CAAAA,CAAIE,CAAAA,CAAE,EAAE,CAAA,CAAIA,CAAAA,CAAE,SAChB,CAEA,OAAOF,CACT,CAEA,GAAID,CAAAA,EAAS,OAAOA,CAAAA,EAAU,QAAA,CAC5B,OAAOA,CAAAA,CAGT,MAAM,IAAI,KAAA,CACR,qHACF,CACF,CAMA,IAAMI,CAAAA,CAAY,IAAI,GAAA,CA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QAAA,CAAAyL,CAAAA,CACA,UAAA,CAAY7E,CACd,CAAA,CAMA,OAAAC,CAAAA,CAAY6E,CAAS,CAAA,CAEdA,CACT,CAAC,CAAA,CAAA,CAMChF,CAAAA,GAAU,CAAA,CACZ,OAAO,CAAE,MAAA,CAAQ,EAAG,WAAA,CAAa,IAAK,CAAA,CAMxC,IAAMiF,CAAAA,CAAc,CAClB,QAAA,CAAU9F,CAAAA,CAAO,QAAA,GAAa,MAAA,CAC9B,YAAA,CAAcA,CAAAA,CAAO,YAAA,GAAiB,MAAA,CACtC,IAAA,CAAMA,CAAAA,CAAO,IAAA,CACb,cAAA,CACEA,CAAAA,CAAO,cAAA,GAAmB,MAAA,CACrB,SAAA,CACD,MACR,CAAA,CAGM+F,CAAAA,CAAc1B,CAAAA,CAAK,CACvB,IAAA,CAAM,uBAAA,CACN,UAAA,CAAYnD,mBAAAA,CAAWlB,CAAM,CAAA,CAC7B,WAAA,CAAA8F,CAAAA,CACA,MAAA,CAAQjF,CACV,CAAC,CAAA,CAED,OAAO,CAAE,MAAA,CAAQA,CAAAA,CAAO,WAAA,CAAAkF,CAAY,CACtC,CAAA,CACA,KAAA,EAAQ,CACNvD,CAAAA,CAAK,KAAA,EAAM,CACXY,CAAAA,CAAM,CAAA,CACNC,CAAAA,CAAgB,KAClB,CAAA,CACA,OAAA,EAAU,CACR4B,CAAAA,EAAO,CACPzC,CAAAA,CAAK,OAAA,GACP,CACF,CACF","file":"chunk-WKGNK4QK.cjs","sourcesContent":["/**\n * Structural diff between two snapshots of a system's constraint `whenSpec`\n * map. The \"git diff for business rules\" — operates on the predicate AST\n * instead of source-text lines.\n *\n * A predicate is a tree of leaf clauses (`{ fact: operator(value) }`) and\n * combinators (`$all` / `$any` / `$not`). `diffRules` flattens both trees\n * into path-keyed leaf lists and compares: missing path → added/removed,\n * same path with different operand → changed (with relaxed/tightened\n * classification for numeric thresholds).\n *\n * Pure module — imports only utils. No engine / store / predicate-runtime\n * dependency: predicates are walked as plain JSON.\n */\n\nimport { stableStringify } from \"../utils/utils.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** A leaf clause extracted from a predicate tree, keyed by its dotted path. */\nexport interface LeafClause {\n /** Dotted path through the predicate. E.g. `phase`, `$all[0].elapsed`, `$not.paused`. */\n path: string;\n /** Operator name. `$eq` is implied for bare-value equality. */\n op: string;\n /** Operand. */\n value: unknown;\n}\n\n/** Kind of change observed for a single clause. */\nexport type ChangeKind =\n | \"added\"\n | \"removed\"\n | \"changed\"\n | \"relaxed\"\n | \"tightened\";\n\n/** A single change between two predicates at a specific path. */\nexport interface Change {\n path: string;\n kind: ChangeKind;\n before?: { op: string; value: unknown };\n after?: { op: string; value: unknown };\n}\n\n/** Status of a single constraint across the two snapshots. */\nexport type ConstraintStatus = \"added\" | \"removed\" | \"changed\" | \"unchanged\";\n\nexport interface ConstraintDiff {\n id: string;\n status: ConstraintStatus;\n /** Empty for `unchanged`. For `added` / `removed`, every leaf is listed once. */\n changes: Change[];\n}\n\nexport interface RulesDiffReport {\n constraints: ConstraintDiff[];\n summary: {\n added: number;\n removed: number;\n changed: number;\n unchanged: number;\n totalClauseChanges: number;\n };\n}\n\nexport interface DiffRulesOptions {\n before: RulesMapInput;\n after: RulesMapInput;\n}\n\n/**\n * Accepted shapes for the `before` / `after` predicate maps:\n * - A plain map `{ [constraintId]: whenSpec }`\n * - The `system.inspect().constraints` array form `Array<{ id, whenSpec? }>`\n * - Either wrapped as `{ constraints: <one-of-the-above> }`\n *\n * Anything else throws at `toRulesMap` so a bad input fails loud.\n */\nexport type RulesMapInput = unknown;\n\n// ============================================================================\n// Input normalization\n// ============================================================================\n\n/**\n * Coerce supported input shapes into a flat `Record<constraintId, whenSpec>`.\n * Constraints without a `whenSpec` (function-form `when`) are dropped with\n * an undefined entry so callers can distinguish them from absent constraints\n * if they care; the diff treats `undefined` as \"no data\" and skips clause\n * walking.\n */\nexport function toRulesMap(raw: RulesMapInput): Record<string, unknown> {\n const inner =\n raw &&\n typeof raw === \"object\" &&\n !Array.isArray(raw) &&\n \"constraints\" in raw\n ? (raw as { constraints: unknown }).constraints\n : raw;\n\n if (Array.isArray(inner)) {\n const out: Record<string, unknown> = {};\n for (const entry of inner) {\n if (!entry || typeof entry !== \"object\" || !(\"id\" in entry)) {\n throw new Error(\n \"[Directive] diffRules: array entries must be `{ id, whenSpec }` objects\",\n );\n }\n const e = entry as { id: unknown; whenSpec?: unknown };\n if (typeof e.id !== \"string\") {\n throw new Error(\n \"[Directive] diffRules: constraint `id` must be a string\",\n );\n }\n out[e.id] = e.whenSpec;\n }\n\n return out;\n }\n\n if (inner && typeof inner === \"object\") {\n return inner as Record<string, unknown>;\n }\n\n throw new Error(\n \"[Directive] diffRules: expected a `{ id: whenSpec }` map, an array of `{ id, whenSpec }`, or `{ constraints: ... }`\",\n );\n}\n\n// ============================================================================\n// Predicate flattening\n// ============================================================================\n\nconst KNOWN_OPS = new Set([\n \"$eq\",\n \"$ne\",\n \"$in\",\n \"$nin\",\n \"$exists\",\n \"$gt\",\n \"$gte\",\n \"$lt\",\n \"$lte\",\n \"$between\",\n \"$matches\",\n \"$startsWith\",\n \"$endsWith\",\n \"$contains\",\n \"$changed\",\n]);\n\nconst COMBINATORS = new Set([\"$all\", \"$any\", \"$not\"]);\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\n/**\n * Treat a value as an operator object iff it is a plain object whose keys\n * are ALL `$`-prefixed AND at least one is a known predicate operator.\n * Mirrors the runtime's `isOperatorObject` shape — diffRules walks the same\n * \"operator object\" boundary as `evaluatePredicate`.\n */\nfunction isOperatorObject(v: unknown): v is Record<string, unknown> {\n if (!isPlainObject(v)) {\n return false;\n }\n const keys = Object.keys(v);\n if (keys.length === 0) {\n return false;\n }\n let sawKnown = false;\n for (const k of keys) {\n if (!k.startsWith(\"$\")) {\n return false;\n }\n if (KNOWN_OPS.has(k)) {\n sawKnown = true;\n }\n }\n\n return sawKnown;\n}\n\n/**\n * Walk a predicate tree and emit every leaf clause with its dotted path.\n * Combinators (`$all` / `$any` / `$not`) become indexed path segments.\n * Bare-value equality (`{ phase: \"red\" }`) emits as `op: \"$eq\"`.\n *\n * Array-form predicates (`[{ fact, op, value }, ...]`) are also accepted —\n * each clause's `fact` becomes the path, the operator is `op`, and the\n * value is `value`.\n *\n * **What gets dropped:** non-object combinator children (e.g. `$not: \"red\"`\n * with a string operand instead of a predicate object), function-form\n * predicates (the engine accepts a function for `when`; this walker only\n * sees data), and bare primitive predicates (a top-level `true` or `\"x\"`).\n * The walker is a tree visitor — anything not shaped like a predicate node\n * is silently skipped, never thrown on.\n */\nexport function flattenPredicate(\n spec: unknown,\n pathPrefix = \"\",\n out: LeafClause[] = [],\n): LeafClause[] {\n if (spec === null || typeof spec !== \"object\") {\n // A leaf that isn't an object — odd as a predicate. Skip.\n return out;\n }\n\n // Array-form (PredicateClause[])\n if (Array.isArray(spec)) {\n for (const clause of spec) {\n if (\n clause &&\n typeof clause === \"object\" &&\n \"fact\" in clause &&\n \"op\" in clause\n ) {\n const c = clause as { fact: unknown; op: unknown; value: unknown };\n out.push({\n path: pathPrefix ? `${pathPrefix}.${String(c.fact)}` : String(c.fact),\n op: String(c.op),\n value: c.value,\n });\n }\n }\n\n return out;\n }\n\n // Combinator nodes\n if (\"$all\" in spec && Array.isArray((spec as { $all: unknown }).$all)) {\n const arr = (spec as { $all: unknown[] }).$all;\n arr.forEach((child, i) => {\n flattenPredicate(child, `${pathPrefix}$all[${i}]`, out);\n });\n\n return out;\n }\n if (\"$any\" in spec && Array.isArray((spec as { $any: unknown }).$any)) {\n const arr = (spec as { $any: unknown[] }).$any;\n arr.forEach((child, i) => {\n flattenPredicate(child, `${pathPrefix}$any[${i}]`, out);\n });\n\n return out;\n }\n if (\"$not\" in spec) {\n flattenPredicate(\n (spec as { $not: unknown }).$not,\n `${pathPrefix}$not`,\n out,\n );\n\n return out;\n }\n\n // Object form — walk each key\n for (const [key, value] of Object.entries(spec as Record<string, unknown>)) {\n const path = pathPrefix ? `${pathPrefix}.${key}` : key;\n\n if (isOperatorObject(value)) {\n for (const [op, operand] of Object.entries(value)) {\n out.push({ path, op, value: operand });\n }\n } else if (isPlainObject(value) && !COMBINATORS.has(key)) {\n // Nested predicate (cross-module pivot or partial-match object).\n flattenPredicate(value, path, out);\n } else {\n // Bare literal — equality.\n out.push({ path, op: \"$eq\", value });\n }\n }\n\n return out;\n}\n\n// ============================================================================\n// Direction analysis (relaxed / tightened for numeric thresholds)\n// ============================================================================\n\nfunction isNumeric(v: unknown): v is number {\n return typeof v === \"number\" && Number.isFinite(v);\n}\n\n/**\n * For numeric-threshold operators, decide whether the new value matches\n * MORE (`relaxed`) or FEWER (`tightened`) fact configurations than the\n * old one. Returns `null` when the operator/operand isn't numeric — the\n * caller falls back to `\"changed\"`.\n */\nfunction directionFor(\n op: string,\n before: unknown,\n after: unknown,\n): \"relaxed\" | \"tightened\" | null {\n switch (op) {\n case \"$gte\":\n case \"$gt\":\n // Lower bound. Lower = matches more.\n if (isNumeric(before) && isNumeric(after)) {\n if (after < before) return \"relaxed\";\n if (after > before) return \"tightened\";\n }\n return null;\n case \"$lte\":\n case \"$lt\":\n // Upper bound. Higher = matches more.\n if (isNumeric(before) && isNumeric(after)) {\n if (after > before) return \"relaxed\";\n if (after < before) return \"tightened\";\n }\n return null;\n case \"$between\": {\n // [low, high] tuple — width compared.\n if (\n Array.isArray(before) &&\n Array.isArray(after) &&\n before.length === 2 &&\n after.length === 2 &&\n isNumeric(before[0]) &&\n isNumeric(before[1]) &&\n isNumeric(after[0]) &&\n isNumeric(after[1])\n ) {\n const widthBefore = before[1] - before[0];\n const widthAfter = after[1] - after[0];\n if (widthAfter > widthBefore) return \"relaxed\";\n if (widthAfter < widthBefore) return \"tightened\";\n }\n return null;\n }\n case \"$in\":\n case \"$nin\": {\n // Set membership. Wider set = relaxed for $in, tightened for $nin.\n if (Array.isArray(before) && Array.isArray(after)) {\n if (op === \"$in\") {\n if (after.length > before.length) return \"relaxed\";\n if (after.length < before.length) return \"tightened\";\n } else {\n if (after.length > before.length) return \"tightened\";\n if (after.length < before.length) return \"relaxed\";\n }\n }\n return null;\n }\n case \"$contains\": {\n // For array operands, more allowed elements = relaxed (matches more\n // facts). For string operands the direction is ambiguous (a longer\n // substring narrows the match set; a shorter substring widens it),\n // so we leave the call to the caller — returns null → \"changed\".\n if (Array.isArray(before) && Array.isArray(after)) {\n if (after.length > before.length) return \"relaxed\";\n if (after.length < before.length) return \"tightened\";\n }\n return null;\n }\n default:\n return null;\n }\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Diff two snapshots of a system's constraint whenSpec map.\n *\n * @example\n * ```ts\n * const report = diffRules({\n * before: { blockCheckout: { cartTotal: { $gte: 100 } } },\n * after: { blockCheckout: { cartTotal: { $gte: 50 } } },\n * });\n *\n * report.constraints[0].status; // \"changed\"\n * report.constraints[0].changes[0].kind; // \"relaxed\"\n * report.summary.totalClauseChanges; // 1\n * ```\n *\n * The input shape is forgiving — either a flat `{ id: whenSpec }` map, the\n * `system.inspect().constraints` array form, or either wrapped as\n * `{ constraints: ... }`. Constraints whose `when` is a function (no\n * `whenSpec`) are tracked as added/removed but cannot be clause-diffed\n * (the function form is opaque).\n */\nexport function diffRules(options: DiffRulesOptions): RulesDiffReport {\n const before = toRulesMap(options.before);\n const after = toRulesMap(options.after);\n\n const allIds = new Set([...Object.keys(before), ...Object.keys(after)]);\n const sortedIds = [...allIds].sort();\n\n const constraints: ConstraintDiff[] = [];\n const summary = {\n added: 0,\n removed: 0,\n changed: 0,\n unchanged: 0,\n totalClauseChanges: 0,\n };\n\n for (const id of sortedIds) {\n const b = before[id];\n const a = after[id];\n const hasB = id in before;\n const hasA = id in after;\n\n if (hasB && !hasA) {\n const clauses = flattenPredicate(b);\n const changes: Change[] =\n clauses.length === 0\n ? // Function-form / opaque whenSpec — flatten yields nothing.\n // Emit one placeholder so renderers can show *something* and\n // the summary's totalClauseChanges stays non-zero for the\n // removed constraint.\n [{ path: \"(function-form predicate)\", kind: \"removed\" }]\n : clauses.map((c) => ({\n path: c.path,\n kind: \"removed\",\n before: { op: c.op, value: c.value },\n }));\n sortChanges(changes);\n constraints.push({ id, status: \"removed\", changes });\n summary.removed++;\n summary.totalClauseChanges += changes.length;\n continue;\n }\n\n if (!hasB && hasA) {\n const clauses = flattenPredicate(a);\n const changes: Change[] =\n clauses.length === 0\n ? [{ path: \"(function-form predicate)\", kind: \"added\" }]\n : clauses.map((c) => ({\n path: c.path,\n kind: \"added\",\n after: { op: c.op, value: c.value },\n }));\n sortChanges(changes);\n constraints.push({ id, status: \"added\", changes });\n summary.added++;\n summary.totalClauseChanges += changes.length;\n continue;\n }\n\n // Both sides have it — clause-level diff.\n const changes = diffClauses(b, a);\n if (changes.length === 0) {\n constraints.push({ id, status: \"unchanged\", changes: [] });\n summary.unchanged++;\n } else {\n constraints.push({ id, status: \"changed\", changes });\n summary.changed++;\n summary.totalClauseChanges += changes.length;\n }\n }\n\n return { constraints, summary };\n}\n\n/**\n * Diff two predicate trees and return the list of leaf-level changes.\n * Exported for reuse beyond the full per-constraint report.\n */\nexport function diffClauses(before: unknown, after: unknown): Change[] {\n // Function-form predicates (anything not walkable) → skip clause walk,\n // but report a single \"changed\" placeholder so callers see something\n // happened at this constraint.\n if (\n before !== undefined &&\n after !== undefined &&\n (before === null ||\n after === null ||\n typeof before !== \"object\" ||\n typeof after !== \"object\")\n ) {\n return stableStringify(before) === stableStringify(after)\n ? []\n : [\n {\n path: \"\",\n kind: \"changed\",\n before: { op: \"$eq\", value: before },\n after: { op: \"$eq\", value: after },\n },\n ];\n }\n\n const flatB = before === undefined ? [] : flattenPredicate(before);\n const flatA = after === undefined ? [] : flattenPredicate(after);\n\n // Key by `path + op` so two different operators on the same path (rare\n // but possible in the array form) are tracked independently.\n const keyOf = (c: LeafClause) => `${c.path}::${c.op}`;\n\n const mapB = new Map<string, LeafClause>(flatB.map((c) => [keyOf(c), c]));\n const mapA = new Map<string, LeafClause>(flatA.map((c) => [keyOf(c), c]));\n\n const allKeys = new Set([...mapB.keys(), ...mapA.keys()]);\n const changes: Change[] = [];\n\n for (const key of allKeys) {\n const b = mapB.get(key);\n const a = mapA.get(key);\n\n if (b && !a) {\n changes.push({\n path: b.path,\n kind: \"removed\",\n before: { op: b.op, value: b.value },\n });\n continue;\n }\n if (!b && a) {\n changes.push({\n path: a.path,\n kind: \"added\",\n after: { op: a.op, value: a.value },\n });\n continue;\n }\n if (b && a) {\n if (stableStringify(b.value) === stableStringify(a.value)) {\n continue;\n }\n const direction = directionFor(b.op, b.value, a.value);\n changes.push({\n path: b.path,\n kind: direction ?? \"changed\",\n before: { op: b.op, value: b.value },\n after: { op: a.op, value: a.value },\n });\n }\n }\n\n sortChanges(changes);\n\n return changes;\n}\n\n/**\n * Deterministic ordering for change lists: primary key is path, secondary\n * is operator (so two clauses sharing a path — possible in the array form\n * with multiple operators on one fact — order stably). Two byte-identical\n * inputs always produce byte-identical outputs.\n */\nfunction sortChanges(changes: Change[]): void {\n changes.sort((x, y) => {\n const p = x.path.localeCompare(y.path);\n if (p !== 0) return p;\n const xo = x.before?.op ?? x.after?.op ?? \"\";\n const yo = y.before?.op ?? y.after?.op ?? \"\";\n\n return xo.localeCompare(yo);\n });\n}\n","/**\n * doctor — \"this rule contradicts an existing rule\" gate (v1 stub).\n *\n * Walks a candidate FactPredicate against an existing system's\n * constraint set (via `system.inspect().constraints`), flagging:\n *\n * - **direct contradiction:** same fact path, opposite-direction\n * comparison (`$gte 50` vs `$lt 50` — they cannot both fire).\n * Reported under `contradictions`.\n * - **subset:** candidate's range is a strict subset of an existing\n * constraint's range (candidate `$gte 100` when existing already\n * has `$gte 50`; the new rule is redundant). Reported under\n * `warnings` — a redundant rule is not a contradiction, just noise.\n * - **overlap:** shares ≥1 fact path with non-trivial intersection —\n * a warning, not a hard error.\n *\n * Pairs with `predicateFromIntent`: an LLM-emitted predicate can be\n * doctor-checked before assignment, and contradictions fed back into\n * the LLM's retry prompt.\n *\n * This is a **structural** v1. Full SMT-lite (Z3.wasm) is deferred to\n * a dedicated R4.B sprint; the primitive of \"doctor says no\" is what\n * this slice ships. False negatives are acceptable (no contradiction\n * reported when one exists in semantics that the structural checker\n * can't see). False positives (contradiction reported where none\n * exists) are NOT acceptable — every reported contradiction must be\n * defensible.\n *\n * **v1 scope LIMITATION (M4):** `checkAgainst` operates on predicate\n * logic only. It does NOT consult `bind:` / `abortOn:` resolver\n * metadata — a candidate that would *write* to a fact in another\n * constraint's abort-binding will not be flagged here. Use\n * `doctor.checkAbortOn()` for that gate.\n *\n * **INVARIANT (M11):** `checkAgainst` depends on `flattenPredicate`\n * emitting `{ path, op, value }` LeafClause shape — if that shape ever\n * changes, every comparison below silently breaks. See\n * `doctor-leaf-shape.contract.test.ts`.\n *\n * Pure, sync, no engine dependency.\n */\n\nimport { type LeafClause, flattenPredicate } from \"./rules-diff.js\";\nimport type { FactPredicate } from \"./types/predicate.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type ContradictionType = \"direct\" | \"subset\" | \"overlap\";\n\nexport interface Contradiction {\n /** ID of the existing constraint that conflicts with the candidate. */\n readonly constraintId: string;\n /** Type of contradiction detected. */\n readonly type: ContradictionType;\n /** Human-readable explanation, suitable for showing to a user or LLM. */\n readonly reason: string;\n /** Path on the candidate predicate that triggered the finding. */\n readonly candidatePath?: string;\n /** Operator + value on the candidate side. */\n readonly candidate?: { op: string; value: unknown };\n /** Operator + value on the existing side. */\n readonly existing?: { op: string; value: unknown };\n}\n\nexport interface CheckAgainstResult {\n /**\n * Hard contradictions — candidate never co-fires with existing rule.\n * Includes only `type: \"direct\"` findings. Redundancy (`type: \"subset\"`)\n * lives under `warnings` — a redundant rule is noise, not a conflict.\n */\n readonly contradictions: readonly Contradiction[];\n /**\n * Soft findings — shared facts with non-trivial intersection\n * (`type: \"overlap\"`) AND subset redundancy (`type: \"subset\"`).\n */\n readonly warnings: readonly Contradiction[];\n}\n\n/** Shape of `system.inspect().constraints[N]` we care about — accepts any superset. */\nexport interface ExistingConstraint {\n readonly id: string;\n readonly whenSpec?: unknown;\n /**\n * Fact paths the constraint's resolver aborts on when changed\n * mid-flight, if exposed by the inspect API. Consulted by\n * {@link doctor.checkAbortOn} to flag candidates that would write to\n * fields under another constraint's abort-binding. Optional — older\n * inspect payloads omit it.\n */\n readonly abortOn?: readonly string[];\n /** Same as {@link abortOn} but for the bind: side of binding metadata. */\n readonly bind?: readonly string[];\n}\n\n/**\n * Returned by {@link doctor.checkAbortOn}.\n *\n * `severity` matches the {@link Contradiction} discriminator on\n * {@link CheckAgainstResult} so callers can route both shapes\n * uniformly: by default, abort-binding collisions are `\"warning\"`\n * (the engine still has a runtime gate), but a caller can promote them\n * to `\"error\"` for stricter pre-deploy linting. (M5)\n */\nexport interface CheckAbortOnFinding {\n readonly constraintId: string;\n /** The fact path on the candidate predicate that triggered the finding. */\n readonly candidatePath: string;\n /** The binding side it would collide with: \"abortOn\" or \"bind\". */\n readonly source: \"abortOn\" | \"bind\";\n readonly reason: string;\n /**\n * Severity discriminator — `\"warning\"` by default (the engine has\n * its own runtime gate), `\"error\"` reserved for callers that want\n * strict pre-deploy lints. (M5)\n */\n readonly severity?: \"error\" | \"warning\";\n}\n\n/**\n * Result of {@link doctor.checkAbortOn}.\n *\n * AbortOn-/bind- collisions are warnings, not contradictions — the\n * engine itself enforces the runtime binding gate, so a pre-deploy\n * doctor pass treats them as advisory. The\n * {@link CheckAbortOnFinding.severity} discriminator anticipates v2\n * promotion of findings to errors. (M5, F-3)\n */\nexport interface CheckAbortOnResult {\n /**\n * AbortOn-/bind- collisions surfaced by {@link doctor.checkAbortOn}.\n * Empty when constraints expose no `abortOn:` / `bind:` metadata or\n * the candidate's fact paths don't overlap.\n */\n readonly warnings: readonly CheckAbortOnFinding[];\n}\n\n// ============================================================================\n// Operator polarity (for direct-contradiction detection)\n// ============================================================================\n\nconst COMPARABLE_OPS = new Set([\n \"$eq\",\n \"$ne\",\n \"$gt\",\n \"$gte\",\n \"$lt\",\n \"$lte\",\n \"$in\",\n \"$nin\",\n]);\n\n/**\n * Numeric comparison: returns -1 if a < b, 0 if equal, 1 if a > b, NaN\n * if not comparable. Compares numbers, bigints, dates, strings lex.\n */\nfunction compareValues(a: unknown, b: unknown): number {\n if (a === b) return 0;\n if (typeof a === \"number\" && typeof b === \"number\") {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n if (typeof a === \"bigint\" && typeof b === \"bigint\") {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n if (a instanceof Date && b instanceof Date) {\n const da = a.getTime();\n const db = b.getTime();\n\n return da < db ? -1 : da > db ? 1 : 0;\n }\n if (typeof a === \"string\" && typeof b === \"string\") {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n\n return Number.NaN;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== typeof b) return false;\n if (a === null || b === null) return false;\n if (typeof a !== \"object\") return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n\n return true;\n }\n const ka = Object.keys(a as object);\n const kb = Object.keys(b as object);\n if (ka.length !== kb.length) return false;\n for (const k of ka) {\n if (\n !deepEqual(\n (a as Record<string, unknown>)[k],\n (b as Record<string, unknown>)[k],\n )\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n// ============================================================================\n// Per-path contradiction check\n// ============================================================================\n\n/**\n * Given two clauses on the same fact path, return the contradiction\n * type (or null when they don't contradict / overlap).\n *\n * @example\n * candidate `$gte 100` vs existing `$lt 50` → \"direct\"\n * candidate `$gte 100` vs existing `$gte 50` → \"subset\"\n * candidate `$gte 50` vs existing `$lt 100` → \"overlap\"\n * candidate `$eq \"a\"` vs existing `$ne \"a\"` → \"direct\"\n */\nexport function compareClauses(\n cand: LeafClause,\n exi: LeafClause,\n): { type: ContradictionType; reason: string } | null {\n // Only structurally-comparable operators are decidable here.\n if (!COMPARABLE_OPS.has(cand.op) || !COMPARABLE_OPS.has(exi.op)) {\n // Shared path with non-comparable operators → soft overlap.\n return { type: \"overlap\", reason: `Both rules touch \"${cand.path}\".` };\n }\n\n // ---- $eq / $ne pairs ----\n if (cand.op === \"$eq\" && exi.op === \"$eq\") {\n if (deepEqual(cand.value, exi.value)) {\n return {\n type: \"subset\",\n reason: `Both rules require ${cand.path} = ${JSON.stringify(cand.value)} — candidate is redundant.`,\n };\n }\n\n return {\n type: \"direct\",\n reason: `Candidate requires ${cand.path} = ${JSON.stringify(cand.value)} but an existing rule requires ${cand.path} = ${JSON.stringify(exi.value)} — they cannot both fire.`,\n };\n }\n if (cand.op === \"$eq\" && exi.op === \"$ne\") {\n if (deepEqual(cand.value, exi.value)) {\n return {\n type: \"direct\",\n reason: `Candidate requires ${cand.path} = ${JSON.stringify(cand.value)} but an existing rule excludes that value.`,\n };\n }\n\n return null;\n }\n if (cand.op === \"$ne\" && exi.op === \"$eq\") {\n if (deepEqual(cand.value, exi.value)) {\n return {\n type: \"direct\",\n reason: `Candidate excludes ${cand.path} = ${JSON.stringify(cand.value)} but an existing rule requires that exact value.`,\n };\n }\n\n return null;\n }\n\n // ---- $in / $nin pairs ----\n if (cand.op === \"$in\" && exi.op === \"$in\") {\n const candSet = new Set(Array.isArray(cand.value) ? cand.value : []);\n const exiSet = new Set(Array.isArray(exi.value) ? exi.value : []);\n const inter = [...candSet].filter((v) => exiSet.has(v));\n if (inter.length === 0) {\n return {\n type: \"direct\",\n reason: `Candidate $in set for ${cand.path} (${JSON.stringify([...candSet])}) and existing $in set (${JSON.stringify([...exiSet])}) have no values in common — the candidate can never fire while the existing rule holds.`,\n };\n }\n if (inter.length === candSet.size && inter.length < exiSet.size) {\n return {\n type: \"subset\",\n reason: `Candidate $in set for ${cand.path} is a strict subset of the existing rule's $in set.`,\n };\n }\n\n return null;\n }\n\n // ---- Order comparisons: $gt / $gte / $lt / $lte ----\n // Two range comparisons over the same fact; check for empty intersection.\n const candLow =\n cand.op === \"$gt\" || cand.op === \"$gte\" ? cand.value : undefined;\n const candHi =\n cand.op === \"$lt\" || cand.op === \"$lte\" ? cand.value : undefined;\n const exiLow = exi.op === \"$gt\" || exi.op === \"$gte\" ? exi.value : undefined;\n const exiHi = exi.op === \"$lt\" || exi.op === \"$lte\" ? exi.value : undefined;\n\n // candidate lower bound vs existing upper bound — disjoint?\n if (candLow !== undefined && exiHi !== undefined) {\n const cmp = compareValues(candLow, exiHi);\n if (!Number.isNaN(cmp)) {\n if (cmp > 0 || (cmp === 0 && (cand.op === \"$gt\" || exi.op === \"$lt\"))) {\n return {\n type: \"direct\",\n reason: `Candidate requires ${cand.path} ${cand.op === \"$gt\" ? \">\" : \"≥\"} ${JSON.stringify(candLow)} but an existing rule caps it at ${exi.op === \"$lt\" ? \"<\" : \"≤\"} ${JSON.stringify(exiHi)}.`,\n };\n }\n }\n }\n\n // existing lower bound vs candidate upper bound — disjoint?\n if (exiLow !== undefined && candHi !== undefined) {\n const cmp = compareValues(exiLow, candHi);\n if (!Number.isNaN(cmp)) {\n if (cmp > 0 || (cmp === 0 && (exi.op === \"$gt\" || cand.op === \"$lt\"))) {\n return {\n type: \"direct\",\n reason: `Candidate caps ${cand.path} at ${cand.op === \"$lt\" ? \"<\" : \"≤\"} ${JSON.stringify(candHi)} but an existing rule requires it ${exi.op === \"$gt\" ? \">\" : \"≥\"} ${JSON.stringify(exiLow)}.`,\n };\n }\n }\n }\n\n // Same direction → check subset.\n if (candLow !== undefined && exiLow !== undefined) {\n const cmp = compareValues(candLow, exiLow);\n if (!Number.isNaN(cmp) && cmp > 0) {\n return {\n type: \"subset\",\n reason: `Candidate's lower bound on ${cand.path} (${JSON.stringify(candLow)}) is stricter than the existing rule's lower bound (${JSON.stringify(exiLow)}) — candidate is a subset.`,\n };\n }\n }\n if (candHi !== undefined && exiHi !== undefined) {\n const cmp = compareValues(candHi, exiHi);\n if (!Number.isNaN(cmp) && cmp < 0) {\n return {\n type: \"subset\",\n reason: `Candidate's upper bound on ${cand.path} (${JSON.stringify(candHi)}) is stricter than the existing rule's upper bound (${JSON.stringify(exiHi)}) — candidate is a subset.`,\n };\n }\n }\n\n // Fall through — overlap.\n return { type: \"overlap\", reason: `Both rules constrain \"${cand.path}\".` };\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\nfunction isExistingConstraint(v: unknown): v is ExistingConstraint {\n return (\n typeof v === \"object\" &&\n v !== null &&\n typeof (v as ExistingConstraint).id === \"string\"\n );\n}\n\nexport const doctor = {\n /**\n * Check a candidate predicate against existing constraints. Returns\n * contradictions (hard) + warnings (soft overlaps).\n *\n * @param candidate - The proposed predicate (typically LLM-emitted).\n * @param existing - Either `system.inspect().constraints` directly,\n * or any array of `{ id, whenSpec? }` shapes.\n * Constraints without `whenSpec` (function-form\n * `when:`) are skipped — they're opaque to us.\n *\n * @example\n * ```ts\n * const candidate = { cartTotal: { $gte: 100 } };\n * const report = doctor.checkAgainst(\n * candidate,\n * system.inspect().constraints,\n * );\n * // → {\n * // contradictions: [\n * // { constraintId: \"freeShipping\", type: \"subset\",\n * // reason: \"Candidate's lower bound on cartTotal...\" }\n * // ],\n * // warnings: []\n * // }\n * ```\n */\n checkAgainst<F = Record<string, unknown>>(\n candidate: FactPredicate<F>,\n existing:\n | readonly ExistingConstraint[]\n | { constraints: readonly ExistingConstraint[] },\n ): CheckAgainstResult {\n const constraints: readonly ExistingConstraint[] = Array.isArray(existing)\n ? existing\n : \"constraints\" in existing && Array.isArray(existing.constraints)\n ? existing.constraints\n : [];\n\n const candidateLeaves = flattenPredicate(candidate);\n if (candidateLeaves.length === 0) {\n return { contradictions: [], warnings: [] };\n }\n\n const candidateByPath = new Map<string, LeafClause[]>();\n for (const leaf of candidateLeaves) {\n const existingList = candidateByPath.get(leaf.path) ?? [];\n existingList.push(leaf);\n candidateByPath.set(leaf.path, existingList);\n }\n\n const contradictions: Contradiction[] = [];\n const warnings: Contradiction[] = [];\n\n for (const c of constraints) {\n if (!isExistingConstraint(c)) continue;\n if (c.whenSpec === undefined) continue; // function-form `when:` — opaque\n\n const exiLeaves = flattenPredicate(c.whenSpec);\n for (const exi of exiLeaves) {\n const candLeaves = candidateByPath.get(exi.path);\n if (!candLeaves) continue;\n for (const cand of candLeaves) {\n const verdict = compareClauses(cand, exi);\n if (!verdict) continue;\n const finding: Contradiction = {\n constraintId: c.id,\n type: verdict.type,\n reason: verdict.reason,\n candidatePath: cand.path,\n candidate: { op: cand.op, value: cand.value },\n existing: { op: exi.op, value: exi.value },\n };\n // M17: subset findings are redundancy warnings, not contradictions.\n // A candidate whose range is a strict subset of an existing rule's\n // range can still co-fire — it's noise, not a conflict.\n if (verdict.type === \"overlap\" || verdict.type === \"subset\") {\n warnings.push(finding);\n } else {\n contradictions.push(finding);\n }\n }\n }\n }\n\n return { contradictions, warnings };\n },\n\n /**\n * Flag a candidate predicate whose referenced fact paths overlap with\n * fields in another constraint's `abortOn:` list (or `bind:`-bound by\n * an existing constraint's resolvers). A v1 stub: relies on\n * `inspect()` exposing `abortOn:` / `bind:` on each constraint\n * snapshot. When that metadata is absent, this returns\n * `{ findings: [] }` — no false positives.\n *\n * **TODO (v2):** wire the engine's resolver-ownership graph through\n * `system.inspect()` so this returns real findings without manual\n * `abortOn:` annotations on inspect payloads.\n *\n * @example\n * ```ts\n * doctor.checkAbortOn(\n * { cartTotal: { $gte: 100 } },\n * system.inspect(),\n * );\n * // → { findings: [\n * // { constraintId: \"applyDiscount\", candidatePath: \"cartTotal\",\n * // source: \"abortOn\",\n * // reason: \"Constraint applyDiscount aborts on cartTotal.\" }\n * // ] }\n * ```\n */\n checkAbortOn<F = Record<string, unknown>>(\n candidate: FactPredicate<F>,\n existing:\n | readonly ExistingConstraint[]\n | { constraints: readonly ExistingConstraint[] },\n ): CheckAbortOnResult {\n const constraints: readonly ExistingConstraint[] = Array.isArray(existing)\n ? existing\n : \"constraints\" in existing && Array.isArray(existing.constraints)\n ? existing.constraints\n : [];\n\n const candidateLeaves = flattenPredicate(candidate);\n if (candidateLeaves.length === 0) {\n return { warnings: [] };\n }\n const candidatePaths = new Set(candidateLeaves.map((l) => l.path));\n\n const warnings: CheckAbortOnFinding[] = [];\n for (const c of constraints) {\n if (!isExistingConstraint(c)) continue;\n const abortOn = Array.isArray(c.abortOn) ? c.abortOn : [];\n const bind = Array.isArray(c.bind) ? c.bind : [];\n for (const path of abortOn) {\n if (candidatePaths.has(path)) {\n warnings.push({\n constraintId: c.id,\n candidatePath: path,\n source: \"abortOn\",\n reason: `Constraint \"${c.id}\" aborts on \"${path}\" — candidate would race or shadow its writes.`,\n severity: \"warning\",\n });\n }\n }\n for (const path of bind) {\n if (candidatePaths.has(path)) {\n warnings.push({\n constraintId: c.id,\n candidatePath: path,\n source: \"bind\",\n reason: `Constraint \"${c.id}\" binds \"${path}\" — candidate would write to a bound field.`,\n severity: \"warning\",\n });\n }\n }\n }\n\n // (M5, F-3) AbortOn-collisions are warnings by default — the engine\n // still enforces the runtime binding gate. v1 result shape is\n // `{ warnings }` only; the per-finding `severity` discriminator\n // anticipates v2 promotion of findings to errors without breaking\n // existing callers.\n return { warnings };\n },\n};\n","/**\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(opts: { capacity?: number } = {}): 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(\n root: unknown,\n dottedPath: string,\n value: unknown,\n): 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 { ModuleSchema, Plugin } from \"../../core/types.js\";\nimport type {\n ClauseResult,\n FactPredicate,\n} from \"../../core/types/predicate.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 | \"resolver.clobber.loop.detected\"\n | \"resolver.clobber.loop.resolved\"\n | \"fact.change\"\n | \"resolver.complete\"\n | \"resolver.error\"\n | \"source.attach\"\n | \"source.detach\"\n | \"source.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: \"resolver.clobber.loop.detected\";\n /** Multi-tenant routing key from `system.meta.systemId`. */\n systemId: string;\n fact: string;\n participants: readonly string[];\n /** Window over which `count` distinct-requirement rejections accumulated. */\n windowMs: number;\n count: number;\n severity: \"warn\" | \"error\";\n /** Sequence numbers of the contributing `resolver.write.rejected` entries. */\n rejectionSeqs: readonly number[];\n /**\n * Verdict tag from the predicate-overlap proof (when available).\n * Operands are PII-redacted upstream in the plugin before the\n * event is constructed, so the audit entry never sees raw values\n * even when `capturePII: false`.\n */\n overlapVerdict?:\n | \"matched\"\n | \"overlap\"\n | \"indeterminate\"\n | \"function-form-opaque\";\n })\n | (AuditEntryBase & {\n kind: \"resolver.clobber.loop.resolved\";\n systemId: string;\n fact: string;\n participants: readonly string[];\n /** Time between the originating `detected` event and this `resolved` entry. */\n durationMs: number;\n resolution:\n | \"no-recurrence-in-window\"\n | \"participant-disabled\"\n | \"predicate-narrowed\";\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: \"source.attach\" | \"source.detach\";\n sourceId: string;\n moduleId: string;\n })\n | (AuditEntryBase & {\n kind: \"source.error\";\n sourceId: string;\n moduleId: string;\n /**\n * `phase: \"runtime\"` (RFC 0008) flags errors the source reported\n * mid-flight via the `reportError` callback `attach` receives as\n * its second argument — distinct from lifecycle `\"attach\"` /\n * `\"cleanup\"` failures.\n */\n phase: \"attach\" | \"cleanup\" | \"runtime\";\n /**\n * Truncated error message — capped at a fixed length by the source\n * manager before it reaches the ledger. Source authors who embed\n * payloads in error messages get a bounded leak surface rather than\n * an unbounded one. Pair with the matching `source.attach` /\n * `source.detach` entries for full lifecycle context.\n */\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?(\n filter: QueryFilter,\n markerEntryFactory: (e: AuditEntry) => AuditEntry,\n ): 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?(\n handler: (droppedSeq: number, droppedCount: number) => void,\n ): 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 {\n ModuleSchema,\n ObservationEvent,\n Plugin,\n System,\n} from \"../../core/types.js\";\nimport type {\n ClauseResult,\n FactPredicate,\n} from \"../../core/types/predicate.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(opts: AuditLedgerOptions = {}): 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 =\n 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 = (\n system as { meta?: { byTag?: (tag: string) => Array<{ id: string }> } }\n ).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.clobber.loop.detected\":\n // The clobber-loop plugin already PII-redacts `predicateOverlap`\n // operands at event-construction time. We surface the verdict\n // tag here so auditors can cross-reference with the contributing\n // `rejectionSeqs` without parsing the predicate payload.\n emit({\n kind: \"resolver.clobber.loop.detected\",\n systemId: event.systemId,\n fact: event.fact,\n participants: event.participants,\n windowMs: event.windowMs,\n count: event.count,\n severity: event.severity,\n rejectionSeqs: event.rejectionSeqs,\n ...(event.predicateOverlap\n ? { overlapVerdict: event.predicateOverlap.verdict }\n : {}),\n });\n break;\n case \"resolver.clobber.loop.resolved\":\n emit({\n kind: \"resolver.clobber.loop.resolved\",\n systemId: event.systemId,\n fact: event.fact,\n participants: event.participants,\n durationMs: event.durationMs,\n resolution: event.resolution,\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 case \"source.attach\":\n case \"source.detach\":\n // Source attach/detach captures the privilege-change posture:\n // a runtime-registered source is a new ingestion endpoint, an\n // attach/detach pair bounds the period during which fact mutations\n // could have originated from this source. `source.publish` is\n // DELIBERATELY NOT captured — high-volume sources would blow up\n // the ledger; the resulting fact.change entries already encode the\n // outcome and remain queryable.\n emit({\n kind: event.type,\n sourceId: event.id,\n moduleId: event.moduleId,\n });\n break;\n case \"source.error\":\n emit({\n kind: \"source.error\",\n sourceId: event.id,\n moduleId: event.moduleId,\n phase: event.phase,\n error:\n event.error instanceof Error\n ? event.error.message\n : String(event.error),\n });\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, source.publish). They're available via\n // .observe() 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 clone.__internal = undefined;\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 (\n (e as AuditEntry & { __internal?: unknown }).__internal !== undefined\n ) {\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"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/rules-diff.ts","../src/core/doctor.ts","../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":["toRulesMap","raw","inner","out","entry","e","KNOWN_OPS","COMBINATORS","isPlainObject","v","isOperatorObject","keys","sawKnown","k","flattenPredicate","spec","pathPrefix","clause","c","child","i","key","value","path","op","operand","isNumeric","directionFor","before","after","widthBefore","widthAfter","diffRules","options","sortedIds","constraints","summary","id","b","a","hasB","hasA","clauses","changes","sortChanges","diffClauses","stableStringify","flatB","flatA","keyOf","mapB","mapA","allKeys","direction","x","y","p","xo","yo","COMPARABLE_OPS","compareValues","da","db","deepEqual","ka","kb","compareClauses","cand","exi","candSet","exiSet","inter","candLow","candHi","exiLow","exiHi","cmp","isExistingConstraint","doctor","candidate","existing","candidateLeaves","candidateByPath","leaf","existingList","contradictions","warnings","exiLeaves","candLeaves","verdict","finding","candidatePaths","l","abortOn","bind","parseRangeBound","t","matchesFilter","filter","start","end","memorySink","opts","capacity","entries","truncateHandler","dropped","limit","n","opts2","tombstoneFactory","count","handler","LEDGER_INTERNAL_TOKEN","freezeEntry","syncHash","hashObject","hashForEntry","replaceAtPath","root","dottedPath","segs","part","m","m2","cur","seg","lastSeg","redactWhenSpec","capturePII","piiTaggedFacts","cloned","walkPredicate","factPath","_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","mergedDefs","def","whenFn","refreshPIITags","meta","tagged","redactValue","redactClauses","mutated","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":"qHA8FO,SAASA,CAAAA,CAAWC,CAAAA,CAA6C,CACtE,IAAMC,CAAAA,CACJD,CAAAA,EACA,OAAOA,CAAAA,EAAQ,QAAA,EACf,CAAC,KAAA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,CAAK,CACvB,IAAA,CAAM,uBAAA,CACN,UAAA,CAAYnD,mBAAAA,CAAWlB,CAAM,CAAA,CAC7B,WAAA,CAAA8F,CAAAA,CACA,MAAA,CAAQjF,CACV,CAAC,CAAA,CAED,OAAO,CAAE,MAAA,CAAQA,CAAAA,CAAO,WAAA,CAAAkF,CAAY,CACtC,CAAA,CACA,KAAA,EAAQ,CACNvD,CAAAA,CAAK,KAAA,EAAM,CACXY,CAAAA,CAAM,CAAA,CACNC,CAAAA,CAAgB,KAClB,CAAA,CACA,OAAA,EAAU,CACR4B,CAAAA,EAAO,CACPzC,CAAAA,CAAK,OAAA,GACP,CACF,CACF","file":"chunk-UQZ2SMGS.cjs","sourcesContent":["/**\n * Structural diff between two snapshots of a system's constraint `whenSpec`\n * map. The \"git diff for business rules\" — operates on the predicate AST\n * instead of source-text lines.\n *\n * A predicate is a tree of leaf clauses (`{ fact: operator(value) }`) and\n * combinators (`$all` / `$any` / `$not`). `diffRules` flattens both trees\n * into path-keyed leaf lists and compares: missing path → added/removed,\n * same path with different operand → changed (with relaxed/tightened\n * classification for numeric thresholds).\n *\n * Pure module — imports only utils. No engine / store / predicate-runtime\n * dependency: predicates are walked as plain JSON.\n */\n\nimport { stableStringify } from \"../utils/utils.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** A leaf clause extracted from a predicate tree, keyed by its dotted path. */\nexport interface LeafClause {\n /** Dotted path through the predicate. E.g. `phase`, `$all[0].elapsed`, `$not.paused`. */\n path: string;\n /** Operator name. `$eq` is implied for bare-value equality. */\n op: string;\n /** Operand. */\n value: unknown;\n}\n\n/** Kind of change observed for a single clause. */\nexport type ChangeKind =\n | \"added\"\n | \"removed\"\n | \"changed\"\n | \"relaxed\"\n | \"tightened\";\n\n/** A single change between two predicates at a specific path. */\nexport interface Change {\n path: string;\n kind: ChangeKind;\n before?: { op: string; value: unknown };\n after?: { op: string; value: unknown };\n}\n\n/** Status of a single constraint across the two snapshots. */\nexport type ConstraintStatus = \"added\" | \"removed\" | \"changed\" | \"unchanged\";\n\nexport interface ConstraintDiff {\n id: string;\n status: ConstraintStatus;\n /** Empty for `unchanged`. For `added` / `removed`, every leaf is listed once. */\n changes: Change[];\n}\n\nexport interface RulesDiffReport {\n constraints: ConstraintDiff[];\n summary: {\n added: number;\n removed: number;\n changed: number;\n unchanged: number;\n totalClauseChanges: number;\n };\n}\n\nexport interface DiffRulesOptions {\n before: RulesMapInput;\n after: RulesMapInput;\n}\n\n/**\n * Accepted shapes for the `before` / `after` predicate maps:\n * - A plain map `{ [constraintId]: whenSpec }`\n * - The `system.inspect().constraints` array form `Array<{ id, whenSpec? }>`\n * - Either wrapped as `{ constraints: <one-of-the-above> }`\n *\n * Anything else throws at `toRulesMap` so a bad input fails loud.\n */\nexport type RulesMapInput = unknown;\n\n// ============================================================================\n// Input normalization\n// ============================================================================\n\n/**\n * Coerce supported input shapes into a flat `Record<constraintId, whenSpec>`.\n * Constraints without a `whenSpec` (function-form `when`) are dropped with\n * an undefined entry so callers can distinguish them from absent constraints\n * if they care; the diff treats `undefined` as \"no data\" and skips clause\n * walking.\n */\nexport function toRulesMap(raw: RulesMapInput): Record<string, unknown> {\n const inner =\n raw &&\n typeof raw === \"object\" &&\n !Array.isArray(raw) &&\n \"constraints\" in raw\n ? (raw as { constraints: unknown }).constraints\n : raw;\n\n if (Array.isArray(inner)) {\n const out: Record<string, unknown> = {};\n for (const entry of inner) {\n if (!entry || typeof entry !== \"object\" || !(\"id\" in entry)) {\n throw new Error(\n \"[Directive] diffRules: array entries must be `{ id, whenSpec }` objects\",\n );\n }\n const e = entry as { id: unknown; whenSpec?: unknown };\n if (typeof e.id !== \"string\") {\n throw new Error(\n \"[Directive] diffRules: constraint `id` must be a string\",\n );\n }\n out[e.id] = e.whenSpec;\n }\n\n return out;\n }\n\n if (inner && typeof inner === \"object\") {\n return inner as Record<string, unknown>;\n }\n\n throw new Error(\n \"[Directive] diffRules: expected a `{ id: whenSpec }` map, an array of `{ id, whenSpec }`, or `{ constraints: ... }`\",\n );\n}\n\n// ============================================================================\n// Predicate flattening\n// ============================================================================\n\nconst KNOWN_OPS = new Set([\n \"$eq\",\n \"$ne\",\n \"$in\",\n \"$nin\",\n \"$exists\",\n \"$gt\",\n \"$gte\",\n \"$lt\",\n \"$lte\",\n \"$between\",\n \"$matches\",\n \"$startsWith\",\n \"$endsWith\",\n \"$contains\",\n \"$changed\",\n]);\n\nconst COMBINATORS = new Set([\"$all\", \"$any\", \"$not\"]);\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\n/**\n * Treat a value as an operator object iff it is a plain object whose keys\n * are ALL `$`-prefixed AND at least one is a known predicate operator.\n * Mirrors the runtime's `isOperatorObject` shape — diffRules walks the same\n * \"operator object\" boundary as `evaluatePredicate`.\n */\nfunction isOperatorObject(v: unknown): v is Record<string, unknown> {\n if (!isPlainObject(v)) {\n return false;\n }\n const keys = Object.keys(v);\n if (keys.length === 0) {\n return false;\n }\n let sawKnown = false;\n for (const k of keys) {\n if (!k.startsWith(\"$\")) {\n return false;\n }\n if (KNOWN_OPS.has(k)) {\n sawKnown = true;\n }\n }\n\n return sawKnown;\n}\n\n/**\n * Walk a predicate tree and emit every leaf clause with its dotted path.\n * Combinators (`$all` / `$any` / `$not`) become indexed path segments.\n * Bare-value equality (`{ phase: \"red\" }`) emits as `op: \"$eq\"`.\n *\n * Array-form predicates (`[{ fact, op, value }, ...]`) are also accepted —\n * each clause's `fact` becomes the path, the operator is `op`, and the\n * value is `value`.\n *\n * **What gets dropped:** non-object combinator children (e.g. `$not: \"red\"`\n * with a string operand instead of a predicate object), function-form\n * predicates (the engine accepts a function for `when`; this walker only\n * sees data), and bare primitive predicates (a top-level `true` or `\"x\"`).\n * The walker is a tree visitor — anything not shaped like a predicate node\n * is silently skipped, never thrown on.\n */\nexport function flattenPredicate(\n spec: unknown,\n pathPrefix = \"\",\n out: LeafClause[] = [],\n): LeafClause[] {\n if (spec === null || typeof spec !== \"object\") {\n // A leaf that isn't an object — odd as a predicate. Skip.\n return out;\n }\n\n // Array-form (PredicateClause[])\n if (Array.isArray(spec)) {\n for (const clause of spec) {\n if (\n clause &&\n typeof clause === \"object\" &&\n \"fact\" in clause &&\n \"op\" in clause\n ) {\n const c = clause as { fact: unknown; op: unknown; value: unknown };\n out.push({\n path: pathPrefix ? `${pathPrefix}.${String(c.fact)}` : String(c.fact),\n op: String(c.op),\n value: c.value,\n });\n }\n }\n\n return out;\n }\n\n // Combinator nodes\n if (\"$all\" in spec && Array.isArray((spec as { $all: unknown }).$all)) {\n const arr = (spec as { $all: unknown[] }).$all;\n arr.forEach((child, i) => {\n flattenPredicate(child, `${pathPrefix}$all[${i}]`, out);\n });\n\n return out;\n }\n if (\"$any\" in spec && Array.isArray((spec as { $any: unknown }).$any)) {\n const arr = (spec as { $any: unknown[] }).$any;\n arr.forEach((child, i) => {\n flattenPredicate(child, `${pathPrefix}$any[${i}]`, out);\n });\n\n return out;\n }\n if (\"$not\" in spec) {\n flattenPredicate(\n (spec as { $not: unknown }).$not,\n `${pathPrefix}$not`,\n out,\n );\n\n return out;\n }\n\n // Object form — walk each key\n for (const [key, value] of Object.entries(spec as Record<string, unknown>)) {\n const path = pathPrefix ? `${pathPrefix}.${key}` : key;\n\n if (isOperatorObject(value)) {\n for (const [op, operand] of Object.entries(value)) {\n out.push({ path, op, value: operand });\n }\n } else if (isPlainObject(value) && !COMBINATORS.has(key)) {\n // Nested predicate (cross-module pivot or partial-match object).\n flattenPredicate(value, path, out);\n } else {\n // Bare literal — equality.\n out.push({ path, op: \"$eq\", value });\n }\n }\n\n return out;\n}\n\n// ============================================================================\n// Direction analysis (relaxed / tightened for numeric thresholds)\n// ============================================================================\n\nfunction isNumeric(v: unknown): v is number {\n return typeof v === \"number\" && Number.isFinite(v);\n}\n\n/**\n * For numeric-threshold operators, decide whether the new value matches\n * MORE (`relaxed`) or FEWER (`tightened`) fact configurations than the\n * old one. Returns `null` when the operator/operand isn't numeric — the\n * caller falls back to `\"changed\"`.\n */\nfunction directionFor(\n op: string,\n before: unknown,\n after: unknown,\n): \"relaxed\" | \"tightened\" | null {\n switch (op) {\n case \"$gte\":\n case \"$gt\":\n // Lower bound. Lower = matches more.\n if (isNumeric(before) && isNumeric(after)) {\n if (after < before) return \"relaxed\";\n if (after > before) return \"tightened\";\n }\n return null;\n case \"$lte\":\n case \"$lt\":\n // Upper bound. Higher = matches more.\n if (isNumeric(before) && isNumeric(after)) {\n if (after > before) return \"relaxed\";\n if (after < before) return \"tightened\";\n }\n return null;\n case \"$between\": {\n // [low, high] tuple — width compared.\n if (\n Array.isArray(before) &&\n Array.isArray(after) &&\n before.length === 2 &&\n after.length === 2 &&\n isNumeric(before[0]) &&\n isNumeric(before[1]) &&\n isNumeric(after[0]) &&\n isNumeric(after[1])\n ) {\n const widthBefore = before[1] - before[0];\n const widthAfter = after[1] - after[0];\n if (widthAfter > widthBefore) return \"relaxed\";\n if (widthAfter < widthBefore) return \"tightened\";\n }\n return null;\n }\n case \"$in\":\n case \"$nin\": {\n // Set membership. Wider set = relaxed for $in, tightened for $nin.\n if (Array.isArray(before) && Array.isArray(after)) {\n if (op === \"$in\") {\n if (after.length > before.length) return \"relaxed\";\n if (after.length < before.length) return \"tightened\";\n } else {\n if (after.length > before.length) return \"tightened\";\n if (after.length < before.length) return \"relaxed\";\n }\n }\n return null;\n }\n case \"$contains\": {\n // For array operands, more allowed elements = relaxed (matches more\n // facts). For string operands the direction is ambiguous (a longer\n // substring narrows the match set; a shorter substring widens it),\n // so we leave the call to the caller — returns null → \"changed\".\n if (Array.isArray(before) && Array.isArray(after)) {\n if (after.length > before.length) return \"relaxed\";\n if (after.length < before.length) return \"tightened\";\n }\n return null;\n }\n default:\n return null;\n }\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Diff two snapshots of a system's constraint whenSpec map.\n *\n * @example\n * ```ts\n * const report = diffRules({\n * before: { blockCheckout: { cartTotal: { $gte: 100 } } },\n * after: { blockCheckout: { cartTotal: { $gte: 50 } } },\n * });\n *\n * report.constraints[0].status; // \"changed\"\n * report.constraints[0].changes[0].kind; // \"relaxed\"\n * report.summary.totalClauseChanges; // 1\n * ```\n *\n * The input shape is forgiving — either a flat `{ id: whenSpec }` map, the\n * `system.inspect().constraints` array form, or either wrapped as\n * `{ constraints: ... }`. Constraints whose `when` is a function (no\n * `whenSpec`) are tracked as added/removed but cannot be clause-diffed\n * (the function form is opaque).\n */\nexport function diffRules(options: DiffRulesOptions): RulesDiffReport {\n const before = toRulesMap(options.before);\n const after = toRulesMap(options.after);\n\n const allIds = new Set([...Object.keys(before), ...Object.keys(after)]);\n const sortedIds = [...allIds].sort();\n\n const constraints: ConstraintDiff[] = [];\n const summary = {\n added: 0,\n removed: 0,\n changed: 0,\n unchanged: 0,\n totalClauseChanges: 0,\n };\n\n for (const id of sortedIds) {\n const b = before[id];\n const a = after[id];\n const hasB = id in before;\n const hasA = id in after;\n\n if (hasB && !hasA) {\n const clauses = flattenPredicate(b);\n const changes: Change[] =\n clauses.length === 0\n ? // Function-form / opaque whenSpec — flatten yields nothing.\n // Emit one placeholder so renderers can show *something* and\n // the summary's totalClauseChanges stays non-zero for the\n // removed constraint.\n [{ path: \"(function-form predicate)\", kind: \"removed\" }]\n : clauses.map((c) => ({\n path: c.path,\n kind: \"removed\",\n before: { op: c.op, value: c.value },\n }));\n sortChanges(changes);\n constraints.push({ id, status: \"removed\", changes });\n summary.removed++;\n summary.totalClauseChanges += changes.length;\n continue;\n }\n\n if (!hasB && hasA) {\n const clauses = flattenPredicate(a);\n const changes: Change[] =\n clauses.length === 0\n ? [{ path: \"(function-form predicate)\", kind: \"added\" }]\n : clauses.map((c) => ({\n path: c.path,\n kind: \"added\",\n after: { op: c.op, value: c.value },\n }));\n sortChanges(changes);\n constraints.push({ id, status: \"added\", changes });\n summary.added++;\n summary.totalClauseChanges += changes.length;\n continue;\n }\n\n // Both sides have it — clause-level diff.\n const changes = diffClauses(b, a);\n if (changes.length === 0) {\n constraints.push({ id, status: \"unchanged\", changes: [] });\n summary.unchanged++;\n } else {\n constraints.push({ id, status: \"changed\", changes });\n summary.changed++;\n summary.totalClauseChanges += changes.length;\n }\n }\n\n return { constraints, summary };\n}\n\n/**\n * Diff two predicate trees and return the list of leaf-level changes.\n * Exported for reuse beyond the full per-constraint report.\n */\nexport function diffClauses(before: unknown, after: unknown): Change[] {\n // Function-form predicates (anything not walkable) → skip clause walk,\n // but report a single \"changed\" placeholder so callers see something\n // happened at this constraint.\n if (\n before !== undefined &&\n after !== undefined &&\n (before === null ||\n after === null ||\n typeof before !== \"object\" ||\n typeof after !== \"object\")\n ) {\n return stableStringify(before) === stableStringify(after)\n ? []\n : [\n {\n path: \"\",\n kind: \"changed\",\n before: { op: \"$eq\", value: before },\n after: { op: \"$eq\", value: after },\n },\n ];\n }\n\n const flatB = before === undefined ? [] : flattenPredicate(before);\n const flatA = after === undefined ? [] : flattenPredicate(after);\n\n // Key by `path + op` so two different operators on the same path (rare\n // but possible in the array form) are tracked independently.\n const keyOf = (c: LeafClause) => `${c.path}::${c.op}`;\n\n const mapB = new Map<string, LeafClause>(flatB.map((c) => [keyOf(c), c]));\n const mapA = new Map<string, LeafClause>(flatA.map((c) => [keyOf(c), c]));\n\n const allKeys = new Set([...mapB.keys(), ...mapA.keys()]);\n const changes: Change[] = [];\n\n for (const key of allKeys) {\n const b = mapB.get(key);\n const a = mapA.get(key);\n\n if (b && !a) {\n changes.push({\n path: b.path,\n kind: \"removed\",\n before: { op: b.op, value: b.value },\n });\n continue;\n }\n if (!b && a) {\n changes.push({\n path: a.path,\n kind: \"added\",\n after: { op: a.op, value: a.value },\n });\n continue;\n }\n if (b && a) {\n if (stableStringify(b.value) === stableStringify(a.value)) {\n continue;\n }\n const direction = directionFor(b.op, b.value, a.value);\n changes.push({\n path: b.path,\n kind: direction ?? \"changed\",\n before: { op: b.op, value: b.value },\n after: { op: a.op, value: a.value },\n });\n }\n }\n\n sortChanges(changes);\n\n return changes;\n}\n\n/**\n * Deterministic ordering for change lists: primary key is path, secondary\n * is operator (so two clauses sharing a path — possible in the array form\n * with multiple operators on one fact — order stably). Two byte-identical\n * inputs always produce byte-identical outputs.\n */\nfunction sortChanges(changes: Change[]): void {\n changes.sort((x, y) => {\n const p = x.path.localeCompare(y.path);\n if (p !== 0) return p;\n const xo = x.before?.op ?? x.after?.op ?? \"\";\n const yo = y.before?.op ?? y.after?.op ?? \"\";\n\n return xo.localeCompare(yo);\n });\n}\n","/**\n * doctor — \"this rule contradicts an existing rule\" gate (v1 stub).\n *\n * Walks a candidate FactPredicate against an existing system's\n * constraint set (via `system.inspect().constraints`), flagging:\n *\n * - **direct contradiction:** same fact path, opposite-direction\n * comparison (`$gte 50` vs `$lt 50` — they cannot both fire).\n * Reported under `contradictions`.\n * - **subset:** candidate's range is a strict subset of an existing\n * constraint's range (candidate `$gte 100` when existing already\n * has `$gte 50`; the new rule is redundant). Reported under\n * `warnings` — a redundant rule is not a contradiction, just noise.\n * - **overlap:** shares ≥1 fact path with non-trivial intersection —\n * a warning, not a hard error.\n *\n * Pairs with `predicateFromIntent`: an LLM-emitted predicate can be\n * doctor-checked before assignment, and contradictions fed back into\n * the LLM's retry prompt.\n *\n * This is a **structural** v1. Full SMT-lite (Z3.wasm) is deferred to\n * a dedicated R4.B sprint; the primitive of \"doctor says no\" is what\n * this slice ships. False negatives are acceptable (no contradiction\n * reported when one exists in semantics that the structural checker\n * can't see). False positives (contradiction reported where none\n * exists) are NOT acceptable — every reported contradiction must be\n * defensible.\n *\n * **v1 scope LIMITATION (M4):** `checkAgainst` operates on predicate\n * logic only. It does NOT consult `bind:` / `abortOn:` resolver\n * metadata — a candidate that would *write* to a fact in another\n * constraint's abort-binding will not be flagged here. Use\n * `doctor.checkAbortOn()` for that gate.\n *\n * **INVARIANT (M11):** `checkAgainst` depends on `flattenPredicate`\n * emitting `{ path, op, value }` LeafClause shape — if that shape ever\n * changes, every comparison below silently breaks. See\n * `doctor-leaf-shape.contract.test.ts`.\n *\n * Pure, sync, no engine dependency.\n */\n\nimport { type LeafClause, flattenPredicate } from \"./rules-diff.js\";\nimport type { FactPredicate } from \"./types/predicate.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type ContradictionType = \"direct\" | \"subset\" | \"overlap\";\n\nexport interface Contradiction {\n /** ID of the existing constraint that conflicts with the candidate. */\n readonly constraintId: string;\n /** Type of contradiction detected. */\n readonly type: ContradictionType;\n /** Human-readable explanation, suitable for showing to a user or LLM. */\n readonly reason: string;\n /** Path on the candidate predicate that triggered the finding. */\n readonly candidatePath?: string;\n /** Operator + value on the candidate side. */\n readonly candidate?: { op: string; value: unknown };\n /** Operator + value on the existing side. */\n readonly existing?: { op: string; value: unknown };\n}\n\nexport interface CheckAgainstResult {\n /**\n * Hard contradictions — candidate never co-fires with existing rule.\n * Includes only `type: \"direct\"` findings. Redundancy (`type: \"subset\"`)\n * lives under `warnings` — a redundant rule is noise, not a conflict.\n */\n readonly contradictions: readonly Contradiction[];\n /**\n * Soft findings — shared facts with non-trivial intersection\n * (`type: \"overlap\"`) AND subset redundancy (`type: \"subset\"`).\n */\n readonly warnings: readonly Contradiction[];\n}\n\n/** Shape of `system.inspect().constraints[N]` we care about — accepts any superset. */\nexport interface ExistingConstraint {\n readonly id: string;\n readonly whenSpec?: unknown;\n /**\n * Fact paths the constraint's resolver aborts on when changed\n * mid-flight, if exposed by the inspect API. Consulted by\n * {@link doctor.checkAbortOn} to flag candidates that would write to\n * fields under another constraint's abort-binding. Optional — older\n * inspect payloads omit it.\n */\n readonly abortOn?: readonly string[];\n /** Same as {@link abortOn} but for the bind: side of binding metadata. */\n readonly bind?: readonly string[];\n}\n\n/**\n * Returned by {@link doctor.checkAbortOn}.\n *\n * `severity` matches the {@link Contradiction} discriminator on\n * {@link CheckAgainstResult} so callers can route both shapes\n * uniformly: by default, abort-binding collisions are `\"warning\"`\n * (the engine still has a runtime gate), but a caller can promote them\n * to `\"error\"` for stricter pre-deploy linting. (M5)\n */\nexport interface CheckAbortOnFinding {\n readonly constraintId: string;\n /** The fact path on the candidate predicate that triggered the finding. */\n readonly candidatePath: string;\n /** The binding side it would collide with: \"abortOn\" or \"bind\". */\n readonly source: \"abortOn\" | \"bind\";\n readonly reason: string;\n /**\n * Severity discriminator — `\"warning\"` by default (the engine has\n * its own runtime gate), `\"error\"` reserved for callers that want\n * strict pre-deploy lints. (M5)\n */\n readonly severity?: \"error\" | \"warning\";\n}\n\n/**\n * Result of {@link doctor.checkAbortOn}.\n *\n * AbortOn-/bind- collisions are warnings, not contradictions — the\n * engine itself enforces the runtime binding gate, so a pre-deploy\n * doctor pass treats them as advisory. The\n * {@link CheckAbortOnFinding.severity} discriminator anticipates v2\n * promotion of findings to errors. (M5, F-3)\n */\nexport interface CheckAbortOnResult {\n /**\n * AbortOn-/bind- collisions surfaced by {@link doctor.checkAbortOn}.\n * Empty when constraints expose no `abortOn:` / `bind:` metadata or\n * the candidate's fact paths don't overlap.\n */\n readonly warnings: readonly CheckAbortOnFinding[];\n}\n\n// ============================================================================\n// Operator polarity (for direct-contradiction detection)\n// ============================================================================\n\nconst COMPARABLE_OPS = new Set([\n \"$eq\",\n \"$ne\",\n \"$gt\",\n \"$gte\",\n \"$lt\",\n \"$lte\",\n \"$in\",\n \"$nin\",\n]);\n\n/**\n * Numeric comparison: returns -1 if a < b, 0 if equal, 1 if a > b, NaN\n * if not comparable. Compares numbers, bigints, dates, strings lex.\n */\nfunction compareValues(a: unknown, b: unknown): number {\n if (a === b) return 0;\n if (typeof a === \"number\" && typeof b === \"number\") {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n if (typeof a === \"bigint\" && typeof b === \"bigint\") {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n if (a instanceof Date && b instanceof Date) {\n const da = a.getTime();\n const db = b.getTime();\n\n return da < db ? -1 : da > db ? 1 : 0;\n }\n if (typeof a === \"string\" && typeof b === \"string\") {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n\n return Number.NaN;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== typeof b) return false;\n if (a === null || b === null) return false;\n if (typeof a !== \"object\") return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n\n return true;\n }\n const ka = Object.keys(a as object);\n const kb = Object.keys(b as object);\n if (ka.length !== kb.length) return false;\n for (const k of ka) {\n if (\n !deepEqual(\n (a as Record<string, unknown>)[k],\n (b as Record<string, unknown>)[k],\n )\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n// ============================================================================\n// Per-path contradiction check\n// ============================================================================\n\n/**\n * Given two clauses on the same fact path, return the contradiction\n * type (or null when they don't contradict / overlap).\n *\n * @example\n * candidate `$gte 100` vs existing `$lt 50` → \"direct\"\n * candidate `$gte 100` vs existing `$gte 50` → \"subset\"\n * candidate `$gte 50` vs existing `$lt 100` → \"overlap\"\n * candidate `$eq \"a\"` vs existing `$ne \"a\"` → \"direct\"\n */\nexport function compareClauses(\n cand: LeafClause,\n exi: LeafClause,\n): { type: ContradictionType; reason: string } | null {\n // Only structurally-comparable operators are decidable here.\n if (!COMPARABLE_OPS.has(cand.op) || !COMPARABLE_OPS.has(exi.op)) {\n // Shared path with non-comparable operators → soft overlap.\n return { type: \"overlap\", reason: `Both rules touch \"${cand.path}\".` };\n }\n\n // ---- $eq / $ne pairs ----\n if (cand.op === \"$eq\" && exi.op === \"$eq\") {\n if (deepEqual(cand.value, exi.value)) {\n return {\n type: \"subset\",\n reason: `Both rules require ${cand.path} = ${JSON.stringify(cand.value)} — candidate is redundant.`,\n };\n }\n\n return {\n type: \"direct\",\n reason: `Candidate requires ${cand.path} = ${JSON.stringify(cand.value)} but an existing rule requires ${cand.path} = ${JSON.stringify(exi.value)} — they cannot both fire.`,\n };\n }\n if (cand.op === \"$eq\" && exi.op === \"$ne\") {\n if (deepEqual(cand.value, exi.value)) {\n return {\n type: \"direct\",\n reason: `Candidate requires ${cand.path} = ${JSON.stringify(cand.value)} but an existing rule excludes that value.`,\n };\n }\n\n return null;\n }\n if (cand.op === \"$ne\" && exi.op === \"$eq\") {\n if (deepEqual(cand.value, exi.value)) {\n return {\n type: \"direct\",\n reason: `Candidate excludes ${cand.path} = ${JSON.stringify(cand.value)} but an existing rule requires that exact value.`,\n };\n }\n\n return null;\n }\n\n // ---- $in / $nin pairs ----\n if (cand.op === \"$in\" && exi.op === \"$in\") {\n const candSet = new Set(Array.isArray(cand.value) ? cand.value : []);\n const exiSet = new Set(Array.isArray(exi.value) ? exi.value : []);\n const inter = [...candSet].filter((v) => exiSet.has(v));\n if (inter.length === 0) {\n return {\n type: \"direct\",\n reason: `Candidate $in set for ${cand.path} (${JSON.stringify([...candSet])}) and existing $in set (${JSON.stringify([...exiSet])}) have no values in common — the candidate can never fire while the existing rule holds.`,\n };\n }\n if (inter.length === candSet.size && inter.length < exiSet.size) {\n return {\n type: \"subset\",\n reason: `Candidate $in set for ${cand.path} is a strict subset of the existing rule's $in set.`,\n };\n }\n\n return null;\n }\n\n // ---- Order comparisons: $gt / $gte / $lt / $lte ----\n // Two range comparisons over the same fact; check for empty intersection.\n const candLow =\n cand.op === \"$gt\" || cand.op === \"$gte\" ? cand.value : undefined;\n const candHi =\n cand.op === \"$lt\" || cand.op === \"$lte\" ? cand.value : undefined;\n const exiLow = exi.op === \"$gt\" || exi.op === \"$gte\" ? exi.value : undefined;\n const exiHi = exi.op === \"$lt\" || exi.op === \"$lte\" ? exi.value : undefined;\n\n // candidate lower bound vs existing upper bound — disjoint?\n if (candLow !== undefined && exiHi !== undefined) {\n const cmp = compareValues(candLow, exiHi);\n if (!Number.isNaN(cmp)) {\n if (cmp > 0 || (cmp === 0 && (cand.op === \"$gt\" || exi.op === \"$lt\"))) {\n return {\n type: \"direct\",\n reason: `Candidate requires ${cand.path} ${cand.op === \"$gt\" ? \">\" : \"≥\"} ${JSON.stringify(candLow)} but an existing rule caps it at ${exi.op === \"$lt\" ? \"<\" : \"≤\"} ${JSON.stringify(exiHi)}.`,\n };\n }\n }\n }\n\n // existing lower bound vs candidate upper bound — disjoint?\n if (exiLow !== undefined && candHi !== undefined) {\n const cmp = compareValues(exiLow, candHi);\n if (!Number.isNaN(cmp)) {\n if (cmp > 0 || (cmp === 0 && (exi.op === \"$gt\" || cand.op === \"$lt\"))) {\n return {\n type: \"direct\",\n reason: `Candidate caps ${cand.path} at ${cand.op === \"$lt\" ? \"<\" : \"≤\"} ${JSON.stringify(candHi)} but an existing rule requires it ${exi.op === \"$gt\" ? \">\" : \"≥\"} ${JSON.stringify(exiLow)}.`,\n };\n }\n }\n }\n\n // Same direction → check subset.\n if (candLow !== undefined && exiLow !== undefined) {\n const cmp = compareValues(candLow, exiLow);\n if (!Number.isNaN(cmp) && cmp > 0) {\n return {\n type: \"subset\",\n reason: `Candidate's lower bound on ${cand.path} (${JSON.stringify(candLow)}) is stricter than the existing rule's lower bound (${JSON.stringify(exiLow)}) — candidate is a subset.`,\n };\n }\n }\n if (candHi !== undefined && exiHi !== undefined) {\n const cmp = compareValues(candHi, exiHi);\n if (!Number.isNaN(cmp) && cmp < 0) {\n return {\n type: \"subset\",\n reason: `Candidate's upper bound on ${cand.path} (${JSON.stringify(candHi)}) is stricter than the existing rule's upper bound (${JSON.stringify(exiHi)}) — candidate is a subset.`,\n };\n }\n }\n\n // Fall through — overlap.\n return { type: \"overlap\", reason: `Both rules constrain \"${cand.path}\".` };\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\nfunction isExistingConstraint(v: unknown): v is ExistingConstraint {\n return (\n typeof v === \"object\" &&\n v !== null &&\n typeof (v as ExistingConstraint).id === \"string\"\n );\n}\n\nexport const doctor = {\n /**\n * Check a candidate predicate against existing constraints. Returns\n * contradictions (hard) + warnings (soft overlaps).\n *\n * @param candidate - The proposed predicate (typically LLM-emitted).\n * @param existing - Either `system.inspect().constraints` directly,\n * or any array of `{ id, whenSpec? }` shapes.\n * Constraints without `whenSpec` (function-form\n * `when:`) are skipped — they're opaque to us.\n *\n * @example\n * ```ts\n * const candidate = { cartTotal: { $gte: 100 } };\n * const report = doctor.checkAgainst(\n * candidate,\n * system.inspect().constraints,\n * );\n * // → {\n * // contradictions: [\n * // { constraintId: \"freeShipping\", type: \"subset\",\n * // reason: \"Candidate's lower bound on cartTotal...\" }\n * // ],\n * // warnings: []\n * // }\n * ```\n */\n checkAgainst<F = Record<string, unknown>>(\n candidate: FactPredicate<F>,\n existing:\n | readonly ExistingConstraint[]\n | { constraints: readonly ExistingConstraint[] },\n ): CheckAgainstResult {\n const constraints: readonly ExistingConstraint[] = Array.isArray(existing)\n ? existing\n : \"constraints\" in existing && Array.isArray(existing.constraints)\n ? existing.constraints\n : [];\n\n const candidateLeaves = flattenPredicate(candidate);\n if (candidateLeaves.length === 0) {\n return { contradictions: [], warnings: [] };\n }\n\n const candidateByPath = new Map<string, LeafClause[]>();\n for (const leaf of candidateLeaves) {\n const existingList = candidateByPath.get(leaf.path) ?? [];\n existingList.push(leaf);\n candidateByPath.set(leaf.path, existingList);\n }\n\n const contradictions: Contradiction[] = [];\n const warnings: Contradiction[] = [];\n\n for (const c of constraints) {\n if (!isExistingConstraint(c)) continue;\n if (c.whenSpec === undefined) continue; // function-form `when:` — opaque\n\n const exiLeaves = flattenPredicate(c.whenSpec);\n for (const exi of exiLeaves) {\n const candLeaves = candidateByPath.get(exi.path);\n if (!candLeaves) continue;\n for (const cand of candLeaves) {\n const verdict = compareClauses(cand, exi);\n if (!verdict) continue;\n const finding: Contradiction = {\n constraintId: c.id,\n type: verdict.type,\n reason: verdict.reason,\n candidatePath: cand.path,\n candidate: { op: cand.op, value: cand.value },\n existing: { op: exi.op, value: exi.value },\n };\n // M17: subset findings are redundancy warnings, not contradictions.\n // A candidate whose range is a strict subset of an existing rule's\n // range can still co-fire — it's noise, not a conflict.\n if (verdict.type === \"overlap\" || verdict.type === \"subset\") {\n warnings.push(finding);\n } else {\n contradictions.push(finding);\n }\n }\n }\n }\n\n return { contradictions, warnings };\n },\n\n /**\n * Flag a candidate predicate whose referenced fact paths overlap with\n * fields in another constraint's `abortOn:` list (or `bind:`-bound by\n * an existing constraint's resolvers). A v1 stub: relies on\n * `inspect()` exposing `abortOn:` / `bind:` on each constraint\n * snapshot. When that metadata is absent, this returns\n * `{ findings: [] }` — no false positives.\n *\n * **TODO (v2):** wire the engine's resolver-ownership graph through\n * `system.inspect()` so this returns real findings without manual\n * `abortOn:` annotations on inspect payloads.\n *\n * @example\n * ```ts\n * doctor.checkAbortOn(\n * { cartTotal: { $gte: 100 } },\n * system.inspect(),\n * );\n * // → { findings: [\n * // { constraintId: \"applyDiscount\", candidatePath: \"cartTotal\",\n * // source: \"abortOn\",\n * // reason: \"Constraint applyDiscount aborts on cartTotal.\" }\n * // ] }\n * ```\n */\n checkAbortOn<F = Record<string, unknown>>(\n candidate: FactPredicate<F>,\n existing:\n | readonly ExistingConstraint[]\n | { constraints: readonly ExistingConstraint[] },\n ): CheckAbortOnResult {\n const constraints: readonly ExistingConstraint[] = Array.isArray(existing)\n ? existing\n : \"constraints\" in existing && Array.isArray(existing.constraints)\n ? existing.constraints\n : [];\n\n const candidateLeaves = flattenPredicate(candidate);\n if (candidateLeaves.length === 0) {\n return { warnings: [] };\n }\n const candidatePaths = new Set(candidateLeaves.map((l) => l.path));\n\n const warnings: CheckAbortOnFinding[] = [];\n for (const c of constraints) {\n if (!isExistingConstraint(c)) continue;\n const abortOn = Array.isArray(c.abortOn) ? c.abortOn : [];\n const bind = Array.isArray(c.bind) ? c.bind : [];\n for (const path of abortOn) {\n if (candidatePaths.has(path)) {\n warnings.push({\n constraintId: c.id,\n candidatePath: path,\n source: \"abortOn\",\n reason: `Constraint \"${c.id}\" aborts on \"${path}\" — candidate would race or shadow its writes.`,\n severity: \"warning\",\n });\n }\n }\n for (const path of bind) {\n if (candidatePaths.has(path)) {\n warnings.push({\n constraintId: c.id,\n candidatePath: path,\n source: \"bind\",\n reason: `Constraint \"${c.id}\" binds \"${path}\" — candidate would write to a bound field.`,\n severity: \"warning\",\n });\n }\n }\n }\n\n // (M5, F-3) AbortOn-collisions are warnings by default — the engine\n // still enforces the runtime binding gate. v1 result shape is\n // `{ warnings }` only; the per-finding `severity` discriminator\n // anticipates v2 promotion of findings to errors without breaking\n // existing callers.\n return { warnings };\n },\n};\n","/**\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(opts: { capacity?: number } = {}): 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(\n root: unknown,\n dottedPath: string,\n value: unknown,\n): 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 { ModuleSchema, Plugin } from \"../../core/types.js\";\nimport type {\n ClauseResult,\n FactPredicate,\n} from \"../../core/types/predicate.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 | \"resolver.clobber.loop.detected\"\n | \"resolver.clobber.loop.resolved\"\n | \"fact.change\"\n | \"resolver.complete\"\n | \"resolver.error\"\n | \"source.attach\"\n | \"source.detach\"\n | \"source.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: \"resolver.clobber.loop.detected\";\n /** Multi-tenant routing key from `system.meta.systemId`. */\n systemId: string;\n fact: string;\n participants: readonly string[];\n /** Window over which `count` distinct-requirement rejections accumulated. */\n windowMs: number;\n count: number;\n severity: \"warn\" | \"error\";\n /** Sequence numbers of the contributing `resolver.write.rejected` entries. */\n rejectionSeqs: readonly number[];\n /**\n * Verdict tag from the predicate-overlap proof (when available).\n * Operands are PII-redacted upstream in the plugin before the\n * event is constructed, so the audit entry never sees raw values\n * even when `capturePII: false`.\n */\n overlapVerdict?:\n | \"matched\"\n | \"overlap\"\n | \"indeterminate\"\n | \"function-form-opaque\";\n })\n | (AuditEntryBase & {\n kind: \"resolver.clobber.loop.resolved\";\n systemId: string;\n fact: string;\n participants: readonly string[];\n /** Time between the originating `detected` event and this `resolved` entry. */\n durationMs: number;\n resolution:\n | \"no-recurrence-in-window\"\n | \"participant-disabled\"\n | \"predicate-narrowed\";\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: \"source.attach\" | \"source.detach\";\n sourceId: string;\n moduleId: string;\n })\n | (AuditEntryBase & {\n kind: \"source.error\";\n sourceId: string;\n moduleId: string;\n /**\n * `phase: \"runtime\"` (RFC 0008) flags errors the source reported\n * mid-flight via the `reportError` callback `attach` receives as\n * its second argument — distinct from lifecycle `\"attach\"` /\n * `\"cleanup\"` failures.\n */\n phase: \"attach\" | \"cleanup\" | \"runtime\";\n /**\n * Truncated error message — capped at a fixed length by the source\n * manager before it reaches the ledger. Source authors who embed\n * payloads in error messages get a bounded leak surface rather than\n * an unbounded one. Pair with the matching `source.attach` /\n * `source.detach` entries for full lifecycle context.\n */\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?(\n filter: QueryFilter,\n markerEntryFactory: (e: AuditEntry) => AuditEntry,\n ): 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?(\n handler: (droppedSeq: number, droppedCount: number) => void,\n ): 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).\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.\n *\n * WARNING: v1 erases only from THIS sink. External copies (toJSON\n * exports, downstream pipelines, persisted backups) must be erased\n * separately.\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 {\n ModuleSchema,\n ObservationEvent,\n Plugin,\n System,\n} from \"../../core/types.js\";\nimport type {\n ClauseResult,\n FactPredicate,\n} from \"../../core/types/predicate.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(opts: AuditLedgerOptions = {}): 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 =\n 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 = (\n system as { meta?: { byTag?: (tag: string) => Array<{ id: string }> } }\n ).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.clobber.loop.detected\":\n // The clobber-loop plugin already PII-redacts `predicateOverlap`\n // operands at event-construction time. We surface the verdict\n // tag here so auditors can cross-reference with the contributing\n // `rejectionSeqs` without parsing the predicate payload.\n emit({\n kind: \"resolver.clobber.loop.detected\",\n systemId: event.systemId,\n fact: event.fact,\n participants: event.participants,\n windowMs: event.windowMs,\n count: event.count,\n severity: event.severity,\n rejectionSeqs: event.rejectionSeqs,\n ...(event.predicateOverlap\n ? { overlapVerdict: event.predicateOverlap.verdict }\n : {}),\n });\n break;\n case \"resolver.clobber.loop.resolved\":\n emit({\n kind: \"resolver.clobber.loop.resolved\",\n systemId: event.systemId,\n fact: event.fact,\n participants: event.participants,\n durationMs: event.durationMs,\n resolution: event.resolution,\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 case \"source.attach\":\n case \"source.detach\":\n // Source attach/detach captures the privilege-change posture:\n // a runtime-registered source is a new ingestion endpoint, an\n // attach/detach pair bounds the period during which fact mutations\n // could have originated from this source. `source.publish` is\n // DELIBERATELY NOT captured — high-volume sources would blow up\n // the ledger; the resulting fact.change entries already encode the\n // outcome and remain queryable.\n emit({\n kind: event.type,\n sourceId: event.id,\n moduleId: event.moduleId,\n });\n break;\n case \"source.error\":\n emit({\n kind: \"source.error\",\n sourceId: event.id,\n moduleId: event.moduleId,\n phase: event.phase,\n error:\n event.error instanceof Error\n ? event.error.message\n : String(event.error),\n });\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, source.publish). They're available via\n // .observe() 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 clone.__internal = undefined;\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 (\n (e as AuditEntry & { __internal?: unknown }).__internal !== undefined\n ) {\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 // Skip the `system.subject-erased` marker when nothing matched\n // the filter — emitting an \"erased: 0\" marker pollutes the chain\n // with noise and confuses auditors looking for real 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"]}
|