@directive-run/core 1.9.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/adapter-utils.d.cts +1 -1
  2. package/dist/adapter-utils.d.ts +1 -1
  3. package/dist/audit-ledger-9IElAHH9.d.ts +205 -0
  4. package/dist/audit-ledger-qMjEBqiP.d.cts +205 -0
  5. package/dist/chunk-26Z5VNPZ.js +16 -0
  6. package/dist/{chunk-FCOZCTLY.js.map → chunk-26Z5VNPZ.js.map} +1 -1
  7. package/dist/chunk-4VZOZWXM.cjs +2 -0
  8. package/dist/chunk-4VZOZWXM.cjs.map +1 -0
  9. package/dist/chunk-7NMXRATK.cjs +3 -0
  10. package/dist/chunk-7NMXRATK.cjs.map +1 -0
  11. package/dist/chunk-7TSYQEN3.js +2 -0
  12. package/dist/chunk-7TSYQEN3.js.map +1 -0
  13. package/dist/{chunk-2OS4RCLV.cjs → chunk-EX3XG667.cjs} +3 -3
  14. package/dist/{chunk-2OS4RCLV.cjs.map → chunk-EX3XG667.cjs.map} +1 -1
  15. package/dist/chunk-TPOKS4RY.js +3 -0
  16. package/dist/chunk-TPOKS4RY.js.map +1 -0
  17. package/dist/{helpers-BwAThjnJ.d.ts → helpers-D2pfb6vT.d.ts} +1 -1
  18. package/dist/{helpers-CG27mEGG.d.cts → helpers-hh6UanB1.d.cts} +1 -1
  19. package/dist/index.cjs +4 -4
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +344 -4
  22. package/dist/index.d.ts +344 -4
  23. package/dist/index.js +4 -4
  24. package/dist/index.js.map +1 -1
  25. package/dist/internals.cjs +1 -1
  26. package/dist/internals.d.cts +4 -4
  27. package/dist/internals.d.ts +4 -4
  28. package/dist/internals.js +1 -1
  29. package/dist/plugins/index.cjs +2 -2
  30. package/dist/plugins/index.cjs.map +1 -1
  31. package/dist/plugins/index.d.cts +2 -1
  32. package/dist/plugins/index.d.ts +2 -1
  33. package/dist/plugins/index.js +2 -2
  34. package/dist/plugins/index.js.map +1 -1
  35. package/dist/{plugins-DvrsPhzx.d.cts → plugins-Ykl_sAPE.d.cts} +1 -1
  36. package/dist/{plugins-DvrsPhzx.d.ts → plugins-Ykl_sAPE.d.ts} +1 -1
  37. package/dist/system-GK3NSFQH.cjs +2 -0
  38. package/dist/{system-DEMPYZHI.cjs.map → system-GK3NSFQH.cjs.map} +1 -1
  39. package/dist/system-VZWB6WXX.js +2 -0
  40. package/dist/{system-R4JL6U4S.js.map → system-VZWB6WXX.js.map} +1 -1
  41. package/dist/testing.cjs +1 -1
  42. package/dist/testing.d.cts +1 -1
  43. package/dist/testing.d.ts +1 -1
  44. package/dist/testing.js +1 -1
  45. package/dist/worker.cjs +1 -1
  46. package/dist/worker.d.cts +1 -1
  47. package/dist/worker.d.ts +1 -1
  48. package/dist/worker.js +1 -1
  49. package/package.json +1 -1
  50. package/dist/chunk-FCOZCTLY.js +0 -16
  51. package/dist/chunk-WIZHZF4G.cjs +0 -3
  52. package/dist/chunk-WIZHZF4G.cjs.map +0 -1
  53. package/dist/chunk-ZE2RY5KP.js +0 -3
  54. package/dist/chunk-ZE2RY5KP.js.map +0 -1
  55. package/dist/system-DEMPYZHI.cjs +0 -2
  56. package/dist/system-R4JL6U4S.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/replay-under.ts","../src/core/sweep-under.ts","../src/core/rules-diff.ts","../src/core/predicate-to-sql.ts","../src/core/predicate-to-mongo.ts","../src/core/predicate-to-pgrest.ts","../src/core/schema-builders.ts","../src/core/module.ts","../src/utils/requirement-status.ts","../src/utils/system-with-status.ts","../src/core/clock.ts","../src/core/timer.ts","../src/index.ts"],"names":["MAX_REPLAY_FRAMES","validateReplaySpec","spec","which","validatePredicate","err","message","isPredicate","preview","unknownOp","walkPredicate","_factPath","op","PREDICATE_OPERATORS","key","PREDICATE_COMBINATORS","toReplayFrames","raw","framesFromHistory","list","entry","index","frame","out","historyExport","parsed","framesFromSnapshots","exportObj","snapshots","i","s","replayUnder","options","frames","original","proposed","entityKey","requested","maxSamples","originalMatched","proposedMatched","newMatchCount","lostMatchCount","unchanged","newMatches","lostMatches","originalEntities","proposedEntities","prevFacts","facts","originalBit","evaluatePredicate","proposedBit","buildSample","report","sample","evaluatePredicateExplained","MAX_SWEEP_POINTS","MAX_SWEEP_EVALUATIONS","isHole","v","substitute","template","values","path","depth","MAX_PREDICATE_DEPTH","name","k","cartesian","keys","sweep","head","rest","headValues","tail","gridSize","size","arr","sweepUnder","objective","r","total","evaluations","warnedObjective","safeObjective","baselineReport","baseline","points","bestIndex","bestScore","score","best","toRulesMap","inner","e","KNOWN_OPS","COMBINATORS","isPlainObject","isOperatorObject","sawKnown","flattenPredicate","pathPrefix","clause","c","child","value","operand","isNumeric","directionFor","before","after","widthBefore","widthAfter","diffRules","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","IDENT_RE","assertIdentifier","kind","assertAllowed","allowed","validateSelect","select","col","nextParam","ctx","renderOp","column","escapeLike","operator","assertNoSiblingKeys","combinator","sibs","buildWhere","parts","DEFAULT_PLACEHOLDER","predicateToSQL","predicate","table","allowedKeys","placeholder","projection","where","predicateToWhere","escapeRegex","FIELD_RE","FIELD_DOTTED_RE","assertFieldName","opts","field","translateOp","buildQuery","obj","conflicts","translated","existing","andClauses","merged","predicateToMongo","assertColumn","encodeValue","encodeList","escapeLikeOperand","colClause","opAndValue","groupClause","logical","renderColumnOps","atTop","lo","hi","build","encodeClause","eq","predicateToPostgrest","mode","createSchemaType","validators","typeName","defaultValue","transform","description","refinements","meta","fn","createChainableType","fieldMeta","intermediate","desc","newRefinements","m","unionImpl","types","typeNames","schemaType","t","createChainableString","fm","n","regex","createChainableNumber","createChainableArray","elementType","indexRef","chainable","ref","et","newRef","validator","createChainableObject","shapeSchema","schemaT","dev_true_default","valueSet","innerType","innerTypeName","valueType","valueTypeName","val","uuidRegex","emailRegex","validateModuleId","validateKeyAlignment","implKeys","schemaKeys","implLabel","schemaLabel","missingImplMessage","validateSnapshotEvents","snapshotEvents","schemaEvents","schemaEventKeys","eventName","validateResolverRequirements","resolvers","requirements","requirementTypes","resolverName","resolver","resolverDef","validatePivotNameConflicts","config","factKeys","reserved","deps","depName","validateOwnsKeys","cid","constraint","owns","BLOCKED_PROPS","validateModuleConfig","createModule","crossModuleDeps","createModuleFactory","createRequirementStatusPlugin","state","notify","listener","getOrCreateSet","map","type","set","getStatus","pendingSet","inflightSet","failedSet","lastError","getAllStatus","allTypes","result","subscribe","reset","req","_resolver","error","createStatusHook","statusPlugin","createSystemWithStatus","allPlugins","createSystem","realClock","cb","ms","handle","virtualClock","initialMs","nowMs","nextId","queue","targetMs","ready","next","defaultClock","initialTimerState","elapsedMs","remainingMs","totalMs","startTimer","pauseTimer","resumeTimer","pausedFor","resetTimer","completeTimer","registerRepeat","tickTimer","elapsed","timerOps","Backoff"],"mappings":"yNAoCO,IAAMA,CAAAA,CAAoB,IAsFjC,SAASC,EAAAA,CACPC,EACAC,CAAAA,CACM,CACN,GAAI,CACFC,mBAAAA,CAAkBF,CAAI,EACxB,CAAA,MAASG,EAAK,CACZ,IAAMC,EAAUD,CAAAA,YAAe,KAAA,CAAQA,CAAAA,CAAI,OAAA,CAAU,MAAA,CAAOA,CAAG,EAE/D,MAAM,IAAI,MACR,CAAA,6BAAA,EAAgCF,CAAK,gCAA2BG,CAAO,CAAA,CACzE,CACF,CAEA,GAAI,CAACC,oBAAYL,CAAI,CAAA,CAAG,CACtB,IAAMM,CAAAA,CACJN,IAAS,IAAA,EAAQ,OAAOA,CAAAA,EAAS,QAAA,CAC7B,CAAA,EAAG,OAAOA,CAAI,CAAA,QAAA,EAAM,IAAA,CAAK,UAAUA,CAAI,CAAC,GACxC,IAAA,CAAK,SAAA,CAAUA,CAAI,CAAA,CAAE,KAAA,CAAM,EAAG,EAAE,CA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3I,CAAAA,CAAK,EAAE,CACrC,CACF,CChDO,IAAMgK,EAAAA,CAAU,CAErB,IAAA,CAAM,MAAA,CAEN,MAAA,CAAQ,QAAA,CAER,YAAa,aACf","file":"index.cjs","sourcesContent":["/**\n * Predicate backtest — rule-change impact.\n *\n * Given a recorded sequence of fact-state frames and a proposed replacement\n * for a constraint's `when` predicate, re-score the frames against BOTH the\n * original and the proposed predicate and produce a backtest report: how\n * many frames each matched, plus the per-frame diff (frames that newly\n * match / no longer match). It answers \"how many recorded frames would the\n * proposed rule have matched differently\" against real recorded history.\n *\n * This is a *static* backtest, not a behavioral simulation — the engine is\n * not re-run. Recorded frames are re-scored against a new predicate; the\n * resulting requirements, resolvers, and downstream fact changes are NOT\n * modeled. Treat the numbers as a divergence scan, not a forecast.\n *\n * Pure module — imports only the predicate runtime. No engine, store, or\n * tracking dependency. Replay walks frames in order; for `$changed`-style\n * predicates each frame is evaluated against the previous frame's facts.\n */\n\nimport {\n evaluatePredicate,\n evaluatePredicateExplained,\n isPredicate,\n validatePredicate,\n walkPredicate,\n} from \"./predicate.js\";\nimport type { ClauseResult, FactPredicate } from \"./types/predicate.js\";\nimport { PREDICATE_COMBINATORS, PREDICATE_OPERATORS } from \"./types/predicate.js\";\n\n/**\n * Upper bound on the number of frames a single {@link replayUnder} call will\n * process. A history file is held entirely in memory; an unbounded array is a\n * denial-of-service surface. A history larger than this should be split or\n * down-sampled before replay.\n */\nexport const MAX_REPLAY_FRAMES = 1_000_000;\n\n/** One recorded fact-state frame. */\nexport interface ReplayFrame<F = Record<string, unknown>> {\n /** Stable identifier — a snapshot id, an index, a session key. */\n id: string | number;\n /** Optional wall-clock time (ms epoch). */\n timestamp?: number;\n /** The fact state at this frame. */\n facts: F;\n}\n\nexport interface ReplayUnderOptions<F = Record<string, unknown>> {\n /** Recorded frames, chronological order. */\n frames: readonly ReplayFrame<F>[];\n /** The constraint's current `when` predicate (the baseline). */\n original: FactPredicate<F>;\n /** The proposed replacement `when` predicate. */\n proposed: FactPredicate<F>;\n /** Max diff samples to attach per bucket (default 20). */\n maxSamples?: number;\n /**\n * A fact key identifying the entity a frame belongs to (e.g. `\"userId\"`,\n * `\"sessionId\"`). When set, the report also reports distinct-entity counts\n * — how many unique entities matched, not just how many frames. Without it\n * the unit is frames: one fact snapshot, not one user or session.\n */\n entityKey?: string;\n}\n\n/** A frame where the original and proposed predicate disagree. */\nexport interface ReplayDiffSample {\n frameId: string | number;\n timestamp?: number;\n /** The fact state at this frame. */\n facts: Record<string, unknown>;\n /** Per-clause breakdown under the original predicate. */\n originalExplain: ClauseResult[];\n /** Per-clause breakdown under the proposed predicate. */\n proposedExplain: ClauseResult[];\n}\n\n/**\n * The outcome of replaying a recorded history under two predicates — a\n * static backtest of a proposed rule change, not a behavioral simulation.\n */\nexport interface PredicateBacktestReport {\n /** Total frames evaluated. */\n framesEvaluated: number;\n /**\n * Frames where the original predicate matched (was true). `matchedEntities`\n * is the count of distinct `entityKey` values among matched frames — only\n * populated when {@link ReplayUnderOptions.entityKey} was supplied.\n */\n original: { matched: number; matchedEntities?: number };\n /** Frames where the proposed predicate matched. */\n proposed: { matched: number; matchedEntities?: number };\n /** proposed.matched - original.matched. */\n delta: number;\n /** Total count of frames that newly match (original false -> proposed true). */\n newMatchCount: number;\n /** Total count of frames that no longer match (original true -> proposed false). */\n lostMatchCount: number;\n /** Frames where original and proposed agree. */\n unchanged: number;\n /** Sampled new-match frames (capped at maxSamples), with clause explain. */\n newMatches: ReplayDiffSample[];\n /** Sampled lost-match frames (capped at maxSamples), with clause explain. */\n lostMatches: ReplayDiffSample[];\n}\n\n/**\n * Validate one predicate spec for {@link replayUnder}, re-throwing any failure\n * with a message that names which spec (`original` / `proposed`) was bad.\n *\n * Three checks run, all up front so a malformed spec never reaches the\n * per-frame loop (where {@link evaluatePredicate} would throw a raw error on,\n * say, a `$matches` operand that is not a RegExp):\n *\n * 1. {@link validatePredicate} — JSON-unrehydratable operands (a `$matches`\n * operand that is not a RegExp, a `bigint`, a `Set`/`Map`).\n * 2. {@link isPredicate} — the spec is structurally a FactPredicate. An\n * empty object `{}` is a valid (always-true) predicate and is allowed.\n * 3. Unknown `$`-operators — a single walk surfaces any `$frobnicate`-style\n * typo as one clear error instead of a per-call dev-warn.\n */\nfunction validateReplaySpec(\n spec: unknown,\n which: \"original\" | \"proposed\",\n): void {\n try {\n validatePredicate(spec);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n\n throw new Error(\n `[Directive] replayUnder: the ${which} predicate is invalid — ${message}`,\n );\n }\n\n if (!isPredicate(spec)) {\n const preview =\n spec === null || typeof spec !== \"object\"\n ? `${typeof spec} — ${JSON.stringify(spec)}`\n : JSON.stringify(spec).slice(0, 80);\n\n throw new Error(\n `[Directive] replayUnder: the ${which} predicate is not a valid FactPredicate (got ${preview})`,\n );\n }\n\n // Surface an unknown `$`-operator (`$frobnicate`) as one clear error.\n // `walkPredicate` reports a `$`-key at fact position via `strayOperatorKey`\n // and an operator clause via `operator`; check both against the known sets.\n let unknownOp: string | undefined;\n walkPredicate(spec, {\n operator(_factPath, op) {\n if (\n unknownOp === undefined &&\n op.startsWith(\"$\") &&\n !PREDICATE_OPERATORS.has(op)\n ) {\n unknownOp = op;\n }\n },\n strayOperatorKey(key) {\n if (\n unknownOp === undefined &&\n !PREDICATE_OPERATORS.has(key) &&\n !PREDICATE_COMBINATORS.has(key)\n ) {\n unknownOp = key;\n }\n },\n });\n\n if (unknownOp !== undefined) {\n throw new Error(\n `[Directive] replayUnder: the ${which} predicate uses an unknown operator \"${unknownOp}\" — known operators: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n}\n\n/**\n * Normalize a parsed-from-JSON history value into a `ReplayFrame[]`.\n *\n * Accepts the three documented history shapes:\n *\n * 1. A bare array of frames: `[{ id, timestamp?, facts }, ...]`\n * 2. An object wrapping them: `{ frames: [{ id, ..., facts }, ...] }`\n * 3. A bare array of fact objects: `[{ phase: \"red\", ... }, ...]`\n * — each element is wrapped as a frame.\n *\n * Frame ids are kept unambiguous: a frame that supplies its own `id` keeps\n * it; a frame missing an `id` (and every bare-fact frame) gets an\n * **index-derived** id prefixed with `#` (`\"#0\"`, `\"#1\"`, …) so a fallback\n * id can never collide with an explicit numeric or string id in a mixed\n * history. This is a pure helper — it **throws** a clear `Error` on bad\n * input and never calls `process.exit`, so library users can catch it.\n *\n * @example\n * ```ts\n * toReplayFrames([{ id: \"s1\", facts: { phase: \"red\" } }]);\n * // → [{ id: \"s1\", facts: { phase: \"red\" } }]\n * toReplayFrames([{ phase: \"red\" }, { phase: \"green\" }]);\n * // → [{ id: \"#0\", facts: { phase: \"red\" } }, { id: \"#1\", facts: { phase: \"green\" } }]\n * ```\n */\nexport function toReplayFrames(raw: unknown): ReplayFrame[] {\n // A history-manager export ({ version, snapshots, currentIndex }) is a\n // valid input shape — route it through framesFromHistory so the CLI and\n // the library accept the same files.\n if (\n raw &&\n typeof raw === \"object\" &&\n !Array.isArray(raw) &&\n Array.isArray((raw as { snapshots?: unknown }).snapshots)\n ) {\n return framesFromHistory(raw);\n }\n\n const list: unknown[] | null = Array.isArray(raw)\n ? raw\n : raw &&\n typeof raw === \"object\" &&\n Array.isArray((raw as { frames?: unknown }).frames)\n ? (raw as { frames: unknown[] }).frames\n : null;\n\n if (!list) {\n throw new Error(\n \"[Directive] toReplayFrames: history must be a JSON array of frames, an object with a `frames` array, or a history export with a `snapshots` array\",\n );\n }\n\n // Enforce the frame cap on `length` before `.map()` materializes a second\n // array — the cap must bound memory, not just the evaluation loop.\n if (list.length > MAX_REPLAY_FRAMES) {\n throw new Error(\n `[Directive] toReplayFrames: history has ${list.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${MAX_REPLAY_FRAMES}) — split or down-sample the history`,\n );\n }\n\n return list.map((entry, index) => {\n if (entry && typeof entry === \"object\" && \"facts\" in entry) {\n const frame = entry as {\n id?: string | number;\n timestamp?: number;\n facts: unknown;\n };\n // An explicit id is used verbatim; a missing id falls back to a\n // `#`-prefixed index so it cannot collide with an explicit id.\n const out: ReplayFrame = {\n id: frame.id ?? `#${index}`,\n facts: (frame.facts ?? {}) as Record<string, unknown>,\n };\n if (typeof frame.timestamp === \"number\") {\n out.timestamp = frame.timestamp;\n }\n\n return out;\n }\n\n // A bare fact object — wrap it, keyed by `#`-prefixed index.\n return { id: `#${index}`, facts: (entry ?? {}) as Record<string, unknown> };\n });\n}\n\n/**\n * Convert a history-manager export (the JSON produced by\n * `system.history.export()`) into a `ReplayFrame[]` ready for\n * {@link replayUnder}.\n *\n * The history manager records a ring buffer of `{ id, timestamp, facts,\n * trigger }` snapshots; `export()` wraps them as `{ version, snapshots,\n * currentIndex }`. Each snapshot's `facts` is the fact state at that point,\n * so the snapshot sequence is exactly a frame stream.\n *\n * Accepts either the parsed export object, the raw JSON string, or a bare\n * array of snapshots. Throws a clear `Error` on bad input.\n *\n * @example\n * ```ts\n * const frames = framesFromHistory(system.history.export());\n * const report = replayUnder({ frames, original, proposed });\n * ```\n */\nexport function framesFromHistory(historyExport: unknown): ReplayFrame[] {\n const parsed =\n typeof historyExport === \"string\"\n ? (JSON.parse(historyExport) as unknown)\n : historyExport;\n\n // A bare snapshot array is accepted directly.\n if (Array.isArray(parsed)) {\n return framesFromSnapshots(parsed);\n }\n\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(\n \"[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())\",\n );\n }\n\n const exportObj = parsed as { version?: unknown; snapshots?: unknown };\n\n // Mirror history.ts import(): only version 1 is understood. A bump in the\n // export format must fail loud here, not silently yield wrong frames.\n if (exportObj.version !== undefined && exportObj.version !== 1) {\n throw new Error(\n `[Directive] framesFromHistory: unsupported history export version ${JSON.stringify(exportObj.version)} — expected 1`,\n );\n }\n\n if (!Array.isArray(exportObj.snapshots)) {\n throw new Error(\n \"[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())\",\n );\n }\n\n return framesFromSnapshots(exportObj.snapshots);\n}\n\n/**\n * Convert an array of `{ id, timestamp?, facts }` snapshots — e.g. the\n * `snapshots` field of a history export, or an array assembled by pushing\n * `system.getSnapshot()` on each reconcile — into a `ReplayFrame[]`.\n *\n * Throws a clear `Error` if the argument is not an array. Each snapshot is\n * normalized through the same {@link toReplayFrames} id logic.\n *\n * @example\n * ```ts\n * const snapshots: typeof history[] = [];\n * system.observe(() => snapshots.push(system.getSnapshot()));\n * // ...later\n * const frames = framesFromSnapshots(snapshots);\n * ```\n */\nexport function framesFromSnapshots(snapshots: unknown): ReplayFrame[] {\n if (!Array.isArray(snapshots)) {\n throw new Error(\n \"[Directive] framesFromSnapshots: expected an array of fact-state snapshots\",\n );\n }\n\n if (snapshots.length > MAX_REPLAY_FRAMES) {\n throw new Error(\n `[Directive] framesFromSnapshots: history has ${snapshots.length} snapshots, exceeds the MAX_REPLAY_FRAMES limit (${MAX_REPLAY_FRAMES}) — split or down-sample the history`,\n );\n }\n\n // A snapshot is always a { facts, ... } object — reject a garbage array\n // before it is silently wrapped into empty-fact frames.\n for (let i = 0; i < snapshots.length; i++) {\n const s = snapshots[i];\n if (!s || typeof s !== \"object\" || !(\"facts\" in s)) {\n throw new Error(\n `[Directive] framesFromSnapshots: snapshot at index ${i} is not a { facts, ... } object`,\n );\n }\n }\n\n return toReplayFrames(snapshots);\n}\n\n/**\n * Replay a recorded fact-frame history through two predicates — the\n * constraint's current `when` and a proposed replacement — and report how\n * their match sets differ.\n *\n * This is a **predicate backtest**: the engine is not re-run. Each recorded\n * frame is statically re-scored against both specs; the previous frame's\n * facts are threaded as `prev` so a replayed effect-`on` predicate using\n * `$changed` still works (for a constraint `when` it is harmless). The\n * report counts matches under each spec and buckets the disagreements into\n * new matches (original false, proposed true) and lost matches (original\n * true, proposed false). Up to `maxSamples` diff frames per bucket carry a\n * per-clause `evaluatePredicateExplained` breakdown for inspection.\n *\n * Both specs are validated up front — a malformed spec throws a clear\n * `[Directive] replayUnder:` error identifying which spec failed, rather\n * than letting a raw `evaluatePredicate` error escape mid-loop.\n *\n * @example\n * ```ts\n * const report = replayUnder({\n * frames: [\n * { id: 0, facts: { phase: \"red\", elapsed: 10 } },\n * { id: 1, facts: { phase: \"red\", elapsed: 35 } },\n * ],\n * original: { phase: \"red\" },\n * proposed: { phase: \"red\", elapsed: { $gte: 30 } },\n * });\n * // report.original.matched === 2\n * // report.proposed.matched === 1\n * // report.delta === -1\n * // report.lostMatchCount === 1\n * ```\n */\nexport function replayUnder<F = Record<string, unknown>>(\n options: ReplayUnderOptions<F>,\n): PredicateBacktestReport {\n const { frames, original, proposed, entityKey } = options;\n const requested = options.maxSamples ?? 20;\n const maxSamples = requested > 0 ? requested : 0;\n\n if (frames.length > MAX_REPLAY_FRAMES) {\n throw new Error(\n `[Directive] replayUnder: history has ${frames.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${MAX_REPLAY_FRAMES}) — split or down-sample the history`,\n );\n }\n\n // Validate both specs before the frame loop — fail loud and clear here\n // rather than at frame 0 with a raw evaluatePredicate stack trace.\n validateReplaySpec(original, \"original\");\n validateReplaySpec(proposed, \"proposed\");\n\n let originalMatched = 0;\n let proposedMatched = 0;\n let newMatchCount = 0;\n let lostMatchCount = 0;\n let unchanged = 0;\n const newMatches: ReplayDiffSample[] = [];\n const lostMatches: ReplayDiffSample[] = [];\n\n // Distinct-entity tracking — only allocated when `entityKey` was supplied.\n const originalEntities = entityKey ? new Set<unknown>() : undefined;\n const proposedEntities = entityKey ? new Set<unknown>() : undefined;\n\n let prevFacts: Record<string, unknown> | undefined;\n\n for (const frame of frames) {\n const facts = frame.facts as Record<string, unknown>;\n const originalBit = evaluatePredicate(original, facts, prevFacts);\n const proposedBit = evaluatePredicate(proposed, facts, prevFacts);\n\n if (originalBit) {\n originalMatched++;\n originalEntities?.add(facts[entityKey as string]);\n }\n if (proposedBit) {\n proposedMatched++;\n proposedEntities?.add(facts[entityKey as string]);\n }\n\n if (originalBit === proposedBit) {\n unchanged++;\n } else if (!originalBit && proposedBit) {\n newMatchCount++;\n if (newMatches.length < maxSamples) {\n newMatches.push(buildSample(frame, original, proposed, prevFacts));\n }\n } else {\n lostMatchCount++;\n if (lostMatches.length < maxSamples) {\n lostMatches.push(buildSample(frame, original, proposed, prevFacts));\n }\n }\n\n prevFacts = facts;\n }\n\n const report: PredicateBacktestReport = {\n framesEvaluated: frames.length,\n original: { matched: originalMatched },\n proposed: { matched: proposedMatched },\n delta: proposedMatched - originalMatched,\n newMatchCount,\n lostMatchCount,\n unchanged,\n newMatches,\n lostMatches,\n };\n\n if (originalEntities && proposedEntities) {\n report.original.matchedEntities = originalEntities.size;\n report.proposed.matchedEntities = proposedEntities.size;\n }\n\n return report;\n}\n\n/**\n * Build a {@link ReplayDiffSample} for a frame the two predicates disagree\n * on — the per-clause explain is computed only here, never for non-diff\n * frames, so the common (mostly-agreeing) case stays cheap.\n */\nfunction buildSample<F>(\n frame: ReplayFrame<F>,\n original: unknown,\n proposed: unknown,\n prevFacts: Record<string, unknown> | undefined,\n): ReplayDiffSample {\n const facts = frame.facts as Record<string, unknown>;\n const sample: ReplayDiffSample = {\n frameId: frame.id,\n facts,\n originalExplain: evaluatePredicateExplained(original, facts, prevFacts),\n proposedExplain: evaluatePredicateExplained(proposed, facts, prevFacts),\n };\n\n if (frame.timestamp !== undefined) {\n sample.timestamp = frame.timestamp;\n }\n\n return sample;\n}\n","/**\n * Parameter sweep over a predicate template — the grid-search counterpart\n * to `replayUnder`.\n *\n * `replayUnder` diffs ONE proposed predicate against the original.\n * `sweepUnder` takes a **template** with one or more `{ $hole: \"name\" }`\n * markers and a set of candidate values, then replays the history once\n * per (cartesian-product) combination. The result is a response curve\n * over the parameter space plus the argmax under a user-supplied\n * objective — turning rule-tuning from guess-and-check into a one-call\n * optimization against recorded traffic.\n *\n * Pure module — imports only the predicate runtime and replay engine.\n * No engine / store / tracking dependency.\n */\n\nimport { MAX_PREDICATE_DEPTH } from \"./predicate.js\";\nimport { type PredicateBacktestReport, type ReplayFrame, replayUnder } from \"./replay-under.js\";\nimport type { FactPredicate } from \"./types/predicate.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** A placeholder inside a predicate template — substituted from `sweep` values. */\nexport interface SweepHole {\n readonly $hole: string;\n}\n\nexport interface SweepUnderOptions<F = Record<string, unknown>> {\n /** Recorded fact-state frames, in chronological order. */\n frames: readonly ReplayFrame<F>[];\n /** The constraint's current `when` predicate (baseline). */\n original: FactPredicate<F>;\n /**\n * Predicate template containing one or more `{ $hole: \"name\" }` markers.\n * Each marker is substituted by the corresponding value from `sweep` on\n * every point in the curve.\n *\n * @example\n * ```ts\n * { cartTotal: { $gte: { $hole: \"threshold\" } } }\n * ```\n */\n template: unknown;\n /**\n * Map of hole name → candidate values. Multiple holes produce the\n * cartesian product (grid search).\n *\n * @example\n * ```ts\n * { threshold: [25, 50, 100, 200] }\n * { riskScore: [0.5, 0.7, 0.9], minAge: [13, 18, 21] } // 3*3 = 9 points\n * ```\n */\n sweep: Readonly<Record<string, readonly unknown[]>>;\n /**\n * Score function for ranking. Higher is better. Default:\n * `(report) => report.proposed.matched` (maximize matched frames).\n */\n objective?: (report: PredicateBacktestReport) => number;\n /** Optional fact key to additionally report distinct-entity counts. */\n entityKey?: string;\n /**\n * Diff frames sampled per replay (default 0 — count-only for speed).\n * Set higher to inspect specific frames in the report.\n */\n maxSamples?: number;\n}\n\n/** One point on the sweep curve — one candidate value tuple. */\nexport interface SweepPoint {\n /** Hole name → value used at this point. */\n values: Readonly<Record<string, unknown>>;\n /** Full backtest report against this candidate. */\n report: PredicateBacktestReport;\n /** Computed objective score (higher is better). */\n score: number;\n}\n\nexport interface SweepReport {\n /** All points, in sweep order (cartesian-product traversal of sweep keys). */\n points: readonly SweepPoint[];\n /** Index of the highest-scoring point in `points`. */\n bestIndex: number;\n /** Convenience accessor: `points[bestIndex]`. */\n best: SweepPoint;\n /** The original predicate replayed against itself — score baseline for comparison. */\n baseline: SweepPoint;\n}\n\n/** Hard cap on points evaluated in a single sweep — protects against runaway grids. */\nexport const MAX_SWEEP_POINTS = 10_000;\n\n/**\n * Aggregate compute cap: `points × frames` per call. `MAX_SWEEP_POINTS`\n * (10k) and `MAX_REPLAY_FRAMES` (1M) bound each axis individually, but\n * their product would be 10B per-frame evaluations — minutes-to-hours of\n * compute. This caps the realistic upper bound at ~50M evaluations\n * (e.g. 50k frames × 1k points, or 5k frames × 10k points).\n */\nexport const MAX_SWEEP_EVALUATIONS = 50_000_000;\n\n// ============================================================================\n// Hole substitution\n// ============================================================================\n\nfunction isHole(v: unknown): v is SweepHole {\n return (\n v !== null &&\n typeof v === \"object\" &&\n !Array.isArray(v) &&\n Object.keys(v as object).length === 1 &&\n typeof (v as SweepHole).$hole === \"string\"\n );\n}\n\n/**\n * Walk `template`, replacing every `{ $hole: name }` marker with the value\n * looked up in `values`. Returns a new tree — does not mutate `template`.\n * Cycle-guarded; depth-capped at `MAX_PREDICATE_DEPTH`.\n *\n * Throws if a hole's name is not present in `values` — surfaces a typo'd\n * hole name up front rather than letting it land as `undefined` in the\n * evaluator.\n */\nfunction substitute(\n template: unknown,\n values: Record<string, unknown>,\n path: Set<object> = new Set(),\n depth = 0,\n): unknown {\n if (depth > MAX_PREDICATE_DEPTH) {\n throw new Error(\n `[Directive] sweepUnder: template exceeds MAX_PREDICATE_DEPTH (${MAX_PREDICATE_DEPTH}) — flatten the template or split the sweep`,\n );\n }\n\n if (isHole(template)) {\n const name = template.$hole;\n if (!(name in values)) {\n throw new Error(\n `[Directive] sweepUnder: template references hole \"${name}\" but sweep has no values for it`,\n );\n }\n\n // Don't recurse into the substituted value — sweep values are opaque\n // payloads, not templates. A value that itself looks like `{$hole:...}`\n // lands literally in the proposed predicate.\n return values[name];\n }\n\n if (template === null || typeof template !== \"object\") {\n return template;\n }\n\n // Cycle guard via DFS path Set — entries are removed on unwind so that\n // shared (non-cyclic) sub-trees still get substituted on every occurrence.\n if (path.has(template)) {\n throw new Error(\n \"[Directive] sweepUnder: template contains a cycle — predicate templates must be a tree\",\n );\n }\n path.add(template);\n\n try {\n if (Array.isArray(template)) {\n return template.map((entry) => substitute(entry, values, path, depth + 1));\n }\n\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(template)) {\n out[k] = substitute(v, values, path, depth + 1);\n }\n\n return out;\n } finally {\n path.delete(template);\n }\n}\n\n// ============================================================================\n// Cartesian product\n// ============================================================================\n\n/**\n * Iterate the cartesian product of the sweep map's value arrays, in\n * declaration order. Generator avoids materializing the whole grid for\n * large multi-hole sweeps.\n */\nfunction* cartesian(\n keys: readonly string[],\n sweep: Readonly<Record<string, readonly unknown[]>>,\n): Generator<Record<string, unknown>> {\n if (keys.length === 0) {\n yield {};\n\n return;\n }\n\n const head = keys[0] as string;\n const rest = keys.slice(1);\n const headValues = sweep[head] ?? [];\n for (const v of headValues) {\n for (const tail of cartesian(rest, sweep)) {\n yield { [head]: v, ...tail };\n }\n }\n}\n\nfunction gridSize(sweep: Readonly<Record<string, readonly unknown[]>>): number {\n let size = 1;\n for (const arr of Object.values(sweep)) {\n size *= arr.length;\n }\n\n return size;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Sweep a predicate template's hole(s) across candidate values and replay\n * the recorded history through each one. Returns the full response curve\n * plus the argmax under a user-supplied objective.\n *\n * The mechanism is a tight loop over `replayUnder`: walk the cartesian\n * product of sweep values, substitute each combination into the template,\n * and run a backtest. Same caveats as `replayUnder` apply (no cascade\n * modeling, survivorship bias) — see {@link replayUnder} docs.\n *\n * @example\n * ```ts\n * const report = sweepUnder({\n * frames: recordedSessions,\n * original: { cartTotal: { $gte: 100 } },\n * template: { cartTotal: { $gte: { $hole: \"threshold\" } } },\n * sweep: { threshold: [25, 50, 100, 200] },\n * });\n *\n * report.best.values; // { threshold: 25 } (assuming higher matched is better)\n * report.best.report.proposed.matched; // 9210\n * report.baseline.score; // 4217 — the original spec's matched count\n * report.points.length; // 4\n * ```\n *\n * Multi-hole sweeps grid-search:\n *\n * ```ts\n * sweepUnder({\n * frames,\n * original,\n * template: {\n * risk: { $gte: { $hole: \"minRisk\" } },\n * age: { $gte: { $hole: \"minAge\" } },\n * },\n * sweep: { minRisk: [0.5, 0.7, 0.9], minAge: [13, 18, 21] },\n * });\n * // → 9 points (3 × 3)\n * ```\n */\nexport function sweepUnder<F = Record<string, unknown>>(\n options: SweepUnderOptions<F>,\n): SweepReport {\n const {\n frames,\n original,\n template,\n sweep,\n objective = (r) => r.proposed.matched,\n entityKey,\n maxSamples = 0,\n } = options;\n\n const keys = Object.keys(sweep);\n if (keys.length === 0) {\n throw new Error(\n \"[Directive] sweepUnder: `sweep` must contain at least one hole name\",\n );\n }\n\n const total = gridSize(sweep);\n if (total > MAX_SWEEP_POINTS) {\n throw new Error(\n `[Directive] sweepUnder: grid has ${total} points, exceeds the MAX_SWEEP_POINTS limit (${MAX_SWEEP_POINTS}) — narrow the sweep ranges or split the run`,\n );\n }\n if (total === 0) {\n throw new Error(\n \"[Directive] sweepUnder: at least one hole has zero candidate values\",\n );\n }\n const evaluations = total * frames.length;\n if (evaluations > MAX_SWEEP_EVALUATIONS) {\n throw new Error(\n `[Directive] sweepUnder: ${total} points × ${frames.length} frames = ${evaluations} per-frame evaluations, exceeds the MAX_SWEEP_EVALUATIONS limit (${MAX_SWEEP_EVALUATIONS}) — narrow the sweep, down-sample the history, or split the run`,\n );\n }\n\n // Invoke the user's objective with a catch + finite-number guard.\n // A throw or non-finite return becomes -Infinity so the point sinks in\n // the ranking instead of corrupting it (and stays out of the argmax).\n let warnedObjective = false;\n const safeObjective = (report: PredicateBacktestReport): number => {\n let raw: unknown;\n try {\n raw = objective(report);\n } catch (err) {\n if (!warnedObjective) {\n warnedObjective = true;\n console.warn(\n `[Directive] sweepUnder: objective threw — point will not rank (${(err as Error).message})`,\n );\n }\n\n return Number.NEGATIVE_INFINITY;\n }\n if (typeof raw !== \"number\" || !Number.isFinite(raw)) {\n if (!warnedObjective) {\n warnedObjective = true;\n console.warn(\n `[Directive] sweepUnder: objective returned a non-finite number (${String(raw)}) — point will not rank`,\n );\n }\n\n return Number.NEGATIVE_INFINITY;\n }\n\n return raw;\n };\n\n // Baseline: replay original against itself so the caller has a\n // comparable score under the same objective. This is one extra\n // replayUnder() call regardless of grid size — cheap, useful.\n const baselineReport = replayUnder({\n frames,\n original,\n proposed: original,\n entityKey,\n maxSamples,\n });\n const baseline: SweepPoint = {\n values: {},\n report: baselineReport,\n score: safeObjective(baselineReport),\n };\n\n const points: SweepPoint[] = [];\n let bestIndex = 0;\n let bestScore = Number.NEGATIVE_INFINITY;\n\n for (const values of cartesian(keys, sweep)) {\n const proposed = substitute(template, values) as FactPredicate<F>;\n const report = replayUnder({\n frames,\n original,\n proposed,\n entityKey,\n maxSamples,\n });\n const score = safeObjective(report);\n if (score > bestScore) {\n bestScore = score;\n bestIndex = points.length;\n }\n points.push({ values, report, score });\n }\n\n // points is guaranteed non-empty here because total > 0 and the loop ran.\n const best = points[bestIndex] as SweepPoint;\n\n return {\n points,\n bestIndex,\n best,\n baseline,\n };\n}\n","/**\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 && typeof raw === \"object\" && !Array.isArray(raw) && \"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(\"[Directive] diffRules: constraint `id` must be a string\");\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\n ? `${pathPrefix}.${String(c.fact)}`\n : 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 * Compile a `FactPredicate` to a parameterized Postgres-style SQL WHERE\n * clause. The same predicate that gates a constraint on the client can\n * filter rows on the server — *one source of truth, two execution sites*.\n *\n * Pure transformation. No engine, no driver, no string concatenation of\n * user values (all operands flow through the parameter array → safe\n * against SQL injection by construction).\n */\n\nimport { MAX_PREDICATE_DEPTH } from \"./predicate.js\";\nimport {\n PREDICATE_OPERATORS,\n type FactPredicate,\n} from \"./types/predicate.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface PredicateToSqlOptions {\n /** Table to query. Validated against the same identifier rule as columns. */\n table: string;\n /**\n * Allowlist of fact / column keys the predicate may reference. STRONGLY\n * RECOMMENDED for any predicate that crosses a trust boundary (AI\n * generation, user input, JSON-over-the-wire). Without an allowlist, a\n * predicate may reference any column the table has.\n */\n allowedKeys?: readonly string[];\n /**\n * Customize the `SELECT` projection. Default `\"*\"`. Accepts:\n * - `\"*\"`\n * - a column identifier (`\"id\"` or `\"users.id\"`)\n * - an array of column identifiers (`[\"id\", \"name\"]`) — joined with `,`\n * Free-form strings (e.g. `\"COUNT(*)\"`) are rejected — build the wrapper\n * SQL manually with {@link predicateToWhere} for those cases.\n */\n select?: string | readonly string[];\n /**\n * Parameter placeholder generator. Default is Postgres-style `$1`, `$2`.\n * Pass `() => \"?\"` for MySQL/SQLite, or supply your own scheme.\n */\n placeholder?: (oneBasedIndex: number) => string;\n}\n\nexport interface PredicateToSqlResult {\n /** Full `SELECT … FROM table WHERE …` statement. */\n sql: string;\n /** Just the `WHERE` clause body (without the literal `WHERE`). */\n where: string;\n /** Parameters, in `$1`-then-`$2`-then-… order. */\n params: unknown[];\n}\n\n// ============================================================================\n// Identifier safety\n// ============================================================================\n\n/**\n * Strict identifier check: alpha, digits, underscore, optional dot for\n * qualified names (`table.column`). No whitespace, no quotes, no\n * semicolons — anything not matching is rejected with a clear error.\n *\n * Identifiers are interpolated *literally* into the SQL string (the only\n * safe alternative is double-quoting, which changes case sensitivity).\n * This regex is the only thing standing between a column-name typo and a\n * SQL injection — keep it strict.\n */\nconst IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*)?$/;\n\nfunction assertIdentifier(name: string, kind: \"table\" | \"column\"): void {\n if (typeof name !== \"string\" || !IDENT_RE.test(name)) {\n throw new Error(\n `[Directive] predicateToSQL: invalid ${kind} identifier \"${name}\" — must match /^[A-Za-z_][A-Za-z0-9_]*(\\\\.[A-Za-z_][A-Za-z0-9_]*)?$/`,\n );\n }\n}\n\nfunction assertAllowed(\n name: string,\n allowed: readonly string[] | undefined,\n): void {\n if (allowed && !allowed.includes(name)) {\n throw new Error(\n `[Directive] predicateToSQL: column \"${name}\" is not in the allowedKeys list — add it to options.allowedKeys or remove it from the predicate`,\n );\n }\n}\n\nfunction validateSelect(select: string | readonly string[]): string {\n if (Array.isArray(select)) {\n if (select.length === 0) {\n throw new Error(`[Directive] predicateToSQL: select must not be empty`);\n }\n for (const col of select) {\n assertIdentifier(col, \"column\");\n }\n\n return select.join(\", \");\n }\n const s = select as string;\n if (s === \"*\") return \"*\";\n assertIdentifier(s, \"column\");\n\n return s;\n}\n\n// ============================================================================\n// Operator translation\n// ============================================================================\n\ninterface BuildContext {\n params: unknown[];\n placeholder: (i: number) => string;\n allowed?: readonly string[];\n}\n\nfunction nextParam(ctx: BuildContext, value: unknown): string {\n ctx.params.push(value);\n\n return ctx.placeholder(ctx.params.length);\n}\n\n/**\n * Render one operator on one column. `column` is already\n * identifier-validated; the operand goes through `nextParam` so it lands\n * in `params`, never in the SQL string.\n */\nfunction renderOp(\n column: string,\n op: string,\n operand: unknown,\n ctx: BuildContext,\n): string {\n switch (op) {\n case \"$eq\":\n return `${column} = ${nextParam(ctx, operand)}`;\n case \"$ne\":\n return `${column} <> ${nextParam(ctx, operand)}`;\n case \"$gt\":\n return `${column} > ${nextParam(ctx, operand)}`;\n case \"$gte\":\n return `${column} >= ${nextParam(ctx, operand)}`;\n case \"$lt\":\n return `${column} < ${nextParam(ctx, operand)}`;\n case \"$lte\":\n return `${column} <= ${nextParam(ctx, operand)}`;\n case \"$in\":\n if (!Array.isArray(operand)) {\n throw new Error(`[Directive] predicateToSQL: $in operand must be an array`);\n }\n return `${column} = ANY(${nextParam(ctx, operand)})`;\n case \"$nin\":\n if (!Array.isArray(operand)) {\n throw new Error(`[Directive] predicateToSQL: $nin operand must be an array`);\n }\n return `NOT (${column} = ANY(${nextParam(ctx, operand)}))`;\n case \"$exists\":\n return operand === true ? `${column} IS NOT NULL` : `${column} IS NULL`;\n case \"$between\": {\n if (!Array.isArray(operand) || operand.length !== 2) {\n throw new Error(\n `[Directive] predicateToSQL: $between operand must be a [low, high] tuple`,\n );\n }\n return `${column} BETWEEN ${nextParam(ctx, operand[0])} AND ${nextParam(ctx, operand[1])}`;\n }\n case \"$startsWith\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToSQL: $startsWith operand must be a string`,\n );\n }\n // ESCAPE '\\' makes the escape character deterministic regardless of\n // the server's standard_conforming_strings setting or MySQL's\n // NO_BACKSLASH_ESCAPES mode.\n return `${column} LIKE ${nextParam(ctx, escapeLike(operand))} || '%' ESCAPE '\\\\'`;\n case \"$endsWith\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToSQL: $endsWith operand must be a string`,\n );\n }\n return `${column} LIKE '%' || ${nextParam(ctx, escapeLike(operand))} ESCAPE '\\\\'`;\n case \"$contains\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToSQL: $contains only supports string operands — array containment requires a JOIN, not a predicate`,\n );\n }\n return `${column} LIKE '%' || ${nextParam(ctx, escapeLike(operand))} || '%' ESCAPE '\\\\'`;\n case \"$matches\": {\n if (!(operand instanceof RegExp)) {\n throw new Error(\n `[Directive] predicateToSQL: $matches operand must be a RegExp`,\n );\n }\n // Postgres uses ~ (case-sensitive) and ~* (case-insensitive). The\n // RegExp's `i` flag picks the operator; other flags are silently\n // dropped because their semantics differ between JS and Postgres.\n const operator = operand.flags.includes(\"i\") ? \"~*\" : \"~\";\n\n return `${column} ${operator} ${nextParam(ctx, operand.source)}`;\n }\n case \"$changed\":\n throw new Error(\n `[Directive] predicateToSQL: $changed is an effects-only operator — no server-side translation (a database row has no \"prev\" snapshot)`,\n );\n default:\n throw new Error(\n `[Directive] predicateToSQL: unknown operator \"${op}\" — known: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n}\n\n/**\n * Escape `%`, `_`, and `\\` in a LIKE operand. Paired with an explicit\n * `ESCAPE '\\'` clause for cross-database determinism.\n */\nfunction escapeLike(s: string): string {\n return s.replace(/[\\\\%_]/g, \"\\\\$&\");\n}\n\n// ============================================================================\n// Recursive walk\n// ============================================================================\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\nfunction isOperatorObject(v: unknown): v is Record<string, unknown> {\n if (!isPlainObject(v)) return false;\n const keys = Object.keys(v);\n if (keys.length === 0) return false;\n for (const k of keys) {\n if (!k.startsWith(\"$\")) return false;\n }\n\n return true;\n}\n\nfunction assertNoSiblingKeys(spec: Record<string, unknown>, combinator: string): void {\n const sibs = Object.keys(spec).filter((k) => k !== combinator);\n if (sibs.length > 0) {\n throw new Error(\n `[Directive] predicateToSQL: ${combinator} cannot coexist with sibling keys (${sibs.join(\", \")}) — wrap them in $all together, or move them inside the ${combinator} children`,\n );\n }\n}\n\nfunction buildWhere(spec: unknown, ctx: BuildContext, depth: number): string {\n if (depth > MAX_PREDICATE_DEPTH) {\n throw new Error(\n `[Directive] predicateToSQL: predicate depth limit (${MAX_PREDICATE_DEPTH}) exceeded — flatten the predicate or check for a cyclic spec object`,\n );\n }\n if (spec === null || typeof spec !== \"object\") {\n throw new Error(\n `[Directive] predicateToSQL: predicate must be an object or array, got ${typeof spec}`,\n );\n }\n\n // Array-form predicate ([{fact, op, value}, ...]) — implicit AND.\n if (Array.isArray(spec)) {\n if (spec.length === 0) return \"TRUE\";\n const parts = spec.map((clause) => {\n if (\n !clause ||\n typeof clause !== \"object\" ||\n !(\"fact\" in clause) ||\n !(\"op\" in clause)\n ) {\n throw new Error(\n `[Directive] predicateToSQL: array-form clause must be { fact, op, value }`,\n );\n }\n const c = clause as { fact: string; op: string; value: unknown };\n assertIdentifier(c.fact, \"column\");\n assertAllowed(c.fact, ctx.allowed);\n\n return renderOp(c.fact, c.op, c.value, ctx);\n });\n\n return parts.length === 1 ? parts[0]! : `(${parts.join(\" AND \")})`;\n }\n\n // Combinators — must be the *only* key on the object.\n if (\"$all\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$all\");\n const arr = (spec as { $all: unknown[] }).$all;\n if (!Array.isArray(arr)) {\n throw new Error(`[Directive] predicateToSQL: $all must be an array`);\n }\n if (arr.length === 0) return \"TRUE\";\n const parts = arr.map((p) => buildWhere(p, ctx, depth + 1));\n\n return parts.length === 1 ? parts[0]! : `(${parts.join(\" AND \")})`;\n }\n if (\"$any\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$any\");\n const arr = (spec as { $any: unknown[] }).$any;\n if (!Array.isArray(arr)) {\n throw new Error(`[Directive] predicateToSQL: $any must be an array`);\n }\n if (arr.length === 0) return \"FALSE\";\n const parts = arr.map((p) => buildWhere(p, ctx, depth + 1));\n\n return parts.length === 1 ? parts[0]! : `(${parts.join(\" OR \")})`;\n }\n if (\"$not\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$not\");\n const inner = (spec as { $not: unknown }).$not;\n\n return `NOT (${buildWhere(inner, ctx, depth + 1)})`;\n }\n\n // Object form — every key is a column, every value either a literal\n // (equality) or an operator object.\n const parts: string[] = [];\n for (const [key, value] of Object.entries(spec as Record<string, unknown>)) {\n assertIdentifier(key, \"column\");\n assertAllowed(key, ctx.allowed);\n\n if (isOperatorObject(value)) {\n for (const [op, operand] of Object.entries(value)) {\n if (!PREDICATE_OPERATORS.has(op)) {\n throw new Error(\n `[Directive] predicateToSQL: unknown operator \"${op}\" on column \"${key}\" — known: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n parts.push(renderOp(key, op, operand, ctx));\n }\n } else if (isPlainObject(value)) {\n throw new Error(\n `[Directive] predicateToSQL: nested predicate at \"${key}\" — cross-module / partial-match predicates have no SQL equivalent (single-table queries only in v1; pass a flat predicate or build JOIN by hand with predicateToWhere)`,\n );\n } else {\n parts.push(renderOp(key, \"$eq\", value, ctx));\n }\n }\n\n if (parts.length === 0) return \"TRUE\";\n if (parts.length === 1) return parts[0]!;\n\n return `(${parts.join(\" AND \")})`;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\nconst DEFAULT_PLACEHOLDER = (i: number) => `$${i}`;\n\n/**\n * Compile a {@link FactPredicate} to a parameterized SQL statement.\n *\n * Operand values **never** appear in the SQL string — they flow through\n * the `params` array. Table and column identifiers are regex-validated.\n *\n * @example\n * ```ts\n * const where = { age: { $gte: 18 }, status: { $in: [\"active\", \"pending\"] } };\n *\n * predicateToSQL(where, { table: \"users\" });\n * // → { sql: \"SELECT * FROM users WHERE (age >= $1 AND status = ANY($2))\",\n * // where: \"(age >= $1 AND status = ANY($2))\",\n * // params: [18, [\"active\", \"pending\"]] }\n *\n * // MySQL/SQLite placeholder:\n * predicateToSQL(where, { table: \"users\", placeholder: () => \"?\" });\n *\n * // Recommended for AI/user-supplied predicates:\n * predicateToSQL(where, { table: \"users\", allowedKeys: [\"age\", \"status\"] });\n * ```\n */\nexport function predicateToSQL<F = Record<string, unknown>>(\n predicate: FactPredicate<F>,\n options: PredicateToSqlOptions,\n): PredicateToSqlResult {\n const { table, allowedKeys } = options;\n const placeholder = options.placeholder ?? DEFAULT_PLACEHOLDER;\n const select = options.select ?? \"*\";\n\n assertIdentifier(table, \"table\");\n const projection = validateSelect(select);\n\n const ctx: BuildContext = { params: [], placeholder, allowed: allowedKeys };\n const where = buildWhere(predicate, ctx, 0);\n const sql = `SELECT ${projection} FROM ${table} WHERE ${where}`;\n\n return { sql, where, params: ctx.params };\n}\n\n/**\n * Lower-level variant — returns just the `WHERE` clause body and the\n * `params` array, no `SELECT ... FROM` wrapper. Use this when you need\n * to embed the WHERE in a larger query (JOIN, UPDATE, DELETE, COUNT).\n *\n * @example\n * ```ts\n * const { where, params } = predicateToWhere({ age: { $gte: 18 } });\n * await db.query(`UPDATE users SET tier = 'adult' WHERE ${where}`, params);\n * ```\n */\nexport function predicateToWhere<F = Record<string, unknown>>(\n predicate: FactPredicate<F>,\n options: Omit<PredicateToSqlOptions, \"table\" | \"select\"> = {},\n): { where: string; params: unknown[] } {\n const placeholder = options.placeholder ?? DEFAULT_PLACEHOLDER;\n const ctx: BuildContext = {\n params: [],\n placeholder,\n allowed: options.allowedKeys,\n };\n\n return { where: buildWhere(predicate, ctx, 0), params: ctx.params };\n}\n","/**\n * Compile a `FactPredicate` to a MongoDB query document. Most of\n * Directive's predicate operator set is already Mongo-compatible by\n * design — this translator handles the few ops that need rewriting\n * (`$startsWith`/`$endsWith`/`$contains` → `$regex`, `$between` →\n * `$gte`+`$lte`, `$matches` → `$regex`/`$options`).\n *\n * Combinators map cleanly: `$all` → `$and`, `$any` → `$or`, `$not` → `$nor`.\n *\n * Pure transformation. No driver dependency.\n */\n\nimport { MAX_PREDICATE_DEPTH } from \"./predicate.js\";\nimport {\n PREDICATE_OPERATORS,\n type FactPredicate,\n} from \"./types/predicate.js\";\n\nexport interface PredicateToMongoOptions {\n /**\n * Allowlist of fact / field keys the predicate may reference. STRONGLY\n * RECOMMENDED for any predicate that crosses a trust boundary.\n */\n allowedKeys?: readonly string[];\n /**\n * Allow `.` in field names (for sub-document traversal: `\"user.role\"`).\n * Default is `false` — `.` is rejected so the predicate cannot\n * accidentally read sub-document fields the developer did not anticipate.\n */\n allowDottedPaths?: boolean;\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\nfunction isOperatorObject(v: unknown): v is Record<string, unknown> {\n if (!isPlainObject(v)) return false;\n const keys = Object.keys(v);\n if (keys.length === 0) return false;\n for (const k of keys) {\n if (!k.startsWith(\"$\")) return false;\n }\n\n return true;\n}\n\nconst FIELD_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst FIELD_DOTTED_RE = /^[A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*)*$/;\n\n/**\n * Reject any field that starts with `$` — that's how Mongo's `$where`\n * JavaScript-evaluation injection lands a predicate-as-RCE. Also reject\n * non-identifier characters (`.`, ` `, etc.) unless dotted paths are\n * explicitly enabled.\n */\nfunction assertFieldName(name: string, opts: PredicateToMongoOptions): void {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(\n `[Directive] predicateToMongo: field name must be a non-empty string, got ${typeof name}`,\n );\n }\n if (name.startsWith(\"$\")) {\n throw new Error(\n `[Directive] predicateToMongo: field name \"${name}\" starts with \"$\" — reserved for Mongo operators (a top-level $where would be an injection vector)`,\n );\n }\n const re = opts.allowDottedPaths ? FIELD_DOTTED_RE : FIELD_RE;\n if (!re.test(name)) {\n throw new Error(\n `[Directive] predicateToMongo: invalid field name \"${name}\"${opts.allowDottedPaths ? \"\" : ' — pass options.allowDottedPaths=true to permit sub-document paths like \"user.role\"'}`,\n );\n }\n}\n\nfunction assertAllowed(\n field: string,\n allowed: readonly string[] | undefined,\n): void {\n if (allowed && !allowed.includes(field)) {\n throw new Error(\n `[Directive] predicateToMongo: field \"${field}\" is not in the allowedKeys list — add it to options.allowedKeys or remove it from the predicate`,\n );\n }\n}\n\nfunction assertNoSiblingKeys(spec: Record<string, unknown>, combinator: string): void {\n const sibs = Object.keys(spec).filter((k) => k !== combinator);\n if (sibs.length > 0) {\n throw new Error(\n `[Directive] predicateToMongo: ${combinator} cannot coexist with sibling keys (${sibs.join(\", \")}) — wrap them in $all together, or move them inside the ${combinator} children`,\n );\n }\n}\n\n/**\n * Translate a single operator/operand pair into the Mongo equivalent.\n * Returns the value side of `{ field: <here> }`.\n */\nfunction translateOp(op: string, operand: unknown): Record<string, unknown> {\n switch (op) {\n case \"$eq\":\n case \"$ne\":\n case \"$gt\":\n case \"$gte\":\n case \"$lt\":\n case \"$lte\":\n case \"$in\":\n case \"$nin\":\n case \"$exists\":\n return { [op]: operand };\n case \"$between\": {\n if (!Array.isArray(operand) || operand.length !== 2) {\n throw new Error(\n `[Directive] predicateToMongo: $between operand must be a [low, high] tuple`,\n );\n }\n return { $gte: operand[0], $lte: operand[1] };\n }\n case \"$startsWith\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToMongo: $startsWith operand must be a string`,\n );\n }\n return { $regex: `^${escapeRegex(operand)}` };\n case \"$endsWith\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToMongo: $endsWith operand must be a string`,\n );\n }\n return { $regex: `${escapeRegex(operand)}$` };\n case \"$contains\":\n if (typeof operand === \"string\") {\n return { $regex: escapeRegex(operand) };\n }\n throw new Error(\n `[Directive] predicateToMongo: $contains in Mongo expects a string operand — for array element membership use $elemMatch or $in directly`,\n );\n case \"$matches\": {\n if (operand instanceof RegExp) {\n return operand.flags\n ? { $regex: operand.source, $options: operand.flags }\n : { $regex: operand.source };\n }\n if (typeof operand === \"string\") {\n return { $regex: operand };\n }\n throw new Error(\n `[Directive] predicateToMongo: $matches operand must be a RegExp or string`,\n );\n }\n case \"$changed\":\n throw new Error(\n `[Directive] predicateToMongo: $changed is an effects-only operator — no MongoDB query equivalent`,\n );\n default:\n throw new Error(\n `[Directive] predicateToMongo: unknown operator \"${op}\" — known: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n}\n\nfunction buildQuery(\n spec: unknown,\n opts: PredicateToMongoOptions,\n depth: number,\n): Record<string, unknown> {\n if (depth > MAX_PREDICATE_DEPTH) {\n throw new Error(\n `[Directive] predicateToMongo: predicate depth limit (${MAX_PREDICATE_DEPTH}) exceeded — flatten the predicate or check for a cyclic spec object`,\n );\n }\n if (spec === null || typeof spec !== \"object\") {\n throw new Error(\n `[Directive] predicateToMongo: predicate must be an object or array, got ${typeof spec}`,\n );\n }\n\n // Array form → implicit AND.\n if (Array.isArray(spec)) {\n if (spec.length === 0) return {};\n const obj: Record<string, unknown> = {};\n const conflicts: Array<Record<string, unknown>> = [];\n for (const clause of spec) {\n if (\n !clause ||\n typeof clause !== \"object\" ||\n !(\"fact\" in clause) ||\n !(\"op\" in clause)\n ) {\n throw new Error(\n `[Directive] predicateToMongo: array-form clause must be { fact, op, value }`,\n );\n }\n const c = clause as { fact: string; op: string; value: unknown };\n assertFieldName(c.fact, opts);\n assertAllowed(c.fact, opts.allowedKeys);\n const translated = translateOp(c.op, c.value);\n\n if (c.fact in obj && isPlainObject(obj[c.fact])) {\n const existing = obj[c.fact] as Record<string, unknown>;\n const overlap = Object.keys(translated).some((k) => k in existing);\n if (overlap) {\n conflicts.push({ [c.fact]: translated });\n } else {\n obj[c.fact] = { ...existing, ...translated };\n }\n } else if (c.fact in obj) {\n conflicts.push({ [c.fact]: translated });\n } else {\n obj[c.fact] = translated;\n }\n }\n if (conflicts.length > 0) {\n const andClauses: Array<Record<string, unknown>> = [];\n for (const [k, v] of Object.entries(obj)) {\n andClauses.push({ [k]: v });\n }\n andClauses.push(...conflicts);\n\n return { $and: andClauses };\n }\n\n return obj;\n }\n\n // Combinators\n if (\"$all\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$all\");\n const arr = (spec as { $all: unknown[] }).$all;\n if (!Array.isArray(arr)) {\n throw new Error(`[Directive] predicateToMongo: $all must be an array`);\n }\n if (arr.length === 0) return {};\n if (arr.length === 1) return buildQuery(arr[0], opts, depth + 1);\n\n return { $and: arr.map((p) => buildQuery(p, opts, depth + 1)) };\n }\n if (\"$any\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$any\");\n const arr = (spec as { $any: unknown[] }).$any;\n if (!Array.isArray(arr)) {\n throw new Error(`[Directive] predicateToMongo: $any must be an array`);\n }\n // Tautological-false — stable across Mongo versions, no _id assumption.\n if (arr.length === 0) return { $expr: { $eq: [1, 0] } };\n if (arr.length === 1) return buildQuery(arr[0], opts, depth + 1);\n\n return { $or: arr.map((p) => buildQuery(p, opts, depth + 1)) };\n }\n if (\"$not\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$not\");\n const inner = (spec as { $not: unknown }).$not;\n // Mongo's top-level $not is restricted to per-field; $nor: [...]\n // is the portable equivalent.\n return { $nor: [buildQuery(inner, opts, depth + 1)] };\n }\n\n // Object form — every key is a field name (validated to NOT start with $).\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(spec as Record<string, unknown>)) {\n assertFieldName(key, opts);\n assertAllowed(key, opts.allowedKeys);\n\n if (isOperatorObject(value)) {\n const merged: Record<string, unknown> = {};\n for (const [op, operand] of Object.entries(value)) {\n if (!PREDICATE_OPERATORS.has(op)) {\n throw new Error(\n `[Directive] predicateToMongo: unknown operator \"${op}\" on field \"${key}\" — known: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n Object.assign(merged, translateOp(op, operand));\n }\n out[key] = merged;\n } else if (isPlainObject(value)) {\n out[key] = value;\n } else {\n out[key] = value;\n }\n }\n\n return out;\n}\n\n/**\n * Compile a {@link FactPredicate} to a MongoDB query document.\n *\n * Field names are validated to NOT start with `$` (which would land\n * `$where` and other server-side JS evaluation operators directly in the\n * query — an injection vector for AI/user-generated predicates).\n *\n * @example\n * ```ts\n * predicateToMongo({ age: { $gte: 18 }, status: { $in: [\"active\", \"pending\"] } })\n * // → { age: { $gte: 18 }, status: { $in: [\"active\", \"pending\"] } }\n *\n * predicateToMongo({ name: { $startsWith: \"Al\" } })\n * // → { name: { $regex: \"^Al\" } }\n *\n * predicateToMongo({ $any: [{ tier: \"gold\" }, { score: { $gte: 100 } }] })\n * // → { $or: [{ tier: \"gold\" }, { score: { $gte: 100 } }] }\n * ```\n */\nexport function predicateToMongo<F = Record<string, unknown>>(\n predicate: FactPredicate<F>,\n options: PredicateToMongoOptions = {},\n): Record<string, unknown> {\n return buildQuery(predicate, options, 0);\n}\n","/**\n * Compile a `FactPredicate` to a PostgREST querystring.\n *\n * PostgREST's filter grammar is column-scoped: `?age=gte.18&status=in.(active,pending)`.\n * Logical groups use `and=(...)` / `or=(...)` / `not.and=(...)`.\n *\n * Reference: https://postgrest.org/en/stable/api.html#operators\n */\n\nimport { MAX_PREDICATE_DEPTH } from \"./predicate.js\";\nimport {\n PREDICATE_OPERATORS,\n type FactPredicate,\n} from \"./types/predicate.js\";\n\nexport interface PredicateToPostgrestOptions {\n /** Allowlist of column keys the predicate may reference. */\n allowedKeys?: readonly string[];\n /**\n * Encoding mode for the returned string.\n * - `\"querystring\"` (default): a full querystring without a leading `?`,\n * with each clause value URL-encoded — drops straight into `fetch`.\n * - `\"raw\"`: the same content, leaving `(`, `)`, `,` unencoded for\n * readability. Use this only when you'll encode the result yourself.\n */\n mode?: \"querystring\" | \"raw\";\n}\n\nconst IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nfunction assertColumn(name: string, allowed?: readonly string[]): void {\n if (typeof name !== \"string\" || !IDENT_RE.test(name)) {\n throw new Error(\n `[Directive] predicateToPostgrest: invalid column identifier \"${name}\"`,\n );\n }\n if (allowed && !allowed.includes(name)) {\n throw new Error(\n `[Directive] predicateToPostgrest: column \"${name}\" is not in the allowedKeys list — add it to options.allowedKeys or remove it from the predicate`,\n );\n }\n}\n\nfunction assertNoSiblingKeys(spec: Record<string, unknown>, combinator: string): void {\n const sibs = Object.keys(spec).filter((k) => k !== combinator);\n if (sibs.length > 0) {\n throw new Error(\n `[Directive] predicateToPostgrest: ${combinator} cannot coexist with sibling keys (${sibs.join(\", \")}) — wrap them in $all together, or move them inside the ${combinator} children`,\n );\n }\n}\n\n/** Encode a single PostgREST value. Strings with reserved chars get quoted. */\nfunction encodeValue(v: unknown): string {\n if (v === null || v === undefined) return \"null\";\n if (typeof v === \"boolean\") return v ? \"true\" : \"false\";\n if (typeof v === \"number\" || typeof v === \"bigint\") return String(v);\n if (v instanceof Date) return v.toISOString();\n if (typeof v === \"string\") {\n // PostgREST treats `,` `.` `(` `)` and `:` as syntax; quote any\n // string containing them. Inside quotes, `\"` → `\\\"` and `\\` → `\\\\`.\n if (/[,.():\"\\\\\\s]/.test(v)) {\n return `\"${v.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n }\n\n return v;\n }\n throw new Error(\n `[Directive] predicateToPostgrest: cannot encode value of type ${typeof v}`,\n );\n}\n\nfunction encodeList(arr: readonly unknown[]): string {\n return `(${arr.map(encodeValue).join(\",\")})`;\n}\n\n/** Escape `\\`, `%`, `_`, `*` so they match literally instead of as wildcards. */\nfunction escapeLikeOperand(s: string): string {\n return s.replace(/[\\\\%_*]/g, \"\\\\$&\");\n}\n\n/**\n * Render the value side of one operator. Returns a string like\n * `gte.18` or `in.(a,b)` — without the column name.\n */\nfunction renderOp(op: string, operand: unknown): string {\n switch (op) {\n case \"$eq\":\n return `eq.${encodeValue(operand)}`;\n case \"$ne\":\n return `neq.${encodeValue(operand)}`;\n case \"$gt\":\n return `gt.${encodeValue(operand)}`;\n case \"$gte\":\n return `gte.${encodeValue(operand)}`;\n case \"$lt\":\n return `lt.${encodeValue(operand)}`;\n case \"$lte\":\n return `lte.${encodeValue(operand)}`;\n case \"$in\":\n if (!Array.isArray(operand)) {\n throw new Error(`[Directive] predicateToPostgrest: $in operand must be an array`);\n }\n return `in.${encodeList(operand)}`;\n case \"$nin\":\n if (!Array.isArray(operand)) {\n throw new Error(`[Directive] predicateToPostgrest: $nin operand must be an array`);\n }\n return `not.in.${encodeList(operand)}`;\n case \"$exists\":\n return operand === true ? \"not.is.null\" : \"is.null\";\n case \"$startsWith\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToPostgrest: $startsWith operand must be a string`,\n );\n }\n return `like.${encodeValue(escapeLikeOperand(operand) + \"*\")}`;\n case \"$endsWith\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToPostgrest: $endsWith operand must be a string`,\n );\n }\n return `like.${encodeValue(\"*\" + escapeLikeOperand(operand))}`;\n case \"$contains\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToPostgrest: $contains expects a string operand (array containment is the cs operator with a different shape — out of scope for v1)`,\n );\n }\n return `like.${encodeValue(\"*\" + escapeLikeOperand(operand) + \"*\")}`;\n case \"$matches\":\n if (operand instanceof RegExp) {\n const o = operand.flags.includes(\"i\") ? \"imatch\" : \"match\";\n\n return `${o}.${encodeValue(operand.source)}`;\n }\n if (typeof operand === \"string\") {\n return `match.${encodeValue(operand)}`;\n }\n throw new Error(\n `[Directive] predicateToPostgrest: $matches operand must be a RegExp or string`,\n );\n // $between is handled at the build() level by decomposing into $gte + $lte.\n case \"$changed\":\n throw new Error(\n `[Directive] predicateToPostgrest: $changed is an effects-only operator — no server query equivalent`,\n );\n default:\n throw new Error(\n `[Directive] predicateToPostgrest: unknown operator \"${op}\" — known: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\nfunction isOperatorObject(v: unknown): v is Record<string, unknown> {\n if (!isPlainObject(v)) return false;\n const keys = Object.keys(v);\n if (keys.length === 0) return false;\n for (const k of keys) {\n if (!k.startsWith(\"$\")) return false;\n }\n\n return true;\n}\n\nfunction colClause(column: string, opAndValue: string): string {\n return `${column}=${opAndValue}`;\n}\n\nfunction groupClause(\n logical: \"and\" | \"or\" | \"not.and\" | \"not.or\",\n parts: string[],\n): string {\n return `${logical}=(${parts.join(\",\")})`;\n}\n\n/**\n * Render one operator inside one column. For `$between`, decomposes into\n * two clauses ($gte + $lte) so the predicate's portability promise holds.\n */\nfunction renderColumnOps(\n column: string,\n op: string,\n operand: unknown,\n atTop: boolean,\n): string[] {\n if (op === \"$between\") {\n if (!Array.isArray(operand) || operand.length !== 2) {\n throw new Error(\n `[Directive] predicateToPostgrest: $between operand must be a [low, high] tuple`,\n );\n }\n const lo = atTop\n ? colClause(column, renderOp(\"$gte\", operand[0]))\n : `${column}.${renderOp(\"$gte\", operand[0])}`;\n const hi = atTop\n ? colClause(column, renderOp(\"$lte\", operand[1]))\n : `${column}.${renderOp(\"$lte\", operand[1])}`;\n\n return [lo, hi];\n }\n\n return [\n atTop\n ? colClause(column, renderOp(op, operand))\n : `${column}.${renderOp(op, operand)}`,\n ];\n}\n\n/**\n * Convert a predicate into PostgREST clause strings. Top-level returns a\n * list of `column=value` pairs (joined by `&`); nested returns\n * grouped/clause-list strings depending on the parent combinator.\n *\n * @param atTop When true, clauses are top-level (& separator).\n * When false, clauses are inside `and=(...)`/`or=(...)`\n * and must use `,` separator and `column.op.val` syntax.\n */\nfunction build(\n spec: unknown,\n allowed: readonly string[] | undefined,\n atTop: boolean,\n depth: number,\n): string[] {\n if (depth > MAX_PREDICATE_DEPTH) {\n throw new Error(\n `[Directive] predicateToPostgrest: predicate depth limit (${MAX_PREDICATE_DEPTH}) exceeded — flatten the predicate or check for a cyclic spec object`,\n );\n }\n if (spec === null || typeof spec !== \"object\") {\n throw new Error(\n `[Directive] predicateToPostgrest: predicate must be an object or array`,\n );\n }\n\n if (Array.isArray(spec)) {\n const out: string[] = [];\n for (const clause of spec) {\n if (\n !clause ||\n typeof clause !== \"object\" ||\n !(\"fact\" in clause) ||\n !(\"op\" in clause)\n ) {\n throw new Error(\n `[Directive] predicateToPostgrest: array-form clause must be { fact, op, value }`,\n );\n }\n const c = clause as { fact: string; op: string; value: unknown };\n assertColumn(c.fact, allowed);\n out.push(...renderColumnOps(c.fact, c.op, c.value, atTop));\n }\n\n return out;\n }\n\n if (\"$all\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$all\");\n const arr = (spec as { $all: unknown[] }).$all;\n if (!Array.isArray(arr)) {\n throw new Error(`[Directive] predicateToPostgrest: $all must be an array`);\n }\n if (atTop) {\n const out: string[] = [];\n for (const child of arr) {\n out.push(...build(child, allowed, true, depth + 1));\n }\n\n return out;\n }\n const parts: string[] = [];\n for (const child of arr) {\n parts.push(...build(child, allowed, false, depth + 1));\n }\n\n return [groupClause(\"and\", parts)];\n }\n if (\"$any\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$any\");\n const arr = (spec as { $any: unknown[] }).$any;\n if (!Array.isArray(arr)) {\n throw new Error(`[Directive] predicateToPostgrest: $any must be an array`);\n }\n // Empty $any is tautological-false. PostgREST has no clean way to\n // express \"match nothing\"; pick a stable contradiction.\n if (arr.length === 0) {\n // pg's `id` exists on every base table — match a value no row can have.\n return atTop\n ? [\"id=is.null\", \"id=not.is.null\"]\n : [groupClause(\"and\", [\"id.is.null\", \"id.not.is.null\"])];\n }\n const parts: string[] = [];\n for (const child of arr) {\n parts.push(...build(child, allowed, false, depth + 1));\n }\n\n return [groupClause(\"or\", parts)];\n }\n if (\"$not\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$not\");\n const inner = (spec as { $not: unknown }).$not;\n const parts = build(inner, allowed, false, depth + 1);\n\n return [groupClause(\"not.and\", parts)];\n }\n\n // Object form\n const out: string[] = [];\n for (const [key, value] of Object.entries(spec as Record<string, unknown>)) {\n assertColumn(key, allowed);\n if (isOperatorObject(value)) {\n for (const [op, operand] of Object.entries(value)) {\n if (!PREDICATE_OPERATORS.has(op)) {\n throw new Error(\n `[Directive] predicateToPostgrest: unknown operator \"${op}\" on column \"${key}\" — known: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n out.push(...renderColumnOps(key, op, operand, atTop));\n }\n } else if (isPlainObject(value)) {\n throw new Error(\n `[Directive] predicateToPostgrest: nested predicate at \"${key}\" — single-table queries only`,\n );\n } else {\n out.push(...renderColumnOps(key, \"$eq\", value, atTop));\n }\n }\n\n return out;\n}\n\n/**\n * Encode a clause string per PostgREST URL conventions.\n *\n * Splits on first `=` so the column/logical name is preserved verbatim\n * (it's identifier-validated) and only the value side is URL-encoded.\n */\nfunction encodeClause(c: string): string {\n const eq = c.indexOf(\"=\");\n if (eq < 0) return encodeURIComponent(c);\n const key = c.slice(0, eq);\n const value = c.slice(eq + 1);\n\n return `${key}=${encodeURIComponent(value)}`;\n}\n\n/**\n * Compile a {@link FactPredicate} to a PostgREST querystring.\n *\n * @example\n * ```ts\n * predicateToPostgrest({ age: { $gte: 18 }, status: { $in: [\"active\", \"pending\"] } })\n * // → \"age=gte.18&status=in.%28active%2Cpending%29\"\n *\n * // Raw mode for debugging / building URLs by hand:\n * predicateToPostgrest({ age: { $gte: 18 } }, { mode: \"raw\" })\n * // → \"age=gte.18\"\n *\n * predicateToPostgrest({ $any: [{ tier: \"gold\" }, { score: { $gte: 100 } }] }, { mode: \"raw\" })\n * // → \"or=(tier.eq.gold,score.gte.100)\"\n * ```\n */\nexport function predicateToPostgrest<F = Record<string, unknown>>(\n predicate: FactPredicate<F>,\n options: PredicateToPostgrestOptions = {},\n): string {\n const mode = options.mode ?? \"querystring\";\n const clauses = build(predicate, options.allowedKeys, true, 0);\n if (clauses.length === 0) return \"\";\n\n return mode === \"raw\" ? clauses.join(\"&\") : clauses.map(encodeClause).join(\"&\");\n}\n","/**\n * Schema Type Builders\n *\n * Provides type-safe schema definitions with optional runtime validation.\n * Used to define fact types, derivation types, event payload types, etc.\n *\n * This module has no dependency on the facts store or tracking system.\n */\n\nimport isDevelopment from \"#is-development\";\nimport type { SchemaType } from \"./types.js\";\n\n// ============================================================================\n// Schema Type Builders\n// ============================================================================\n\n/** Brand symbol for branded types */\ndeclare const Brand: unique symbol;\n\n/** Branded type - adds a unique brand to a base type */\nexport type Branded<T, B extends string> = T & { readonly [Brand]: B };\n\n/** Extended SchemaType with type name for better error messages */\nexport interface ExtendedSchemaType<T> extends SchemaType<T> {\n readonly _typeName?: string;\n readonly _default?: T | (() => T);\n readonly _transform?: (value: unknown) => T;\n readonly _description?: string;\n readonly _refinements?: Array<{\n predicate: (value: T) => boolean;\n message: string;\n }>;\n /** Mutable - set by array validators to indicate which element failed */\n _lastFailedIndex?: number;\n /** Optional metadata for debugging and devtools (never read on hot path). */\n readonly _meta?: import(\"./types/meta.js\").DefinitionMeta;\n}\n\n/** Create a schema type builder with optional type name */\nfunction createSchemaType<T>(\n validators: Array<(v: T) => boolean> = [],\n typeName?: string,\n defaultValue?: T | (() => T),\n transform?: (value: unknown) => T,\n description?: string,\n refinements?: Array<{ predicate: (value: T) => boolean; message: string }>,\n meta?: import(\"./types/meta.js\").DefinitionMeta,\n): ExtendedSchemaType<T> {\n return {\n _type: undefined as unknown as T,\n _validators: validators,\n _typeName: typeName,\n _default: defaultValue,\n _transform: transform,\n _description: description,\n _refinements: refinements,\n _meta: meta,\n validate(fn: (value: T) => boolean) {\n return createSchemaType(\n [...validators, fn],\n typeName,\n defaultValue,\n transform,\n description,\n refinements,\n meta,\n );\n },\n };\n}\n\n/** Chainable schema type with all common methods */\nexport interface ChainableSchemaType<T> extends ExtendedSchemaType<T> {\n default(value: T | (() => T)): ChainableSchemaType<T>;\n transform<U>(fn: (value: T) => U): ChainableSchemaType<U>;\n brand<B extends string>(): ChainableSchemaType<Branded<T, B>>;\n describe(description: string): ChainableSchemaType<T>;\n refine(\n predicate: (value: T) => boolean,\n message: string,\n ): ChainableSchemaType<T>;\n nullable(): ChainableSchemaType<T | null>;\n optional(): ChainableSchemaType<T | undefined>;\n /** Attach metadata for debugging and devtools. */\n meta(meta: import(\"./types/meta.js\").DefinitionMeta): ChainableSchemaType<T>;\n}\n\n/** Create a chainable schema type with common methods */\nfunction createChainableType<T>(\n validators: Array<(v: T) => boolean>,\n typeName: string,\n defaultValue?: T | (() => T),\n transform?: (value: unknown) => T,\n description?: string,\n refinements?: Array<{ predicate: (value: T) => boolean; message: string }>,\n fieldMeta?: import(\"./types/meta.js\").DefinitionMeta,\n): ChainableSchemaType<T> {\n const base = createSchemaType<T>(\n validators,\n typeName,\n defaultValue,\n transform,\n description,\n refinements,\n fieldMeta,\n );\n return {\n ...base,\n default(value: T | (() => T)) {\n return createChainableType(\n validators,\n typeName,\n value,\n transform,\n description,\n refinements,\n fieldMeta,\n );\n },\n transform<U>(fn: (value: T) => U) {\n const newTransform = (v: unknown) => {\n const intermediate = transform ? transform(v) : (v as T);\n return fn(intermediate);\n };\n return createChainableType<U>(\n [],\n typeName,\n undefined,\n newTransform as (v: unknown) => U,\n description,\n undefined,\n fieldMeta,\n );\n },\n brand<B extends string>() {\n return createChainableType<Branded<T, B>>(\n validators as Array<(v: Branded<T, B>) => boolean>,\n `Branded<${typeName}>`,\n defaultValue as Branded<T, B> | (() => Branded<T, B>),\n transform as (value: unknown) => Branded<T, B>,\n description,\n refinements as Array<{\n predicate: (value: Branded<T, B>) => boolean;\n message: string;\n }>,\n fieldMeta,\n );\n },\n describe(desc: string) {\n return createChainableType(\n validators,\n typeName,\n defaultValue,\n transform,\n desc,\n refinements,\n fieldMeta,\n );\n },\n refine(predicate: (value: T) => boolean, message: string) {\n const newRefinements = [...(refinements ?? []), { predicate, message }];\n return createChainableType(\n [...validators, predicate],\n typeName,\n defaultValue,\n transform,\n description,\n newRefinements,\n fieldMeta,\n );\n },\n nullable() {\n return createChainableType<T | null>(\n [\n (v): v is T | null =>\n v === null || validators.every((fn) => fn(v as T)),\n ],\n `${typeName} | null`,\n defaultValue as (T | null) | (() => T | null),\n transform as (value: unknown) => T | null,\n description,\n undefined,\n fieldMeta,\n );\n },\n optional() {\n return createChainableType<T | undefined>(\n [\n (v): v is T | undefined =>\n v === undefined || validators.every((fn) => fn(v as T)),\n ],\n `${typeName} | undefined`,\n defaultValue as (T | undefined) | (() => T | undefined),\n transform as (value: unknown) => T | undefined,\n description,\n undefined,\n fieldMeta,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableType(\n validators,\n typeName,\n defaultValue,\n transform,\n description,\n refinements,\n m,\n );\n },\n };\n}\n\n/**\n * Two-form union schema constructor.\n *\n * Hoisted out of the `t` object literal because the overload-cast pattern\n * (`(impl) as { ovl1; ovl2 }`) inside an object literal triggers a TS\n * declaration-emit \"implicitly has type any\" cycle. Annotating the const\n * with the explicit overload type breaks the cycle so DTS can emit `t`'s\n * shape without recursing through the runtime expression.\n *\n * @internal\n */\ntype UnionFn = {\n <T = unknown>(): ChainableSchemaType<T>;\n <T extends SchemaType<unknown>[]>(\n ...types: T\n ): ChainableSchemaType<T[number] extends SchemaType<infer U> ? U : never>;\n};\n\nconst unionImpl: UnionFn = (<T extends SchemaType<unknown>[]>(...types: T) => {\n if (types.length === 0) {\n return createChainableType<unknown>([], \"union\");\n }\n type UnionType = T[number] extends SchemaType<infer U> ? U : never;\n const typeNames = types.map(\n (schemaType) =>\n (schemaType as ExtendedSchemaType<unknown>)._typeName ?? \"unknown\",\n );\n return createChainableType<UnionType>(\n [\n (v): v is UnionType =>\n types.some((schemaType) => schemaType._validators.every((fn) => fn(v))),\n ],\n typeNames.join(\" | \"),\n );\n}) as UnionFn;\n\n/**\n * Schema type builders for defining fact types.\n *\n * @remarks\n * Each builder returns a chainable {@link ExtendedSchemaType} with validation\n * methods (`.min()`, `.max()`, `.pattern()`, etc.) and dev-mode runtime\n * type checking. Validators are tree-shaken in production builds.\n *\n * @example\n * ```typescript\n * const module = createModule(\"example\", {\n * schema: {\n * name: t.string(),\n * age: t.number().min(0).max(150),\n * active: t.boolean(),\n * tags: t.array<string>().of(t.string()),\n * user: t.object<{ id: string; email: string }>(),\n * },\n * });\n * ```\n *\n * @public\n */\nexport const t = {\n /**\n * Create a string schema type.\n *\n * @example\n * ```typescript\n * // Basic string\n * schema: { name: t.string() }\n *\n * // String literal union (for type safety)\n * schema: { phase: t.string<\"red\" | \"green\" | \"yellow\">() }\n *\n * // With custom validation\n * schema: { email: t.string().validate(s => s.includes(\"@\")) }\n *\n * // With transform\n * schema: { trimmed: t.string().transform(s => s.trim()) }\n *\n * // With brand\n * schema: { userId: t.string().brand<\"UserId\">() }\n * ```\n */\n string<T extends string = string>() {\n type ChainableString = ChainableSchemaType<T> & {\n minLength(n: number): ChainableString;\n maxLength(n: number): ChainableString;\n pattern(regex: RegExp): ChainableString;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableString;\n };\n\n const createChainableString = (\n validators: Array<(v: T) => boolean>,\n defaultValue?: T | (() => T),\n transform?: (value: unknown) => T,\n description?: string,\n refinements?: Array<{\n predicate: (value: T) => boolean;\n message: string;\n }>,\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableString => {\n const chainable = createChainableType<T>(\n validators,\n \"string\",\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n return {\n ...chainable,\n minLength(n: number) {\n return createChainableString(\n [...validators, (v) => (v as string).length >= n],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n maxLength(n: number) {\n return createChainableString(\n [...validators, (v) => (v as string).length <= n],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n pattern(regex: RegExp) {\n return createChainableString(\n [...validators, (v) => regex.test(v as string)],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n default(value: T | (() => T)) {\n return createChainableString(\n validators,\n value,\n transform,\n description,\n refinements,\n fm,\n );\n },\n describe(desc: string) {\n return createChainableString(\n validators,\n defaultValue,\n transform,\n desc,\n refinements,\n fm,\n );\n },\n refine(predicate: (value: T) => boolean, message: string) {\n const newRefinements = [\n ...(refinements ?? []),\n { predicate, message },\n ];\n return createChainableString(\n [...validators, predicate],\n defaultValue,\n transform,\n description,\n newRefinements,\n fm,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableString(\n validators,\n defaultValue,\n transform,\n description,\n refinements,\n m,\n );\n },\n };\n };\n\n return createChainableString([(v): v is T => typeof v === \"string\"]);\n },\n\n /**\n * Create a number schema type with optional min/max constraints.\n *\n * @example\n * ```typescript\n * // Basic number\n * schema: { count: t.number() }\n *\n * // With range constraints\n * schema: { age: t.number().min(0).max(150) }\n *\n * // With custom validation\n * schema: { even: t.number().validate(n => n % 2 === 0) }\n *\n * // With default\n * schema: { count: t.number().default(0) }\n *\n * // With transform (from string)\n * schema: { age: t.number().transform(v => parseInt(String(v), 10)) }\n * ```\n */\n number() {\n type ChainableNumber = ChainableSchemaType<number> & {\n min(n: number): ChainableNumber;\n max(n: number): ChainableNumber;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableNumber;\n };\n\n const createChainableNumber = (\n validators: Array<(v: number) => boolean>,\n defaultValue?: number | (() => number),\n transform?: (value: unknown) => number,\n description?: string,\n refinements?: Array<{\n predicate: (value: number) => boolean;\n message: string;\n }>,\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableNumber => {\n const chainable = createChainableType<number>(\n validators,\n \"number\",\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n return {\n ...chainable,\n min(n: number) {\n return createChainableNumber(\n [...validators, (v) => v >= n],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n max(n: number) {\n return createChainableNumber(\n [...validators, (v) => v <= n],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n default(value: number | (() => number)) {\n return createChainableNumber(\n validators,\n value,\n transform,\n description,\n refinements,\n fm,\n );\n },\n describe(desc: string) {\n return createChainableNumber(\n validators,\n defaultValue,\n transform,\n desc,\n refinements,\n fm,\n );\n },\n refine(predicate: (value: number) => boolean, message: string) {\n const newRefinements = [\n ...(refinements ?? []),\n { predicate, message },\n ];\n return createChainableNumber(\n [...validators, predicate],\n defaultValue,\n transform,\n description,\n newRefinements,\n fm,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableNumber(\n validators,\n defaultValue,\n transform,\n description,\n refinements,\n m,\n );\n },\n };\n };\n return createChainableNumber([(v) => typeof v === \"number\"]);\n },\n\n /**\n * Create a boolean schema type.\n *\n * @example\n * ```typescript\n * schema: {\n * active: t.boolean(),\n * verified: t.boolean().default(false),\n * }\n * ```\n */\n boolean() {\n return createChainableType<boolean>(\n [(v) => typeof v === \"boolean\"],\n \"boolean\",\n );\n },\n\n /**\n * Create an array schema type.\n * Can be used with or without element validation:\n * - `t.array<string>()` - Type-only, no element validation\n * - `t.array<string>().of(t.string())` - With element validation\n */\n array<T>() {\n type ChainableArray = ChainableSchemaType<T[]> & {\n of(elementType: SchemaType<T>): ChainableArray;\n nonEmpty(): ChainableArray;\n maxLength(n: number): ChainableArray;\n minLength(n: number): ChainableArray;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableArray;\n _lastFailedIndex?: number;\n };\n\n const createChainableArray = (\n validators: Array<(v: T[]) => boolean>,\n elementType?: SchemaType<T>,\n defaultValue?: T[] | (() => T[]),\n description?: string,\n indexRef?: { value: number },\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableArray => {\n const chainable = createChainableType<T[]>(\n validators,\n \"array\",\n defaultValue,\n undefined,\n description,\n undefined,\n fm,\n );\n // Use ref for storing failed index (shared with validator closure)\n const ref = indexRef ?? { value: -1 };\n const result: ChainableArray = {\n ...chainable,\n get _lastFailedIndex() {\n return ref.value;\n },\n set _lastFailedIndex(v: number) {\n ref.value = v;\n },\n of(et: SchemaType<T>) {\n const newRef = { value: -1 };\n return createChainableArray(\n [\n ...validators,\n (v) => {\n for (let i = 0; i < v.length; i++) {\n if (!et._validators.every((validator) => validator(v[i]))) {\n newRef.value = i;\n return false;\n }\n }\n return true;\n },\n ],\n et,\n defaultValue,\n description,\n newRef,\n fm,\n );\n },\n nonEmpty() {\n return createChainableArray(\n [...validators, (v) => v.length > 0],\n elementType,\n defaultValue,\n description,\n ref,\n fm,\n );\n },\n maxLength(n: number) {\n return createChainableArray(\n [...validators, (v) => v.length <= n],\n elementType,\n defaultValue,\n description,\n ref,\n fm,\n );\n },\n minLength(n: number) {\n return createChainableArray(\n [...validators, (v) => v.length >= n],\n elementType,\n defaultValue,\n description,\n ref,\n fm,\n );\n },\n default(value: T[] | (() => T[])) {\n return createChainableArray(\n validators,\n elementType,\n value,\n description,\n ref,\n fm,\n );\n },\n describe(desc: string) {\n return createChainableArray(\n validators,\n elementType,\n defaultValue,\n desc,\n ref,\n fm,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableArray(\n validators,\n elementType,\n defaultValue,\n description,\n ref,\n m,\n );\n },\n };\n return result;\n };\n return createChainableArray([(v) => Array.isArray(v)]);\n },\n\n /**\n * Create an object schema type for any complex value.\n * Can be used with or without shape validation:\n * - `t.object<User>()` - Type-only, no property validation\n * - `t.object<User>().shape({ name: t.string(), age: t.number() })` - With property validation\n *\n * For arrays, prefer `t.array<T>()` which adds `Array.isArray` validation.\n */\n object<T>() {\n type ChainableObject = ChainableSchemaType<T> & {\n shape(schema: { [K in keyof T]?: SchemaType<T[K]> }): ChainableObject;\n nonNull(): ChainableObject;\n hasKeys(...keys: string[]): ChainableObject;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableObject;\n };\n\n const createChainableObject = (\n validators: Array<(v: T) => boolean>,\n defaultValue?: T | (() => T),\n description?: string,\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableObject => {\n const chainable = createChainableType<T>(\n validators,\n \"object\",\n defaultValue,\n undefined,\n description,\n undefined,\n fm,\n );\n return {\n ...chainable,\n shape(shapeSchema: { [K in keyof T]?: SchemaType<T[K]> }) {\n return createChainableObject(\n [\n ...validators,\n (v) => {\n for (const [key, schemaType] of Object.entries(shapeSchema)) {\n const value = (v as Record<string, unknown>)[key];\n const schemaT = schemaType as SchemaType<unknown>;\n if (\n schemaT &&\n !schemaT._validators.every((validator) => validator(value))\n ) {\n return false;\n }\n }\n return true;\n },\n ],\n defaultValue,\n description,\n fm,\n );\n },\n nonNull() {\n return createChainableObject(\n [...validators, (v) => v !== null && v !== undefined],\n defaultValue,\n description,\n fm,\n );\n },\n hasKeys(...keys: string[]) {\n return createChainableObject(\n [\n ...validators,\n (v) => keys.every((k) => k in (v as Record<string, unknown>)),\n ],\n defaultValue,\n description,\n fm,\n );\n },\n default(value: T | (() => T)) {\n return createChainableObject(validators, value, description, fm);\n },\n describe(desc: string) {\n return createChainableObject(validators, defaultValue, desc, fm);\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableObject(\n validators,\n defaultValue,\n description,\n m,\n );\n },\n };\n };\n return createChainableObject([\n (v) => typeof v === \"object\" && v !== null && !Array.isArray(v),\n ]);\n },\n\n /**\n * Create an enum schema type for string literal unions.\n *\n * @example\n * ```typescript\n * // Define allowed values\n * schema: { status: t.enum(\"idle\", \"loading\", \"success\", \"error\") }\n *\n * // Type is inferred as \"idle\" | \"loading\" | \"success\" | \"error\"\n * ```\n */\n enum<T extends string>(...values: T[]) {\n if (isDevelopment && values.length === 0) {\n console.warn(\n \"[Directive] t.enum() called with no values - this will reject all strings\",\n );\n }\n const valueSet = new Set(values);\n return createChainableType<T>(\n [(v): v is T => typeof v === \"string\" && valueSet.has(v as T)],\n `enum(${values.join(\"|\")})`,\n );\n },\n\n /**\n * Create a literal schema type for exact value matching.\n *\n * @example\n * ```typescript\n * // Exact string match\n * schema: { type: t.literal(\"user\") }\n *\n * // Exact number match\n * schema: { version: t.literal(1) }\n *\n * // Exact boolean\n * schema: { enabled: t.literal(true) }\n * ```\n */\n literal<T extends string | number | boolean>(value: T) {\n return createChainableType<T>(\n [(v): v is T => v === value],\n `literal(${String(value)})`,\n );\n },\n\n /**\n * Create a nullable schema type (T | null).\n *\n * @example\n * ```typescript\n * // Nullable string\n * schema: { name: t.nullable(t.string()) }\n *\n * // Nullable object\n * schema: { user: t.nullable(t.object<User>()) }\n * ```\n */\n nullable<T>(innerType: SchemaType<T>) {\n const innerTypeName =\n (innerType as ExtendedSchemaType<T>)._typeName ?? \"unknown\";\n return createSchemaType<T | null>(\n [\n (v): v is T | null => {\n if (v === null) {\n return true;\n }\n return innerType._validators.every((validator) => validator(v as T));\n },\n ],\n `${innerTypeName} | null`,\n ) as SchemaType<T | null>;\n },\n\n /**\n * Create an optional schema type (T | undefined).\n *\n * @example\n * ```typescript\n * // Optional string\n * schema: { nickname: t.optional(t.string()) }\n *\n * // Optional number\n * schema: { age: t.optional(t.number()) }\n * ```\n */\n optional<T>(innerType: SchemaType<T>) {\n const innerTypeName =\n (innerType as ExtendedSchemaType<T>)._typeName ?? \"unknown\";\n return createSchemaType<T | undefined>(\n [\n (v): v is T | undefined => {\n if (v === undefined) {\n return true;\n }\n return innerType._validators.every((validator) => validator(v as T));\n },\n ],\n `${innerTypeName} | undefined`,\n ) as SchemaType<T | undefined>;\n },\n\n /**\n * Create a union schema type.\n *\n * **Two forms:**\n * - `t.union(t.string(), t.number())` — variadic schema args; the runtime\n * validator checks that the value matches at least one inner schema.\n * - `t.union<string | number | boolean>()` — generic-only form with no\n * schema args; the runtime validator accepts ANY value (mirrors\n * {@link unknown} plus generic narrowing). Use this for polymorphic\n * payloads where the union is too dynamic to enumerate as inner schemas\n * (e.g. an `UPDATE_FIELD` event whose `value` may be `string | number |\n * boolean | Date`).\n *\n * Chainable methods (`.validate`, `.transform`, `.default`, `.describe`,\n * `.refine`, `.optional`, `.nullable`) work the same for both forms.\n *\n * @example\n * ```typescript\n * // Variadic — runtime validation against inner schemas\n * schema: { value: t.union(t.string(), t.number()) }\n *\n * // Generic-only — type-only narrowing, runtime accepts any value\n * schema: {\n * payload: t.union<string | number | boolean>(),\n * }\n *\n * // Add a custom predicate via .validate when you still want a runtime check\n * schema: {\n * strict: t.union<string | number>().validate(\n * (v) => typeof v === \"string\" || typeof v === \"number\",\n * ),\n * }\n * ```\n */\n union: unionImpl,\n\n /**\n * Create a record schema type for dynamic key-value maps.\n *\n * @example\n * ```typescript\n * // Record with string values\n * schema: { metadata: t.record(t.string()) }\n *\n * // Record with number values\n * schema: { scores: t.record(t.number()) }\n * ```\n */\n record<V>(valueType: SchemaType<V>) {\n const valueTypeName =\n (valueType as ExtendedSchemaType<V>)._typeName ?? \"unknown\";\n return createChainableType<Record<string, V>>(\n [\n (v): v is Record<string, V> => {\n if (typeof v !== \"object\" || v === null || Array.isArray(v))\n return false;\n return Object.values(v).every((val) =>\n valueType._validators.every((validator) => validator(val)),\n );\n },\n ],\n `Record<string, ${valueTypeName}>`,\n );\n },\n\n /**\n * Create a tuple schema type for fixed-length arrays with specific types.\n *\n * @example\n * ```typescript\n * // [string, number] tuple\n * schema: { coord: t.tuple(t.string(), t.number()) }\n *\n * // [x, y, z] coordinates\n * schema: { position: t.tuple(t.number(), t.number(), t.number()) }\n * ```\n */\n tuple<T extends SchemaType<unknown>[]>(...types: T) {\n if (isDevelopment && types.length === 0) {\n console.warn(\n \"[Directive] t.tuple() called with no types - this will only accept empty arrays\",\n );\n }\n type TupleType = {\n [K in keyof T]: T[K] extends SchemaType<infer U> ? U : never;\n };\n const typeNames = types.map(\n (schemaType) =>\n (schemaType as ExtendedSchemaType<unknown>)._typeName ?? \"unknown\",\n );\n return createChainableType<TupleType>(\n [\n (v): v is TupleType => {\n if (!Array.isArray(v) || v.length !== types.length) {\n return false;\n }\n return types.every((schemaType, i) =>\n schemaType._validators.every((validator) => validator(v[i])),\n );\n },\n ],\n `[${typeNames.join(\", \")}]`,\n );\n },\n\n /**\n * Create a date schema type.\n *\n * @example\n * ```typescript\n * schema: { createdAt: t.date() }\n * ```\n */\n date() {\n return createChainableType<Date>(\n [(v): v is Date => v instanceof Date && !Number.isNaN(v.getTime())],\n \"Date\",\n );\n },\n\n /**\n * Create a UUID schema type.\n *\n * @example\n * ```typescript\n * schema: { id: t.uuid() }\n * ```\n */\n uuid() {\n const uuidRegex =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return createChainableType<string>(\n [(v): v is string => typeof v === \"string\" && uuidRegex.test(v)],\n \"uuid\",\n );\n },\n\n /**\n * Create an email schema type.\n *\n * @example\n * ```typescript\n * schema: { email: t.email() }\n * ```\n */\n email() {\n // Simple email regex - for comprehensive validation use Zod\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return createChainableType<string>(\n [(v): v is string => typeof v === \"string\" && emailRegex.test(v)],\n \"email\",\n );\n },\n\n /**\n * Create a URL schema type.\n *\n * @example\n * ```typescript\n * schema: { website: t.url() }\n * ```\n */\n url() {\n return createChainableType<string>(\n [\n (v): v is string => {\n if (typeof v !== \"string\") {\n return false;\n }\n try {\n new URL(v);\n return true;\n } catch {\n return false;\n }\n },\n ],\n \"url\",\n );\n },\n\n /**\n * Create a bigint schema type.\n *\n * @example\n * ```typescript\n * schema: { largeNumber: t.bigint() }\n * ```\n */\n bigint() {\n return createChainableType<bigint>(\n [(v): v is bigint => typeof v === \"bigint\"],\n \"bigint\",\n );\n },\n\n /**\n * Create an `any` schema type that accepts all values without validation.\n *\n * @example\n * ```typescript\n * schema: { payload: t.any() }\n * ```\n */\n // biome-ignore lint/suspicious/noExplicitAny: Intentional any type for schema builder\n any() {\n return createChainableType<any>([], \"any\");\n },\n\n /**\n * Create an `unknown` schema type that accepts all values without validation.\n * Prefer `t.unknown()` over `t.any()` for stricter downstream type checking.\n *\n * @example\n * ```typescript\n * schema: { data: t.unknown() }\n * ```\n */\n unknown() {\n return createChainableType<unknown>([], \"unknown\");\n },\n};\n","/**\n * Module - The declarative API for defining Directive modules\n *\n * Modules group related facts, constraints, resolvers, effects, and derivations.\n */\n\nimport isDevelopment from \"#is-development\";\nimport { BLOCKED_PROPS } from \"./tracking.js\";\nimport type {\n CrossModuleConstraintsDef,\n CrossModuleDeps,\n CrossModuleDerivationsDef,\n CrossModuleEffectsDef,\n DefinitionMeta,\n EffectsDef,\n Facts,\n ModuleDef,\n ModuleHooks,\n ModuleSchema,\n TypedConstraintsDef,\n TypedDerivationsDef,\n TypedEventsDef,\n TypedResolversDef,\n} from \"./types.js\";\n\n// ============================================================================\n// Module Configuration\n// ============================================================================\n\n/**\n * Module configuration with consolidated schema.\n *\n * derive and events are optional - omit them if your schema has empty derivations/events.\n */\nexport interface ModuleConfig<M extends ModuleSchema> {\n schema: M;\n init?: (facts: Facts<M[\"facts\"]>) => void;\n derive?: TypedDerivationsDef<M>;\n events?: TypedEventsDef<M>;\n effects?: EffectsDef<M[\"facts\"]>;\n constraints?: TypedConstraintsDef<M>;\n resolvers?: TypedResolversDef<M>;\n hooks?: ModuleHooks<M>;\n /** Optional metadata for debugging and devtools (never read on hot path). */\n meta?: DefinitionMeta;\n /** History configuration — controls which events create snapshots for undo/redo. */\n history?: {\n /** Events that create history snapshots. Omit to snapshot all events. */\n snapshotEvents?: Array<\n keyof (M[\"events\"] extends Record<string, unknown>\n ? M[\"events\"]\n : Record<string, never>) &\n string\n >;\n };\n}\n\n/**\n * Module configuration with cross-module dependencies for type-safe access\n * to other modules' facts in effects and constraints.\n *\n * When crossModuleDeps is provided:\n * - Own module facts: `facts.self.*`\n * - Cross-module facts: `facts.{dep}.*`\n *\n * @example\n * ```typescript\n * import { authSchema } from './auth';\n * import { dataSchema } from './data';\n *\n * const uiModule = createModule(\"ui\", {\n * schema: uiSchema,\n * crossModuleDeps: { auth: authSchema, data: dataSchema },\n * effects: {\n * onAuthChange: {\n * run: (facts) => {\n * facts.self.notifications // ✅ own module via \"self\"\n * facts.auth.isAuthenticated // ✅ cross-module (namespaced)\n * facts.data.users // ✅ cross-module (namespaced)\n * }\n * }\n * },\n * constraints: {\n * fetchWhenAuth: {\n * when: (facts) => facts.auth.isAuthenticated && facts.self.users.length === 0,\n * require: { type: \"FETCH_USERS\" },\n * }\n * }\n * });\n * ```\n */\nexport interface ModuleConfigWithDeps<\n M extends ModuleSchema,\n Deps extends CrossModuleDeps,\n> {\n schema: M;\n /**\n * Cross-module dependencies for type-safe access in derive/effects/constraints.\n *\n * **Access patterns by context:**\n * - `derive`, `effects`, `constraints`: Use `facts.self.*` for own module, `facts.{dep}.*` for cross-module\n * - `init`, `events`, `resolvers`: Use flat access (`facts.myFact`) - no cross-module access\n *\n * This separation ensures initialization and event handling stay scoped to own module,\n * while observers (derive/effects/constraints) can see across modules.\n *\n * @example\n * ```typescript\n * crossModuleDeps: { auth: authSchema },\n * init: (facts) => { facts.users = []; }, // flat access\n * derive: { count: (facts) => facts.self.users.length }, // facts.self.*\n * effects: { log: { run: (facts) => console.log(facts.auth.token) } }, // facts.{dep}.*\n * ```\n */\n crossModuleDeps: Deps;\n /** Initialize module facts. Uses flat access (`facts.myFact`) to ensure modules initialize independently. */\n init?: (facts: Facts<M[\"facts\"]>) => void;\n /** Derivations with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n derive?: CrossModuleDerivationsDef<M, Deps>;\n /** Event handlers. Uses flat access (`facts.myFact`) to keep mutations scoped to own module. */\n events?: TypedEventsDef<M>;\n /** Effects with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n effects?: CrossModuleEffectsDef<M, Deps>;\n /** Constraints with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n constraints?: CrossModuleConstraintsDef<M, Deps>;\n /** Resolvers. Uses flat access (`ctx.facts.myFact`) to keep async mutations scoped to own module. */\n resolvers?: TypedResolversDef<M>;\n hooks?: ModuleHooks<M>;\n /** Optional metadata for debugging and devtools (never read on hot path). */\n meta?: DefinitionMeta;\n /** History configuration — controls which events create snapshots for undo/redo. */\n history?: {\n /** Events that create history snapshots. Omit to snapshot all events. */\n snapshotEvents?: Array<\n keyof (M[\"events\"] extends Record<string, unknown>\n ? M[\"events\"]\n : Record<string, never>) &\n string\n >;\n };\n}\n\n// ============================================================================\n// Module Validation Helpers (dev-mode only)\n// ============================================================================\n\n/** Validate module ID follows naming conventions */\nfunction validateModuleId(id: string): void {\n if (!id || typeof id !== \"string\") {\n console.warn(\"[Directive] Module ID must be a non-empty string\");\n\n return;\n }\n if (!/^(__[a-z][a-z0-9_-]*|[a-z][a-z0-9-]*)$/i.test(id)) {\n console.warn(\n `[Directive] Module ID \"${id}\" should follow kebab-case convention (e.g., \"my-module\")`,\n );\n }\n}\n\n/** Warn when keys in `implKeys` are missing from `schemaKeys` and vice versa */\nfunction validateKeyAlignment(\n implKeys: Set<string>,\n schemaKeys: Set<string>,\n implLabel: string,\n schemaLabel: string,\n missingImplMessage: string,\n): void {\n for (const key of implKeys) {\n if (!schemaKeys.has(key)) {\n console.warn(\n `[Directive] ${implLabel} \"${key}\" not declared in ${schemaLabel}`,\n );\n }\n }\n for (const key of schemaKeys) {\n if (!implKeys.has(key)) {\n console.warn(\n `[Directive] ${schemaLabel}[\"${key}\"] ${missingImplMessage}`,\n );\n }\n }\n}\n\n/** Validate history.snapshotEvents reference valid event names */\nfunction validateSnapshotEvents(\n snapshotEvents: string[],\n schemaEvents: Record<string, unknown>,\n): void {\n if (snapshotEvents.length === 0) {\n console.warn(\n \"[Directive] history.snapshotEvents is an empty array — no events will create history snapshots. \" +\n \"Omit history.snapshotEvents entirely to snapshot all events, or list specific events.\",\n );\n }\n const schemaEventKeys = new Set(Object.keys(schemaEvents));\n for (const eventName of snapshotEvents) {\n if (!schemaEventKeys.has(eventName)) {\n console.warn(\n `[Directive] history.snapshotEvents entry \"${eventName}\" not declared in schema.events. ` +\n `Available events: ${[...schemaEventKeys].join(\", \") || \"(none)\"}`,\n );\n }\n }\n}\n\n/** Validate resolvers reference valid requirement types */\nfunction validateResolverRequirements(\n resolvers: Record<string, unknown>,\n requirements: Record<string, unknown>,\n): void {\n const requirementTypes = new Set(Object.keys(requirements));\n for (const [resolverName, resolver] of Object.entries(resolvers)) {\n const resolverDef = resolver as { requirement?: string };\n if (\n typeof resolverDef.requirement === \"string\" &&\n !requirementTypes.has(resolverDef.requirement)\n ) {\n console.warn(\n `[Directive] Resolver \"${resolverName}\" references unknown requirement type \"${resolverDef.requirement}\". ` +\n `Available types: ${[...requirementTypes].join(\", \") || \"(none)\"}`,\n );\n }\n }\n}\n\n/**\n * Throw when a module's fact key conflicts with a reserved namespace pivot\n * or evaluation alias used by the data-form predicate runtime. Two classes:\n *\n * - The cross-module namespace pivots — `self` and every declared\n * `crossModuleDeps` namespace. A fact named after a pivot would make\n * `prefixPredicateSpec` mis-route the pivot's nested predicate against\n * the pivot's namespace instead of treating it as a literal fact lookup.\n * - The evaluation aliases `prev` and `current` — reserved for the\n * previous/live snapshot scopes (`$changed`, clobber baselines). A fact\n * with one of these names would shadow the alias in those scopes.\n *\n * Thrown unconditionally — this is a structural integrity check, not a dev\n * convenience. Production users running into this would otherwise see silent\n * mis-routing.\n */\nfunction validatePivotNameConflicts<M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): void {\n const facts = (config.schema?.facts ?? {}) as Record<string, unknown>;\n const factKeys = Object.keys(facts);\n if (factKeys.length === 0) {\n return;\n }\n const reserved = new Set<string>([\"self\", \"prev\", \"current\"]);\n const deps =\n \"crossModuleDeps\" in config && config.crossModuleDeps\n ? Object.keys(\n config.crossModuleDeps as Record<string, unknown>,\n )\n : [];\n for (const depName of deps) {\n reserved.add(depName);\n }\n for (const key of factKeys) {\n if (reserved.has(key)) {\n throw new Error(\n `[Directive] module '${id}': fact key '${key}' conflicts with a reserved namespace pivot or evaluation alias (self / prev / current / a crossModuleDep namespace). Three fixes:\\n` +\n ` 1. Rename the fact (e.g. ${key}_)\\n` +\n ` 2. Remove '${key}' from this module's crossModuleDeps if it's not actually needed\\n` +\n ` 3. Move the fact under a wrapping namespace (t.object({ inner: ... }))`,\n );\n }\n }\n}\n\n/**\n * Reject constraint `owns` entries that name a reserved property — a\n * `BLOCKED_PROPS` key (`__proto__`, `constructor`, `prototype`) or a\n * `$`-prefixed key. Such names can never be owned fact slots, so the\n * clobber-detection binding would silently no-op. A structural integrity\n * check — runs unconditionally, not just in dev.\n */\nfunction validateOwnsKeys<M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): void {\n const constraints = config.constraints as\n | Record<string, { owns?: readonly string[] }>\n | undefined;\n if (!constraints) {\n return;\n }\n for (const [cid, constraint] of Object.entries(constraints)) {\n const owns = constraint?.owns;\n if (!owns) {\n continue;\n }\n for (const key of owns) {\n if (BLOCKED_PROPS.has(key) || key.startsWith(\"$\")) {\n throw new Error(\n `[Directive] module '${id}' constraint '${cid}': owns key '${key}' is reserved (BLOCKED_PROPS or $-prefixed)`,\n );\n }\n }\n }\n}\n\n/** Run all dev-mode validations for a module config */\nfunction validateModuleConfig<M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): void {\n validateModuleId(id);\n\n if (!config.schema) {\n console.warn(\"[Directive] Module schema is required\");\n } else if (!config.schema.facts) {\n console.warn(\"[Directive] Module schema.facts is required\");\n }\n\n validateKeyAlignment(\n new Set(Object.keys(config.derive ?? {})),\n new Set(Object.keys(config.schema?.derivations ?? {})),\n \"Derivation\",\n \"schema.derivations\",\n \"has no matching implementation in derive\",\n );\n\n validateKeyAlignment(\n new Set(Object.keys(config.events ?? {})),\n new Set(Object.keys(config.schema?.events ?? {})),\n \"Event\",\n \"schema.events\",\n \"has no matching handler in events\",\n );\n\n if (config.history?.snapshotEvents) {\n validateSnapshotEvents(\n config.history.snapshotEvents as string[],\n config.schema?.events ?? {},\n );\n }\n\n if (config.resolvers && config.schema?.requirements) {\n validateResolverRequirements(\n config.resolvers as Record<string, unknown>,\n config.schema.requirements,\n );\n }\n}\n\n// ============================================================================\n// createModule\n// ============================================================================\n\n/**\n * Create a module definition with full type inference.\n *\n * The consolidated schema provides:\n * - Derivation composition (`derived.otherDerivation` is typed)\n * - Event dispatch (`system.dispatch({ type: \"...\" })` has autocomplete)\n * - Resolver requirements (`req.payload` is typed based on requirement type)\n *\n * @param id - Unique module identifier (kebab-case recommended)\n * @param config - Module configuration including schema, init, derive, constraints, resolvers, etc.\n * @returns A frozen module definition ready for use with `createSystem`\n *\n * @example\n * ```ts\n * const trafficLight = createModule(\"traffic-light\", {\n * schema: {\n * facts: {\n * phase: t.string<\"red\" | \"green\" | \"yellow\">(),\n * elapsed: t.number(),\n * },\n * derivations: {\n * isRed: t.boolean(),\n * timeRemaining: t.number(),\n * },\n * events: {\n * tick: {},\n * setPhase: { phase: t.string<\"red\" | \"green\" | \"yellow\">() },\n * },\n * requirements: {\n * TRANSITION: { to: t.string<\"red\" | \"green\" | \"yellow\">() },\n * },\n * },\n * init: (facts) => {\n * facts.phase = \"red\";\n * facts.elapsed = 0;\n * },\n * derive: {\n * isRed: (facts) => facts.phase === \"red\",\n * timeRemaining: (facts, derived) => {\n * // derived.isRed is typed as boolean!\n * return derived.isRed ? 30 - facts.elapsed : 0;\n * },\n * },\n * events: {\n * tick: (facts) => { facts.elapsed += 1; },\n * setPhase: (facts, { phase }) => { facts.phase = phase; }, // phase is typed!\n * },\n * constraints: {\n * shouldTransition: {\n * when: (facts) => facts.phase === \"red\" && facts.elapsed > 30,\n * require: { type: \"TRANSITION\", to: \"green\" },\n * },\n * },\n * resolvers: {\n * transition: {\n * requirement: \"TRANSITION\",\n * resolve: async (req, ctx) => {\n * ctx.facts.phase = req.to; // req.to is typed!\n * ctx.facts.elapsed = 0;\n * },\n * },\n * },\n * hooks: {\n * // Optional: observe resolver failures owned by this module.\n * // Fires AFTER retries are exhausted and the engine has handled the error\n * // (error boundary, plugin emit, retry decision). Use it as a side-channel\n * // observer for module-local logging/telemetry — not for recovery.\n * onResolverError: (error, requirement, ctx) => {\n * console.warn(`[traffic-light] resolver failed for ${requirement.type}`, error);\n * },\n * },\n * });\n * ```\n *\n * @example With cross-module dependencies\n * ```ts\n * import { authSchema } from './auth';\n *\n * const dataModule = createModule(\"data\", {\n * schema: dataSchema,\n * crossModuleDeps: { auth: authSchema },\n * constraints: {\n * fetchWhenAuth: {\n * when: (facts) => {\n * // facts.self.* for own module, facts.auth.* for cross-module\n * return facts.auth.isAuthenticated && facts.self.users.length === 0;\n * },\n * require: { type: \"FETCH_USERS\" },\n * },\n * },\n * derive: {\n * canFetch: (facts) => facts.auth.isAuthenticated && facts.self.users.length === 0,\n * },\n * });\n * ```\n *\n * @public\n */\n// Overload 1: With crossModuleDeps\nexport function createModule<\n const M extends ModuleSchema,\n const Deps extends CrossModuleDeps,\n>(id: string, config: ModuleConfigWithDeps<M, Deps>): ModuleDef<M>;\n\n// Overload 2: Without crossModuleDeps (original signature)\nexport function createModule<const M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M>,\n): ModuleDef<M>;\n\n// Overload 3: Union (used by createModuleFactory)\nexport function createModule<const M extends ModuleSchema>(\n id: string,\n config: ModuleConfigWithDeps<M, CrossModuleDeps> | ModuleConfig<M>,\n): ModuleDef<M>;\n\n/** @internal Implementation overload — see public overloads above. */\nexport function createModule<const M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): ModuleDef<M> {\n // Pivot-name conflicts are a structural integrity check, not a dev\n // convenience — run unconditionally.\n validatePivotNameConflicts(id, config);\n\n // Reserved `owns` keys would silently disable clobber-detection — a\n // structural integrity check, run unconditionally.\n validateOwnsKeys(id, config);\n\n if (isDevelopment) {\n validateModuleConfig(id, config);\n }\n\n // Extract crossModuleDeps if present (for runtime proxy creation)\n const crossModuleDeps =\n \"crossModuleDeps\" in config ? config.crossModuleDeps : undefined;\n\n return {\n id,\n schema: config.schema,\n init: config.init,\n // Cast to TypedDerivationsDef for ModuleDef compatibility (runtime handles both types)\n derive: (config.derive ?? {}) as TypedDerivationsDef<M>,\n events: config.events ?? ({} as TypedEventsDef<M>),\n effects: config.effects as EffectsDef<M[\"facts\"]> | undefined,\n constraints: config.constraints as TypedConstraintsDef<M> | undefined,\n resolvers: config.resolvers,\n hooks: config.hooks,\n meta: config.meta,\n history: config.history,\n // Store crossModuleDeps for runtime proxy creation\n crossModuleDeps: crossModuleDeps as CrossModuleDeps | undefined,\n };\n}\n\n/**\n * Create a module factory that produces named instances from a single definition.\n * Useful for multi-instance UIs (tabs, panels, multi-tenant) where you need\n * isolated state from the same schema.\n *\n * @param config - Module configuration (same shape as `createModule` minus the `id`)\n * @returns A factory function that accepts a name and returns a `ModuleDef`\n *\n * @example\n * ```typescript\n * const chatRoom = createModuleFactory({\n * schema: {\n * facts: { messages: t.array<string>(), users: t.array<string>() },\n * derivations: { count: t.number() },\n * },\n * init: (facts) => { facts.messages = []; facts.users = []; },\n * derive: { count: (facts) => facts.messages.length },\n * });\n *\n * const system = createSystem({\n * modules: {\n * lobby: chatRoom(\"lobby\"),\n * support: chatRoom(\"support\"),\n * },\n * });\n * ```\n *\n * @public\n */\nexport function createModuleFactory<const M extends ModuleSchema>(\n config: ModuleConfig<M>,\n): (name: string) => ModuleDef<M>;\nexport function createModuleFactory<\n const M extends ModuleSchema,\n const Deps extends CrossModuleDeps,\n>(config: ModuleConfigWithDeps<M, Deps>): (name: string) => ModuleDef<M>;\n/** @internal Implementation overload — see public overloads above. */\nexport function createModuleFactory<const M extends ModuleSchema>(\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): (name: string) => ModuleDef<M> {\n // Pass config directly — createModule's implementation overload handles both types.\n // Do NOT cast to ModuleConfig<M> which would strip crossModuleDeps.\n return (name: string) => createModule(name, config);\n}\n","/**\n * Requirement Status Utilities\n *\n * Provides reactive tracking of requirement status for UI feedback.\n */\n\nimport type { Plugin, RequirementWithId } from \"../core/types.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Status of a requirement type */\nexport interface RequirementTypeStatus {\n /** Number of pending (unmet) requirements of this type */\n pending: number;\n /** Number of inflight (being resolved) requirements of this type */\n inflight: number;\n /** Number of failed requirements of this type */\n failed: number;\n /** Whether any requirements of this type are loading (pending or inflight) */\n isLoading: boolean;\n /** Whether any requirements of this type have failed */\n hasError: boolean;\n /** Last error for this type (if any) */\n lastError: Error | null;\n}\n\n/** Status tracking state */\ninterface StatusState {\n pending: Map<string, Set<string>>; // type -> set of requirement IDs\n inflight: Map<string, Set<string>>; // type -> set of requirement IDs\n failed: Map<string, Set<string>>; // type -> set of requirement IDs\n errors: Map<string, Error>; // type -> last error\n listeners: Set<() => void>;\n}\n\n// ============================================================================\n// Requirement Status Plugin\n// ============================================================================\n\n/**\n * Create a plugin that tracks requirement status for reactive UI updates.\n *\n * @example\n * ```typescript\n * import { createRequirementStatusPlugin } from '@directive-run/core';\n *\n * const statusPlugin = createRequirementStatusPlugin();\n *\n * const system = createSystem({\n * modules: [myModule],\n * plugins: [statusPlugin.plugin],\n * });\n *\n * // Get status for a requirement type\n * const status = statusPlugin.getStatus(\"FETCH_USER\");\n * console.log(status.isLoading, status.hasError);\n *\n * // Subscribe to status changes\n * const unsubscribe = statusPlugin.subscribe(() => {\n * console.log(\"Status changed:\", statusPlugin.getStatus(\"FETCH_USER\"));\n * });\n * ```\n */\nexport function createRequirementStatusPlugin(): {\n plugin: Plugin<never>;\n getStatus: (type: string) => RequirementTypeStatus;\n getAllStatus: () => Map<string, RequirementTypeStatus>;\n subscribe: (listener: () => void) => () => void;\n reset: () => void;\n} {\n const state: StatusState = {\n pending: new Map(),\n inflight: new Map(),\n failed: new Map(),\n errors: new Map(),\n listeners: new Set(),\n };\n\n /** Notify all listeners */\n function notify(): void {\n for (const listener of state.listeners) {\n listener();\n }\n }\n\n /** Get or create a set for a type in a map */\n function getOrCreateSet(\n map: Map<string, Set<string>>,\n type: string,\n ): Set<string> {\n let set = map.get(type);\n if (!set) {\n set = new Set();\n map.set(type, set);\n }\n return set;\n }\n\n /** Get status for a requirement type */\n function getStatus(type: string): RequirementTypeStatus {\n const pendingSet = state.pending.get(type) ?? new Set();\n const inflightSet = state.inflight.get(type) ?? new Set();\n const failedSet = state.failed.get(type) ?? new Set();\n const lastError = state.errors.get(type) ?? null;\n\n return {\n pending: pendingSet.size,\n inflight: inflightSet.size,\n failed: failedSet.size,\n isLoading: pendingSet.size > 0 || inflightSet.size > 0,\n hasError: failedSet.size > 0,\n lastError,\n };\n }\n\n /** Get status for all tracked types */\n function getAllStatus(): Map<string, RequirementTypeStatus> {\n const allTypes = new Set([\n ...state.pending.keys(),\n ...state.inflight.keys(),\n ...state.failed.keys(),\n ]);\n\n const result = new Map<string, RequirementTypeStatus>();\n for (const type of allTypes) {\n result.set(type, getStatus(type));\n }\n return result;\n }\n\n /** Subscribe to status changes */\n function subscribe(listener: () => void): () => void {\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n }\n\n /** Reset all status */\n function reset(): void {\n state.pending.clear();\n state.inflight.clear();\n state.failed.clear();\n state.errors.clear();\n notify();\n }\n\n const plugin: Plugin<never> = {\n name: \"requirement-status\",\n\n onRequirementCreated(req: RequirementWithId) {\n const type = req.requirement.type;\n getOrCreateSet(state.pending, type).add(req.id);\n // Clear from failed when a new requirement is created\n state.failed.get(type)?.delete(req.id);\n notify();\n },\n\n onResolverStart(_resolver: string, req: RequirementWithId) {\n const type = req.requirement.type;\n // Move from pending to inflight\n state.pending.get(type)?.delete(req.id);\n getOrCreateSet(state.inflight, type).add(req.id);\n notify();\n },\n\n onResolverComplete(_resolver: string, req: RequirementWithId) {\n const type = req.requirement.type;\n // Remove from inflight\n state.inflight.get(type)?.delete(req.id);\n state.pending.get(type)?.delete(req.id);\n notify();\n },\n\n onResolverError(_resolver: string, req: RequirementWithId, error: unknown) {\n const type = req.requirement.type;\n // Move from inflight to failed\n state.inflight.get(type)?.delete(req.id);\n getOrCreateSet(state.failed, type).add(req.id);\n state.errors.set(\n type,\n error instanceof Error ? error : new Error(String(error)),\n );\n notify();\n },\n\n onResolverCancel(_resolver: string, req: RequirementWithId) {\n const type = req.requirement.type;\n // Remove from all tracking\n state.pending.get(type)?.delete(req.id);\n state.inflight.get(type)?.delete(req.id);\n notify();\n },\n\n onRequirementMet(req: RequirementWithId) {\n const type = req.requirement.type;\n // Clean up when requirement is met\n state.pending.get(type)?.delete(req.id);\n state.inflight.get(type)?.delete(req.id);\n notify();\n },\n };\n\n return {\n plugin,\n getStatus,\n getAllStatus,\n subscribe,\n reset,\n };\n}\n\n// ============================================================================\n// React Hook Helper (for use with React adapter)\n// ============================================================================\n\n/**\n * Create a hook factory for requirement status.\n * This is designed to be used with React's useSyncExternalStore.\n *\n * @example\n * ```typescript\n * import { useSyncExternalStore } from 'react';\n * import { createRequirementStatusPlugin, createStatusHook } from '@directive-run/core';\n *\n * const statusPlugin = createRequirementStatusPlugin();\n * const useRequirementStatus = createStatusHook(statusPlugin);\n *\n * function MyComponent() {\n * const status = useRequirementStatus(\"FETCH_USER\");\n * if (status.isLoading) return <Spinner />;\n * if (status.hasError) return <Error error={status.lastError} />;\n * return <Content />;\n * }\n * ```\n */\nexport function createStatusHook(\n statusPlugin: ReturnType<typeof createRequirementStatusPlugin>,\n): (type: string) => RequirementTypeStatus {\n // This returns a function that can be used with useSyncExternalStore\n // The actual hook implementation would be in the React adapter\n return (type: string) => statusPlugin.getStatus(type);\n}\n","/**\n * System with Status Plugin Helper\n *\n * Convenience function for creating a system with status tracking enabled.\n */\n\nimport { createSystem } from \"../core/system.js\";\nimport type {\n ErrorBoundaryConfig,\n ModuleDef,\n ModuleSchema,\n Plugin,\n SingleModuleSystem,\n TraceOption,\n} from \"../core/types.js\";\nimport { createRequirementStatusPlugin } from \"./requirement-status.js\";\n\n/** Options for createSystemWithStatus */\nexport interface CreateSystemWithStatusOptions<M extends ModuleSchema> {\n /** The module to use for the system */\n module: ModuleDef<M>;\n /** Additional plugins to include alongside the status plugin */\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic contravariance issues\n plugins?: Plugin<any>[];\n /** Trace: per-run reconciliation changelog */\n trace?: TraceOption;\n /** Error boundary configuration */\n errorBoundary?: ErrorBoundaryConfig;\n /** Tick interval in milliseconds */\n tickMs?: number;\n /** Enable zero-config mode */\n zeroConfig?: boolean;\n /** Initial facts to set on the system */\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies by module\n initialFacts?: Record<string, any>;\n}\n\n/** Return type for createSystemWithStatus */\nexport interface SystemWithStatus<M extends ModuleSchema> {\n /**\n * The Directive system instance.\n * This is a SingleModuleSystem - use system.facts, system.dispatch(), etc.\n */\n system: SingleModuleSystem<M>;\n /** The status plugin for use with useRequirementStatus hooks */\n statusPlugin: ReturnType<typeof createRequirementStatusPlugin>;\n}\n\n/**\n * Create a Directive system with a status plugin pre-configured.\n *\n * This is a convenience wrapper around `createSystem` and `createRequirementStatusPlugin`\n * that handles the wiring automatically. The status plugin is added to the system's\n * plugins array so it receives lifecycle events.\n *\n * @param options - System configuration options\n * @returns An object containing both the system and the statusPlugin\n *\n * @example\n * ```tsx\n * import { createSystemWithStatus } from '@directive-run/core';\n * import { useRequirementStatus, useFact } from '@directive-run/react';\n *\n * // Simple setup - no provider needed\n * const { system, statusPlugin } = createSystemWithStatus({\n * module: myModule,\n * });\n * system.start();\n *\n * function App() {\n * const data = useFact(system, \"data\");\n * return <LoadingIndicator />;\n * }\n *\n * function LoadingIndicator() {\n * const status = useRequirementStatus(statusPlugin, \"FETCH_DATA\");\n * if (status.isLoading) return <Spinner />;\n * if (status.hasError) return <Error message={status.lastError?.message} />;\n * return <Content />;\n * }\n * ```\n */\nexport function createSystemWithStatus<M extends ModuleSchema>(\n options: CreateSystemWithStatusOptions<M>,\n): SystemWithStatus<M> {\n // Create the status plugin\n const statusPlugin = createRequirementStatusPlugin();\n\n // Add the plugin to the options\n const existingPlugins = options.plugins ?? [];\n\n // Create the system with the status plugin included\n // Use type assertion to bypass overload resolution issues\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const allPlugins = [...existingPlugins, statusPlugin.plugin] as Plugin<any>[];\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const system = createSystem({\n module: options.module,\n plugins: allPlugins,\n trace: options.trace,\n errorBoundary: options.errorBoundary,\n tickMs: options.tickMs,\n zeroConfig: options.zeroConfig,\n initialFacts: options.initialFacts,\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n } as any);\n\n return {\n // The system returned by createSystem with a single module is a SingleModuleSystem\n system: system as SingleModuleSystem<M>,\n statusPlugin,\n };\n}\n","/**\n * SignalClock — injectable clock source for declarative timers (RFC 0001).\n *\n * The clock interface decouples Directive's timer primitives from any\n * single time source. Production uses `realClock()`. Tests use\n * `virtualClock()` which advances synchronously via `clock.advanceBy()`.\n * Replay / dehydrate scenarios use a clock seeded from the recorded\n * stream.\n *\n * Auto-detection: `defaultClock()` returns `virtualClock()` when running\n * under Vitest (process.env.VITEST === 'true'), otherwise `realClock()`.\n * Consumers can pass an explicit clock to `createSystem({ clock })` to\n * override.\n *\n * @see ../../docs/rfcs/0001-t-timer.md\n */\n\n/**\n * Stable interface for any time source.\n */\nexport interface SignalClock {\n /** Current time, in milliseconds since the Unix epoch. */\n now(): number;\n /**\n * Schedule a callback to fire after `ms` milliseconds. Returns a\n * cancellation function. Implementations may queue callbacks or fire\n * them on a tick boundary; the only contract is \"fires no earlier\n * than `ms` from now.\"\n */\n setTimeout(cb: () => void, ms: number): () => void;\n /**\n * (Test-only.) Synchronously advance the clock by `ms` milliseconds,\n * firing all scheduled callbacks whose deadlines fall within the\n * advanced window. Real clocks throw if called.\n */\n advanceBy?(ms: number): void;\n}\n\n/**\n * Production clock — wraps `Date.now()` and `globalThis.setTimeout`.\n * No mocking, no virtualization.\n */\nexport function realClock(): SignalClock {\n return {\n now: () => Date.now(),\n setTimeout: (cb, ms) => {\n const handle = globalThis.setTimeout(cb, ms);\n return () => globalThis.clearTimeout(handle);\n },\n };\n}\n\n/**\n * Virtual clock — advances only when `advanceBy(ms)` is called. All\n * scheduled callbacks fire synchronously in order of their deadlines.\n *\n * Two scheduled callbacks at the same deadline fire in registration order.\n * Cancellation is O(1).\n */\nexport function virtualClock(initialMs = 0): SignalClock {\n let nowMs = initialMs;\n let nextId = 0;\n interface Scheduled {\n id: number;\n deadlineMs: number;\n cb: () => void;\n canceled: boolean;\n }\n const queue: Scheduled[] = [];\n\n return {\n now: () => nowMs,\n setTimeout: (cb, ms) => {\n const entry: Scheduled = {\n id: nextId++,\n deadlineMs: nowMs + ms,\n cb,\n canceled: false,\n };\n queue.push(entry);\n return () => {\n entry.canceled = true;\n };\n },\n advanceBy: (ms) => {\n const targetMs = nowMs + ms;\n // Fire all callbacks whose deadlines fall in [nowMs, targetMs].\n // Sort live entries by deadline + registration order so ties\n // resolve deterministically.\n while (true) {\n const ready = queue\n .filter((e) => !e.canceled && e.deadlineMs <= targetMs)\n .sort((a, b) =>\n a.deadlineMs !== b.deadlineMs\n ? a.deadlineMs - b.deadlineMs\n : a.id - b.id,\n );\n if (ready.length === 0) break;\n const next = ready[0]!;\n // Advance \"now\" monotonically — never let a callback that\n // schedules another callback in the past pull `nowMs`\n // backward. Without this clamp, `setTimeout(cb2, -5)` from\n // inside a callback would make `clock.now()` return a smaller\n // value mid-advance, breaking elapsedMs (negative results)\n // and replay determinism. (R1 sec C3.)\n nowMs = Math.max(nowMs, next.deadlineMs);\n next.canceled = true;\n next.cb();\n }\n // Final advance — even if no callbacks fired in [nowMs, targetMs],\n // wall clock still moves forward.\n nowMs = Math.max(nowMs, targetMs);\n },\n };\n}\n\n/**\n * Returns `realClock()` always.\n *\n * Earlier drafts auto-detected vitest (`process.env.VITEST === 'true'`)\n * and returned a `virtualClock()` in that environment. AE review\n * flagged this as a footgun: tests that legitimately need real time\n * (sleep-based debounce checks, real-`setTimeout`-bound integration\n * fixtures) silently received a virtual clock that never advanced\n * unless the test author called `advanceBy()`, producing apparent\n * deadlocks indistinguishable from genuine bugs. Auto-detection is\n * therefore opt-in.\n *\n * Use {@link virtualClock} explicitly in tests:\n *\n * ```ts\n * const clock = virtualClock(0);\n * const sys = createSystem({ module, clock });\n * clock.advanceBy(1_000);\n * ```\n */\nexport function defaultClock(): SignalClock {\n return realClock();\n}\n","/**\n * Timer fact — a runtime container that advances over time on a\n * SignalClock (RFC 0001 v0.1).\n *\n * Produced by `createTimerFact(clock, opts)`. Holds the durable state\n * (startedAtMs, pausedDurationMs, status) and exposes a control surface\n * (start, pause, resume, reset) plus reactive reads (elapsedMs,\n * remainingMs, status).\n *\n * v0.1 SCOPE: timer is a \"thick fact\" — a single object you store in a\n * regular Directive fact (e.g. `t.object<TimerFactState>()`). The\n * engine doesn't auto-tick it; the consumer is responsible for calling\n * `timer.tick()` when they want elapsedMs / remainingMs to update.\n * Typical wiring: a setInterval in the consumer that calls `timer.tick()`\n * and dispatches an event when status changes.\n *\n * v0.2 (deferred): true `t.timer({ms})` schema integration where the\n * engine subscribes to the clock and writes the fact deltas itself,\n * eliminating the consumer-side tick wiring.\n *\n * @see ../../docs/rfcs/0001-t-timer.md\n */\n\n// SignalClock is the canonical time source for timer ops; consumers\n// pass `clock.now()` into the helpers below. Re-exported by index.ts\n// alongside this module so they can `import { realClock, timerOps,\n// initialTimerState } from \"@directive-run/core\"` together.\n\n/**\n * Persistent timer state — JSON-roundtrippable, suitable for storing\n * inside a Directive fact.\n */\nexport interface TimerFactState {\n /** Unix-ms when the timer last started or resumed. null = not running. */\n startedAtMs: number | null;\n /** Total ms accumulated while paused. */\n pausedDurationMs: number;\n /** ms when the timer was paused, if currently paused. null otherwise. */\n pausedAtMs: number | null;\n /**\n * - 'idle': not yet started, or reset.\n * - 'running': currently counting.\n * - 'paused': paused; pausedAtMs is set.\n * - 'completed': hit the deadline (countdown mode only).\n */\n status: \"idle\" | \"running\" | \"paused\" | \"completed\";\n /** Number of times the timer has fired (repeat mode only). */\n repeats: number;\n}\n\nexport interface TimerFactOpts {\n /** Duration in ms. Countdown mode counts this down; up mode counts up to ∞. */\n ms: number;\n /**\n * - 'down' (default): counts down from `ms` to 0; status → 'completed' at 0.\n * - 'up': counts elapsed time; never completes.\n * - 'repeat': fires every `ms`; increments `repeats`; status stays 'running'.\n */\n mode?: \"down\" | \"up\" | \"repeat\";\n}\n\n/**\n * Initial state for a newly-created timer. Pass this to your Directive\n * `init()` to seed the fact.\n */\nexport function initialTimerState(): TimerFactState {\n return {\n startedAtMs: null,\n pausedDurationMs: 0,\n pausedAtMs: null,\n status: \"idle\",\n repeats: 0,\n };\n}\n\n/**\n * Compute elapsed ms for a given timer state at a given clock-now.\n * Pure function — no side effects, no reads beyond its inputs.\n *\n * @example\n * ```ts\n * const elapsed = elapsedMs(facts.countdown, clock.now());\n * if (elapsed >= 60_000) {\n * facts.countdown = { ...facts.countdown, status: 'completed' };\n * }\n * ```\n */\nexport function elapsedMs(state: TimerFactState, nowMs: number): number {\n if (state.startedAtMs === null) return 0;\n // Clamp at 0 — a clock step-back (NTP correction, virtual-clock\n // re-entrancy, replay seeded from older snapshot) would otherwise\n // produce negative elapsed values that:\n // - make tickTimer never report 'complete' (because `elapsed >= ms`\n // stays false past the deadline)\n // - make remainingMs report values > the configured ms total\n // - silently wrap into pausedDurationMs accumulation downstream\n // (R1 sec C4.)\n if (state.status === \"paused\" && state.pausedAtMs !== null) {\n return Math.max(\n 0,\n state.pausedAtMs - state.startedAtMs - state.pausedDurationMs,\n );\n }\n return Math.max(0, nowMs - state.startedAtMs - state.pausedDurationMs);\n}\n\n/**\n * Compute remaining ms for a countdown timer at a given clock-now.\n * Returns 0 if the timer has hit zero or hasn't started.\n */\nexport function remainingMs(\n state: TimerFactState,\n nowMs: number,\n totalMs: number,\n): number {\n return Math.max(0, totalMs - elapsedMs(state, nowMs));\n}\n\n/**\n * Transition: start an idle (or reset) timer.\n *\n * No-op if already running, paused, or completed (use `reset()` first).\n */\nexport function startTimer(\n state: TimerFactState,\n nowMs: number,\n): TimerFactState {\n if (state.status === \"running\") return state;\n if (state.status === \"paused\") return state;\n return {\n ...state,\n startedAtMs: nowMs,\n pausedDurationMs: 0,\n pausedAtMs: null,\n status: \"running\",\n repeats: 0,\n };\n}\n\n/**\n * Transition: pause a running timer. Records the pause moment so a\n * later `resumeTimer()` can correctly extend pausedDurationMs.\n *\n * No-op if not running.\n */\nexport function pauseTimer(\n state: TimerFactState,\n nowMs: number,\n): TimerFactState {\n if (state.status !== \"running\") return state;\n return { ...state, pausedAtMs: nowMs, status: \"paused\" };\n}\n\n/**\n * Transition: resume a paused timer. Adds the time spent paused into\n * `pausedDurationMs` so elapsed/remaining math stays correct.\n *\n * No-op if not paused.\n */\nexport function resumeTimer(\n state: TimerFactState,\n nowMs: number,\n): TimerFactState {\n if (state.status !== \"paused\") return state;\n if (state.pausedAtMs === null) return state;\n // Clamp pausedFor at 0 — clock step-back between pause and resume\n // would otherwise produce a negative pausedDurationMs accumulation,\n // which propagates into elapsedMs (returns inflated values), which\n // prematurely completes countdowns. (R1 sec M1.)\n const pausedFor = Math.max(0, nowMs - state.pausedAtMs);\n return {\n ...state,\n pausedDurationMs: state.pausedDurationMs + pausedFor,\n pausedAtMs: null,\n status: \"running\",\n };\n}\n\n/**\n * Transition: reset a timer to idle. Loses all elapsed time + repeat\n * count. Equivalent to `initialTimerState()`.\n */\nexport function resetTimer(): TimerFactState {\n return initialTimerState();\n}\n\n/**\n * Transition: mark the timer completed. For countdown mode when\n * elapsed reaches `ms`; for repeat mode when consumer wants to halt.\n */\nexport function completeTimer(state: TimerFactState): TimerFactState {\n return { ...state, status: \"completed\" };\n}\n\n/**\n * Transition: register a repeat firing. Increments `repeats` and\n * advances `startedAtMs` by `ms` so the next interval lands at the\n * intended boundary (drift-free).\n */\nexport function registerRepeat(\n state: TimerFactState,\n ms: number,\n): TimerFactState {\n if (state.startedAtMs === null) return state;\n // Defensible-illegal: registerRepeat from a paused state would\n // otherwise advance startedAtMs while leaving status === 'paused',\n // producing an inconsistent state (logically running by clock math\n // but reads as paused). No-op instead. (R2 sec m-R2-2.)\n if (state.status === \"paused\") return state;\n // Reset pausedDurationMs on each repeat so accumulated pause time\n // from prior intervals does not double-count into the next\n // interval's elapsed math. Without this reset, every repeat after a\n // pause would arithmetic-drift the next deadline by the cumulative\n // pause window. (R1 sec M9.)\n return {\n ...state,\n startedAtMs: state.startedAtMs + ms,\n pausedDurationMs: 0,\n pausedAtMs: null,\n repeats: state.repeats + 1,\n };\n}\n\n/**\n * Higher-level helper: given a timer state, total ms, and the current\n * clock, return whether the timer should transition to 'completed' (for\n * countdown mode) or fire a repeat (for repeat mode).\n *\n * Pure — does not mutate state. Returns a structured signal the consumer\n * applies via `completeTimer` / `registerRepeat`.\n */\nexport function tickTimer(\n state: TimerFactState,\n nowMs: number,\n opts: TimerFactOpts,\n): { kind: \"no-op\" } | { kind: \"complete\" } | { kind: \"repeat\" } {\n if (state.status !== \"running\") return { kind: \"no-op\" };\n const elapsed = elapsedMs(state, nowMs);\n\n if (opts.mode === \"up\") {\n // 'up' never completes; consumer reads elapsedMs directly.\n return { kind: \"no-op\" };\n }\n\n if (opts.mode === \"repeat\") {\n if (elapsed >= opts.ms) return { kind: \"repeat\" };\n return { kind: \"no-op\" };\n }\n\n // 'down' (default)\n if (elapsed >= opts.ms) return { kind: \"complete\" };\n return { kind: \"no-op\" };\n}\n\n/**\n * Bundle of helpers for one timer in one module — convenience for\n * callers who want a single import. Each method takes the current\n * state and clock-now, returns the next state. No mutation.\n *\n * @example\n * ```ts\n * import {\n * createSystem,\n * t,\n * realClock,\n * timerOps,\n * initialTimerState,\n * type TimerFactState,\n * } from '@directive-run/core';\n *\n * const clock = realClock();\n * const ops = timerOps({ ms: 60_000, mode: 'down' });\n *\n * createModule('countdown', {\n * schema: { facts: { state: t.object<TimerFactState>() }, events: { START: {} } },\n * init: (f) => { f.state = initialTimerState(); },\n * events: {\n * START: (f) => { f.state = ops.start(f.state, clock.now()); },\n * },\n * });\n *\n * // In the consumer (React, Node, edge), tick periodically:\n * setInterval(() => {\n * const signal = ops.tick(f.state, clock.now());\n * if (signal.kind === 'complete') {\n * sys.dispatch({ type: 'TIMEOUT' });\n * }\n * }, 100);\n * ```\n */\nexport function timerOps(opts: TimerFactOpts) {\n return {\n initial: initialTimerState,\n start: startTimer,\n pause: pauseTimer,\n resume: resumeTimer,\n reset: resetTimer,\n complete: completeTimer,\n registerRepeat: (state: TimerFactState) => registerRepeat(state, opts.ms),\n tick: (state: TimerFactState, nowMs: number) =>\n tickTimer(state, nowMs, opts),\n elapsedMs,\n remainingMs: (state: TimerFactState, nowMs: number) =>\n remainingMs(state, nowMs, opts.ms),\n };\n}\n","/**\n * @directive-run/core\n *\n * Constraint-driven runtime for TypeScript.\n *\n * Also available:\n * - `@directive-run/core/internals` – Manager factories, engine, tracking, and internal types\n * - `@directive-run/core/plugins` – Logging, devtools, persistence, observability, circuit breaker\n * - `@directive-run/core/testing` – Mock resolvers, fake timers, assertion helpers\n * - `@directive-run/core/migration` – Redux/Zustand/XState migration scaffolding\n * - `@directive-run/core/adapter-utils` – Shared framework adapter utilities\n * - `@directive-run/core/worker` – Web Worker support\n *\n * @packageDocumentation\n */\n\n// ============================================================================\n// Core Types — what 90% of users need\n// ============================================================================\n\nexport type {\n // Schema\n Schema,\n SchemaType,\n InferSchemaType,\n // Module Schema (consolidated)\n ModuleSchema,\n InferFacts,\n InferDerivations,\n InferSelectorState,\n InferEvents,\n InferRequirements,\n InferRequirementTypes,\n // Facts\n Facts,\n FactsSnapshot,\n // Requirements\n Requirement,\n RequirementWithId,\n // Constraints + Resolvers (config types)\n RetryPolicy,\n BatchConfig,\n // Plugins\n Plugin,\n Snapshot,\n // Errors\n ErrorBoundaryConfig,\n // Module\n ModuleDef,\n ModuleHooks,\n // System\n System,\n SystemConfig,\n SystemInspection,\n SystemSnapshot,\n MetaAccessor,\n MetaMatch,\n ObservationEvent,\n // Trace\n TraceEntry,\n TraceOption,\n // History\n HistoryOption,\n HistoryAPI,\n HistoryState,\n // Composition (Namespaced Multi-Module)\n ModulesMap,\n NamespacedSystem,\n CreateSystemOptionsNamed,\n // Single Module\n CreateSystemOptionsSingle,\n SingleModuleSystem,\n // Type Guards\n SystemMode,\n AnySystem,\n // Cross-Module Dependencies\n CrossModuleDeps,\n // Dynamic Definitions\n DynamicConstraintDef,\n DynamicEffectDef,\n DynamicResolverDef,\n // Definition Meta\n DefinitionMeta,\n DerivationDefWithMeta,\n // Data-configuration predicates and templates\n FactPredicate,\n FactTemplate,\n KeySelector,\n PatchSpec,\n PayloadRef,\n PatchValue,\n OperatorObject,\n PredicateObject,\n PredicateClause,\n PredicateCombinator,\n PredicateCombinatorKey,\n PredicateOp,\n ClauseResult,\n // Distributable Snapshots\n DistributableSnapshot,\n DistributableSnapshotOptions,\n} from \"./core/types.js\";\n\n// Predicate / template runtime\nexport {\n applyPatch,\n memoizePredicate,\n evaluateKeySelector,\n evaluatePredicate,\n evaluatePredicateExplained,\n evaluateTemplate,\n extractDeps,\n extractTemplateKeys,\n isPredicate,\n isTemplate,\n validatePredicate,\n} from \"./core/predicate.js\";\n\n// Predicate backtest — rule-change impact replay\nexport {\n MAX_REPLAY_FRAMES,\n framesFromHistory,\n framesFromSnapshots,\n replayUnder,\n toReplayFrames,\n} from \"./core/replay-under.js\";\nexport type {\n PredicateBacktestReport,\n ReplayDiffSample,\n ReplayFrame,\n ReplayUnderOptions,\n} from \"./core/replay-under.js\";\n\n// Parameter sweep — grid-search predicate templates against recorded history\nexport { MAX_SWEEP_POINTS, sweepUnder } from \"./core/sweep-under.js\";\nexport type {\n SweepHole,\n SweepPoint,\n SweepReport,\n SweepUnderOptions,\n} from \"./core/sweep-under.js\";\n\n// Rules diff — structural diff of constraint whenSpec across two snapshots\nexport { diffClauses, diffRules, flattenPredicate, toRulesMap } from \"./core/rules-diff.js\";\nexport type {\n Change,\n ChangeKind,\n ConstraintDiff,\n ConstraintStatus,\n DiffRulesOptions,\n LeafClause,\n RulesDiffReport,\n RulesMapInput,\n} from \"./core/rules-diff.js\";\n\n// Predicate codegen — one predicate, run on client AND server\nexport { predicateToSQL, predicateToWhere } from \"./core/predicate-to-sql.js\";\nexport type {\n PredicateToSqlOptions,\n PredicateToSqlResult,\n} from \"./core/predicate-to-sql.js\";\nexport { predicateToMongo } from \"./core/predicate-to-mongo.js\";\nexport type { PredicateToMongoOptions } from \"./core/predicate-to-mongo.js\";\nexport { predicateToPostgrest } from \"./core/predicate-to-pgrest.js\";\nexport type { PredicateToPostgrestOptions } from \"./core/predicate-to-pgrest.js\";\n\n// ============================================================================\n// Core Classes\n// ============================================================================\n\nexport { DirectiveError } from \"./core/types.js\";\n\n// ============================================================================\n// Schema Type Builders\n// ============================================================================\n\n/**\n * Schema type builders for defining fact types.\n *\n * @example\n * ```ts\n * import { t } from '@directive-run/core';\n *\n * const schema = {\n * facts: {\n * count: t.number().min(0).default(0),\n * name: t.string(),\n * status: t.enum(\"idle\", \"loading\", \"error\"),\n * user: t.object<User>().nullable(),\n * },\n * derivations: { doubled: t.number() },\n * events: { increment: {} },\n * requirements: { FETCH_USER: {} },\n * };\n * ```\n */\nexport {\n t,\n type Branded,\n type ExtendedSchemaType,\n type ChainableSchemaType,\n} from \"./core/schema-builders.js\";\n\n// ============================================================================\n// Module & System\n// ============================================================================\n\nexport {\n createModule,\n createModuleFactory,\n type ModuleConfig,\n type ModuleConfigWithDeps,\n} from \"./core/module.js\";\nexport { createSystem } from \"./core/system.js\";\nexport { createSystemWithStatus } from \"./utils/system-with-status.js\";\n\n// Helper factory functions for typed constraint/resolver definitions\nexport {\n typedConstraint,\n typedResolver,\n} from \"./core/types.js\";\n\n// ============================================================================\n// Requirements Helpers\n// ============================================================================\n\nexport {\n req,\n forType,\n isRequirementType,\n generateRequirementId,\n RequirementSet,\n} from \"./core/requirements.js\";\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nexport {\n isSingleModuleSystem,\n isNamespacedSystem,\n} from \"./core/types/composition.js\";\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/**\n * Backoff strategy constants for retry policies.\n *\n * @example\n * ```ts\n * import { Backoff } from '@directive-run/core';\n *\n * retry: { attempts: 3, backoff: Backoff.Exponential, initialDelay: 100 }\n * ```\n */\nexport const Backoff = {\n /** No delay between retries */\n None: \"none\",\n /** Linear delay increase (initialDelay * attempt) */\n Linear: \"linear\",\n /** Exponential delay increase (initialDelay * 2^attempt) */\n Exponential: \"exponential\",\n} as const;\n\n// ============================================================================\n// Requirement Status Utilities\n// ============================================================================\n\nexport {\n createRequirementStatusPlugin,\n createStatusHook,\n type RequirementTypeStatus,\n} from \"./utils/requirement-status.js\";\n\n// ============================================================================\n// Snapshot Utilities\n// ============================================================================\n\nexport {\n shallowEqual,\n isSnapshotExpired,\n validateSnapshot,\n diffSnapshots,\n signSnapshot,\n verifySnapshotSignature,\n isSignedSnapshot,\n type DistributableSnapshotLike,\n type SnapshotDiff,\n type SnapshotDiffEntry,\n type SignedSnapshot,\n} from \"./utils/utils.js\";\n\n// ============================================================================\n// Clock + Timer (RFC 0001 v0.1)\n// ============================================================================\n\nexport {\n type SignalClock,\n realClock,\n virtualClock,\n defaultClock,\n} from \"./core/clock.js\";\n\nexport {\n type TimerFactState,\n type TimerFactOpts,\n initialTimerState,\n elapsedMs,\n remainingMs,\n startTimer,\n pauseTimer,\n resumeTimer,\n resetTimer,\n completeTimer,\n registerRepeat,\n tickTimer,\n timerOps,\n} from \"./core/timer.js\";\n\n// ============================================================================\n// Lower-level APIs — use \"@directive-run/core/internals\" for these\n// ============================================================================\n// Manager factories, engine, tracking, and internal types are available at:\n// import { createEngine, createFacts, withTracking } from \"@directive-run/core/internals\"\n//\n// Internal types (FactsStore, FactChange, DerivationState, ConstraintState,\n// DerivationsDef, ConstraintsDef, ResolversDef, EventsDef, ReconcileResult,\n// RecoveryStrategy, ErrorSource, etc.) are also in internals.\n\n// Migration utilities available via \"@directive-run/core/migration\" subpath export.\n"]}
1
+ {"version":3,"sources":["../src/core/replay-under.ts","../src/core/sweep-under.ts","../src/core/rules-diff.ts","../src/core/predict.ts","../src/core/doctor.ts","../src/core/predicate-to-sql.ts","../src/core/predicate-to-mongo.ts","../src/core/predicate-to-pgrest.ts","../src/core/schema-builders.ts","../src/core/module.ts","../src/utils/requirement-status.ts","../src/utils/system-with-status.ts","../src/core/clock.ts","../src/core/timer.ts","../src/index.ts"],"names":["MAX_REPLAY_FRAMES","validateReplaySpec","spec","which","validatePredicate","err","message","isPredicate","preview","unknownOp","walkPredicate","_factPath","op","PREDICATE_OPERATORS","key","PREDICATE_COMBINATORS","toReplayFrames","raw","framesFromHistory","list","entry","index","frame","out","historyExport","parsed","framesFromSnapshots","exportObj","snapshots","i","s","replayUnder","options","frames","original","proposed","entityKey","requested","maxSamples","originalMatched","proposedMatched","newMatchCount","lostMatchCount","unchanged","newMatches","lostMatches","originalEntities","proposedEntities","prevFacts","facts","originalBit","evaluatePredicate","proposedBit","buildSample","report","sample","evaluatePredicateExplained","MAX_SWEEP_POINTS","MAX_SWEEP_EVALUATIONS","isHole","v","substitute","template","values","path","depth","MAX_PREDICATE_DEPTH","name","k","cartesian","keys","sweep","head","rest","headValues","tail","gridSize","size","arr","sweepUnder","objective","r","total","evaluations","warnedObjective","safeObjective","baselineReport","baseline","points","bestIndex","bestScore","score","best","toRulesMap","inner","e","KNOWN_OPS","COMBINATORS","isPlainObject","isOperatorObject","sawKnown","flattenPredicate","pathPrefix","clause","c","child","value","operand","isNumeric","directionFor","before","after","widthBefore","widthAfter","diffRules","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","fmt","suggestionFor","expected","actual","collectFailedLeaves","predict","predicate","prev","whenExplain","wouldFire","missingChanges","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","IDENT_RE","assertIdentifier","kind","assertAllowed","allowed","validateSelect","select","col","nextParam","ctx","renderOp","column","escapeLike","operator","assertNoSiblingKeys","combinator","sibs","buildWhere","parts","DEFAULT_PLACEHOLDER","predicateToSQL","table","allowedKeys","placeholder","projection","where","predicateToWhere","escapeRegex","FIELD_RE","FIELD_DOTTED_RE","assertFieldName","opts","field","translateOp","buildQuery","obj","conflicts","translated","andClauses","merged","predicateToMongo","assertColumn","encodeValue","encodeList","escapeLikeOperand","colClause","opAndValue","groupClause","logical","renderColumnOps","atTop","lo","hi","build","encodeClause","eq","predicateToPostgrest","mode","createSchemaType","validators","typeName","defaultValue","transform","description","refinements","meta","fn","createChainableType","fieldMeta","intermediate","desc","newRefinements","m","unionImpl","types","typeNames","schemaType","t","createChainableString","fm","n","regex","createChainableNumber","createChainableArray","elementType","indexRef","chainable","ref","et","newRef","validator","createChainableObject","shapeSchema","schemaT","dev_true_default","valueSet","innerType","innerTypeName","valueType","valueTypeName","val","uuidRegex","emailRegex","validateModuleId","validateKeyAlignment","implKeys","schemaKeys","implLabel","schemaLabel","missingImplMessage","validateSnapshotEvents","snapshotEvents","schemaEvents","schemaEventKeys","eventName","validateResolverRequirements","resolvers","requirements","requirementTypes","resolverName","resolver","resolverDef","validatePivotNameConflicts","config","factKeys","reserved","deps","depName","validateOwnsKeys","cid","constraint","owns","BLOCKED_PROPS","validateModuleConfig","createModule","crossModuleDeps","createModuleFactory","createRequirementStatusPlugin","state","notify","listener","getOrCreateSet","map","type","set","getStatus","pendingSet","inflightSet","failedSet","lastError","getAllStatus","allTypes","result","subscribe","reset","req","_resolver","error","createStatusHook","statusPlugin","createSystemWithStatus","allPlugins","createSystem","realClock","cb","ms","handle","virtualClock","initialMs","nowMs","nextId","queue","targetMs","ready","next","defaultClock","initialTimerState","elapsedMs","remainingMs","totalMs","startTimer","pauseTimer","resumeTimer","pausedFor","resetTimer","completeTimer","registerRepeat","tickTimer","elapsed","timerOps","Backoff"],"mappings":"2QAoCO,IAAMA,CAAAA,CAAoB,IAsFjC,SAASC,EAAAA,CACPC,CAAAA,CACAC,CAAAA,CACM,CACN,GAAI,CACFC,mBAAAA,CAAkBF,CAAI,EACxB,CAAA,MAASG,EAAK,CACZ,IAAMC,CAAAA,CAAUD,CAAAA,YAAe,KAAA,CAAQA,CAAAA,CAAI,OAAA,CAAU,MAAA,CAAOA,CAAG,CAAA,CAE/D,MAAM,IAAI,KAAA,CACR,CAAA,6BAAA,EAAgCF,CAAK,CAAA,6BAAA,EAA2BG,CAAO,CAAA,CACzE,CACF,CAEA,GAAI,CAACC,mBAAAA,CAAYL,CAAI,CAAA,CAAG,CACtB,IAAMM,CAAAA,CACJN,CAAAA,GAAS,MAAQ,OAAOA,CAAAA,EAAS,QAAA,CAC7B,CAAA,EAAG,OAAOA,CAAI,CAAA,QAAA,EAAM,IAAA,CAAK,SAAA,CAAUA,CAAI,CAAC,CAAA,CAAA,CACxC,IAAA,CAAK,SAAA,CAAUA,CAAI,CAAA,CAAE,KAAA,CAAM,CAAA,CAAG,EAAE,CAAA,CAEtC,MAAM,IAAI,KAAA,CACR,CAAA,6BAAA,EAAgCC,CAAK,CAAA,6CAAA,EAAgDK,CAAO,CAAA,CAAA,CAC9F,CACF,CAKA,IAAIC,CAAAA,CAsBJ,GArBAC,mBAAAA,CAAcR,CAAAA,CAAM,CAClB,QAAA,CAASS,CAAAA,CAAWC,CAAAA,CAAI,CAEpBH,CAAAA,GAAc,MAAA,EACdG,CAAAA,CAAG,UAAA,CAAW,GAAG,CAAA,EACjB,CAACC,mBAAAA,CAAoB,GAAA,CAAID,CAAE,CAAA,GAE3BH,CAAAA,CAAYG,CAAAA,EAEhB,CAAA,CACA,gBAAA,CAAiBE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A,CAAO3G,CAAAA,CAAK,EAAE,CAAA,CACxE,IAAA,CAAM,CAAC2G,EAAuB+B,CAAAA,GAC5BkB,EAAAA,CAAUjD,CAAAA,CAAO+B,CAAAA,CAAO1I,CAAI,CAAA,CAC9B,SAAA,CAAAkJ,CAAAA,CACA,YAAa,CAACvC,CAAAA,CAAuB+B,CAAAA,GACnCS,EAAAA,CAAYxC,CAAAA,CAAO+B,CAAAA,CAAO1I,CAAAA,CAAK,EAAE,CACrC,CACF,CCNO,IAAM+J,EAAAA,CAAU,CAErB,IAAA,CAAM,MAAA,CAEN,MAAA,CAAQ,QAAA,CAER,YAAa,aACf","file":"index.cjs","sourcesContent":["/**\n * Predicate backtest — rule-change impact.\n *\n * Given a recorded sequence of fact-state frames and a proposed replacement\n * for a constraint's `when` predicate, re-score the frames against BOTH the\n * original and the proposed predicate and produce a backtest report: how\n * many frames each matched, plus the per-frame diff (frames that newly\n * match / no longer match). It answers \"how many recorded frames would the\n * proposed rule have matched differently\" against real recorded history.\n *\n * This is a *static* backtest, not a behavioral simulation — the engine is\n * not re-run. Recorded frames are re-scored against a new predicate; the\n * resulting requirements, resolvers, and downstream fact changes are NOT\n * modeled. Treat the numbers as a divergence scan, not a forecast.\n *\n * Pure module — imports only the predicate runtime. No engine, store, or\n * tracking dependency. Replay walks frames in order; for `$changed`-style\n * predicates each frame is evaluated against the previous frame's facts.\n */\n\nimport {\n evaluatePredicate,\n evaluatePredicateExplained,\n isPredicate,\n validatePredicate,\n walkPredicate,\n} from \"./predicate.js\";\nimport type { ClauseResult, FactPredicate } from \"./types/predicate.js\";\nimport { PREDICATE_COMBINATORS, PREDICATE_OPERATORS } from \"./types/predicate.js\";\n\n/**\n * Upper bound on the number of frames a single {@link replayUnder} call will\n * process. A history file is held entirely in memory; an unbounded array is a\n * denial-of-service surface. A history larger than this should be split or\n * down-sampled before replay.\n */\nexport const MAX_REPLAY_FRAMES = 1_000_000;\n\n/** One recorded fact-state frame. */\nexport interface ReplayFrame<F = Record<string, unknown>> {\n /** Stable identifier — a snapshot id, an index, a session key. */\n id: string | number;\n /** Optional wall-clock time (ms epoch). */\n timestamp?: number;\n /** The fact state at this frame. */\n facts: F;\n}\n\nexport interface ReplayUnderOptions<F = Record<string, unknown>> {\n /** Recorded frames, chronological order. */\n frames: readonly ReplayFrame<F>[];\n /** The constraint's current `when` predicate (the baseline). */\n original: FactPredicate<F>;\n /** The proposed replacement `when` predicate. */\n proposed: FactPredicate<F>;\n /** Max diff samples to attach per bucket (default 20). */\n maxSamples?: number;\n /**\n * A fact key identifying the entity a frame belongs to (e.g. `\"userId\"`,\n * `\"sessionId\"`). When set, the report also reports distinct-entity counts\n * — how many unique entities matched, not just how many frames. Without it\n * the unit is frames: one fact snapshot, not one user or session.\n */\n entityKey?: string;\n}\n\n/** A frame where the original and proposed predicate disagree. */\nexport interface ReplayDiffSample {\n frameId: string | number;\n timestamp?: number;\n /** The fact state at this frame. */\n facts: Record<string, unknown>;\n /** Per-clause breakdown under the original predicate. */\n originalExplain: ClauseResult[];\n /** Per-clause breakdown under the proposed predicate. */\n proposedExplain: ClauseResult[];\n}\n\n/**\n * The outcome of replaying a recorded history under two predicates — a\n * static backtest of a proposed rule change, not a behavioral simulation.\n */\nexport interface PredicateBacktestReport {\n /** Total frames evaluated. */\n framesEvaluated: number;\n /**\n * Frames where the original predicate matched (was true). `matchedEntities`\n * is the count of distinct `entityKey` values among matched frames — only\n * populated when {@link ReplayUnderOptions.entityKey} was supplied.\n */\n original: { matched: number; matchedEntities?: number };\n /** Frames where the proposed predicate matched. */\n proposed: { matched: number; matchedEntities?: number };\n /** proposed.matched - original.matched. */\n delta: number;\n /** Total count of frames that newly match (original false -> proposed true). */\n newMatchCount: number;\n /** Total count of frames that no longer match (original true -> proposed false). */\n lostMatchCount: number;\n /** Frames where original and proposed agree. */\n unchanged: number;\n /** Sampled new-match frames (capped at maxSamples), with clause explain. */\n newMatches: ReplayDiffSample[];\n /** Sampled lost-match frames (capped at maxSamples), with clause explain. */\n lostMatches: ReplayDiffSample[];\n}\n\n/**\n * Validate one predicate spec for {@link replayUnder}, re-throwing any failure\n * with a message that names which spec (`original` / `proposed`) was bad.\n *\n * Three checks run, all up front so a malformed spec never reaches the\n * per-frame loop (where {@link evaluatePredicate} would throw a raw error on,\n * say, a `$matches` operand that is not a RegExp):\n *\n * 1. {@link validatePredicate} — JSON-unrehydratable operands (a `$matches`\n * operand that is not a RegExp, a `bigint`, a `Set`/`Map`).\n * 2. {@link isPredicate} — the spec is structurally a FactPredicate. An\n * empty object `{}` is a valid (always-true) predicate and is allowed.\n * 3. Unknown `$`-operators — a single walk surfaces any `$frobnicate`-style\n * typo as one clear error instead of a per-call dev-warn.\n */\nfunction validateReplaySpec(\n spec: unknown,\n which: \"original\" | \"proposed\",\n): void {\n try {\n validatePredicate(spec);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n\n throw new Error(\n `[Directive] replayUnder: the ${which} predicate is invalid — ${message}`,\n );\n }\n\n if (!isPredicate(spec)) {\n const preview =\n spec === null || typeof spec !== \"object\"\n ? `${typeof spec} — ${JSON.stringify(spec)}`\n : JSON.stringify(spec).slice(0, 80);\n\n throw new Error(\n `[Directive] replayUnder: the ${which} predicate is not a valid FactPredicate (got ${preview})`,\n );\n }\n\n // Surface an unknown `$`-operator (`$frobnicate`) as one clear error.\n // `walkPredicate` reports a `$`-key at fact position via `strayOperatorKey`\n // and an operator clause via `operator`; check both against the known sets.\n let unknownOp: string | undefined;\n walkPredicate(spec, {\n operator(_factPath, op) {\n if (\n unknownOp === undefined &&\n op.startsWith(\"$\") &&\n !PREDICATE_OPERATORS.has(op)\n ) {\n unknownOp = op;\n }\n },\n strayOperatorKey(key) {\n if (\n unknownOp === undefined &&\n !PREDICATE_OPERATORS.has(key) &&\n !PREDICATE_COMBINATORS.has(key)\n ) {\n unknownOp = key;\n }\n },\n });\n\n if (unknownOp !== undefined) {\n throw new Error(\n `[Directive] replayUnder: the ${which} predicate uses an unknown operator \"${unknownOp}\" — known operators: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n}\n\n/**\n * Normalize a parsed-from-JSON history value into a `ReplayFrame[]`.\n *\n * Accepts the three documented history shapes:\n *\n * 1. A bare array of frames: `[{ id, timestamp?, facts }, ...]`\n * 2. An object wrapping them: `{ frames: [{ id, ..., facts }, ...] }`\n * 3. A bare array of fact objects: `[{ phase: \"red\", ... }, ...]`\n * — each element is wrapped as a frame.\n *\n * Frame ids are kept unambiguous: a frame that supplies its own `id` keeps\n * it; a frame missing an `id` (and every bare-fact frame) gets an\n * **index-derived** id prefixed with `#` (`\"#0\"`, `\"#1\"`, …) so a fallback\n * id can never collide with an explicit numeric or string id in a mixed\n * history. This is a pure helper — it **throws** a clear `Error` on bad\n * input and never calls `process.exit`, so library users can catch it.\n *\n * @example\n * ```ts\n * toReplayFrames([{ id: \"s1\", facts: { phase: \"red\" } }]);\n * // → [{ id: \"s1\", facts: { phase: \"red\" } }]\n * toReplayFrames([{ phase: \"red\" }, { phase: \"green\" }]);\n * // → [{ id: \"#0\", facts: { phase: \"red\" } }, { id: \"#1\", facts: { phase: \"green\" } }]\n * ```\n */\nexport function toReplayFrames(raw: unknown): ReplayFrame[] {\n // A history-manager export ({ version, snapshots, currentIndex }) is a\n // valid input shape — route it through framesFromHistory so the CLI and\n // the library accept the same files.\n if (\n raw &&\n typeof raw === \"object\" &&\n !Array.isArray(raw) &&\n Array.isArray((raw as { snapshots?: unknown }).snapshots)\n ) {\n return framesFromHistory(raw);\n }\n\n const list: unknown[] | null = Array.isArray(raw)\n ? raw\n : raw &&\n typeof raw === \"object\" &&\n Array.isArray((raw as { frames?: unknown }).frames)\n ? (raw as { frames: unknown[] }).frames\n : null;\n\n if (!list) {\n throw new Error(\n \"[Directive] toReplayFrames: history must be a JSON array of frames, an object with a `frames` array, or a history export with a `snapshots` array\",\n );\n }\n\n // Enforce the frame cap on `length` before `.map()` materializes a second\n // array — the cap must bound memory, not just the evaluation loop.\n if (list.length > MAX_REPLAY_FRAMES) {\n throw new Error(\n `[Directive] toReplayFrames: history has ${list.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${MAX_REPLAY_FRAMES}) — split or down-sample the history`,\n );\n }\n\n return list.map((entry, index) => {\n if (entry && typeof entry === \"object\" && \"facts\" in entry) {\n const frame = entry as {\n id?: string | number;\n timestamp?: number;\n facts: unknown;\n };\n // An explicit id is used verbatim; a missing id falls back to a\n // `#`-prefixed index so it cannot collide with an explicit id.\n const out: ReplayFrame = {\n id: frame.id ?? `#${index}`,\n facts: (frame.facts ?? {}) as Record<string, unknown>,\n };\n if (typeof frame.timestamp === \"number\") {\n out.timestamp = frame.timestamp;\n }\n\n return out;\n }\n\n // A bare fact object — wrap it, keyed by `#`-prefixed index.\n return { id: `#${index}`, facts: (entry ?? {}) as Record<string, unknown> };\n });\n}\n\n/**\n * Convert a history-manager export (the JSON produced by\n * `system.history.export()`) into a `ReplayFrame[]` ready for\n * {@link replayUnder}.\n *\n * The history manager records a ring buffer of `{ id, timestamp, facts,\n * trigger }` snapshots; `export()` wraps them as `{ version, snapshots,\n * currentIndex }`. Each snapshot's `facts` is the fact state at that point,\n * so the snapshot sequence is exactly a frame stream.\n *\n * Accepts either the parsed export object, the raw JSON string, or a bare\n * array of snapshots. Throws a clear `Error` on bad input.\n *\n * @example\n * ```ts\n * const frames = framesFromHistory(system.history.export());\n * const report = replayUnder({ frames, original, proposed });\n * ```\n */\nexport function framesFromHistory(historyExport: unknown): ReplayFrame[] {\n const parsed =\n typeof historyExport === \"string\"\n ? (JSON.parse(historyExport) as unknown)\n : historyExport;\n\n // A bare snapshot array is accepted directly.\n if (Array.isArray(parsed)) {\n return framesFromSnapshots(parsed);\n }\n\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(\n \"[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())\",\n );\n }\n\n const exportObj = parsed as { version?: unknown; snapshots?: unknown };\n\n // Mirror history.ts import(): only version 1 is understood. A bump in the\n // export format must fail loud here, not silently yield wrong frames.\n if (exportObj.version !== undefined && exportObj.version !== 1) {\n throw new Error(\n `[Directive] framesFromHistory: unsupported history export version ${JSON.stringify(exportObj.version)} — expected 1`,\n );\n }\n\n if (!Array.isArray(exportObj.snapshots)) {\n throw new Error(\n \"[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())\",\n );\n }\n\n return framesFromSnapshots(exportObj.snapshots);\n}\n\n/**\n * Convert an array of `{ id, timestamp?, facts }` snapshots — e.g. the\n * `snapshots` field of a history export, or an array assembled by pushing\n * `system.getSnapshot()` on each reconcile — into a `ReplayFrame[]`.\n *\n * Throws a clear `Error` if the argument is not an array. Each snapshot is\n * normalized through the same {@link toReplayFrames} id logic.\n *\n * @example\n * ```ts\n * const snapshots: typeof history[] = [];\n * system.observe(() => snapshots.push(system.getSnapshot()));\n * // ...later\n * const frames = framesFromSnapshots(snapshots);\n * ```\n */\nexport function framesFromSnapshots(snapshots: unknown): ReplayFrame[] {\n if (!Array.isArray(snapshots)) {\n throw new Error(\n \"[Directive] framesFromSnapshots: expected an array of fact-state snapshots\",\n );\n }\n\n if (snapshots.length > MAX_REPLAY_FRAMES) {\n throw new Error(\n `[Directive] framesFromSnapshots: history has ${snapshots.length} snapshots, exceeds the MAX_REPLAY_FRAMES limit (${MAX_REPLAY_FRAMES}) — split or down-sample the history`,\n );\n }\n\n // A snapshot is always a { facts, ... } object — reject a garbage array\n // before it is silently wrapped into empty-fact frames.\n for (let i = 0; i < snapshots.length; i++) {\n const s = snapshots[i];\n if (!s || typeof s !== \"object\" || !(\"facts\" in s)) {\n throw new Error(\n `[Directive] framesFromSnapshots: snapshot at index ${i} is not a { facts, ... } object`,\n );\n }\n }\n\n return toReplayFrames(snapshots);\n}\n\n/**\n * Replay a recorded fact-frame history through two predicates — the\n * constraint's current `when` and a proposed replacement — and report how\n * their match sets differ.\n *\n * This is a **predicate backtest**: the engine is not re-run. Each recorded\n * frame is statically re-scored against both specs; the previous frame's\n * facts are threaded as `prev` so a replayed effect-`on` predicate using\n * `$changed` still works (for a constraint `when` it is harmless). The\n * report counts matches under each spec and buckets the disagreements into\n * new matches (original false, proposed true) and lost matches (original\n * true, proposed false). Up to `maxSamples` diff frames per bucket carry a\n * per-clause `evaluatePredicateExplained` breakdown for inspection.\n *\n * Both specs are validated up front — a malformed spec throws a clear\n * `[Directive] replayUnder:` error identifying which spec failed, rather\n * than letting a raw `evaluatePredicate` error escape mid-loop.\n *\n * @example\n * ```ts\n * const report = replayUnder({\n * frames: [\n * { id: 0, facts: { phase: \"red\", elapsed: 10 } },\n * { id: 1, facts: { phase: \"red\", elapsed: 35 } },\n * ],\n * original: { phase: \"red\" },\n * proposed: { phase: \"red\", elapsed: { $gte: 30 } },\n * });\n * // report.original.matched === 2\n * // report.proposed.matched === 1\n * // report.delta === -1\n * // report.lostMatchCount === 1\n * ```\n */\nexport function replayUnder<F = Record<string, unknown>>(\n options: ReplayUnderOptions<F>,\n): PredicateBacktestReport {\n const { frames, original, proposed, entityKey } = options;\n const requested = options.maxSamples ?? 20;\n const maxSamples = requested > 0 ? requested : 0;\n\n if (frames.length > MAX_REPLAY_FRAMES) {\n throw new Error(\n `[Directive] replayUnder: history has ${frames.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${MAX_REPLAY_FRAMES}) — split or down-sample the history`,\n );\n }\n\n // Validate both specs before the frame loop — fail loud and clear here\n // rather than at frame 0 with a raw evaluatePredicate stack trace.\n validateReplaySpec(original, \"original\");\n validateReplaySpec(proposed, \"proposed\");\n\n let originalMatched = 0;\n let proposedMatched = 0;\n let newMatchCount = 0;\n let lostMatchCount = 0;\n let unchanged = 0;\n const newMatches: ReplayDiffSample[] = [];\n const lostMatches: ReplayDiffSample[] = [];\n\n // Distinct-entity tracking — only allocated when `entityKey` was supplied.\n const originalEntities = entityKey ? new Set<unknown>() : undefined;\n const proposedEntities = entityKey ? new Set<unknown>() : undefined;\n\n let prevFacts: Record<string, unknown> | undefined;\n\n for (const frame of frames) {\n const facts = frame.facts as Record<string, unknown>;\n const originalBit = evaluatePredicate(original, facts, prevFacts);\n const proposedBit = evaluatePredicate(proposed, facts, prevFacts);\n\n if (originalBit) {\n originalMatched++;\n originalEntities?.add(facts[entityKey as string]);\n }\n if (proposedBit) {\n proposedMatched++;\n proposedEntities?.add(facts[entityKey as string]);\n }\n\n if (originalBit === proposedBit) {\n unchanged++;\n } else if (!originalBit && proposedBit) {\n newMatchCount++;\n if (newMatches.length < maxSamples) {\n newMatches.push(buildSample(frame, original, proposed, prevFacts));\n }\n } else {\n lostMatchCount++;\n if (lostMatches.length < maxSamples) {\n lostMatches.push(buildSample(frame, original, proposed, prevFacts));\n }\n }\n\n prevFacts = facts;\n }\n\n const report: PredicateBacktestReport = {\n framesEvaluated: frames.length,\n original: { matched: originalMatched },\n proposed: { matched: proposedMatched },\n delta: proposedMatched - originalMatched,\n newMatchCount,\n lostMatchCount,\n unchanged,\n newMatches,\n lostMatches,\n };\n\n if (originalEntities && proposedEntities) {\n report.original.matchedEntities = originalEntities.size;\n report.proposed.matchedEntities = proposedEntities.size;\n }\n\n return report;\n}\n\n/**\n * Build a {@link ReplayDiffSample} for a frame the two predicates disagree\n * on — the per-clause explain is computed only here, never for non-diff\n * frames, so the common (mostly-agreeing) case stays cheap.\n */\nfunction buildSample<F>(\n frame: ReplayFrame<F>,\n original: unknown,\n proposed: unknown,\n prevFacts: Record<string, unknown> | undefined,\n): ReplayDiffSample {\n const facts = frame.facts as Record<string, unknown>;\n const sample: ReplayDiffSample = {\n frameId: frame.id,\n facts,\n originalExplain: evaluatePredicateExplained(original, facts, prevFacts),\n proposedExplain: evaluatePredicateExplained(proposed, facts, prevFacts),\n };\n\n if (frame.timestamp !== undefined) {\n sample.timestamp = frame.timestamp;\n }\n\n return sample;\n}\n","/**\n * Parameter sweep over a predicate template — the grid-search counterpart\n * to `replayUnder`.\n *\n * `replayUnder` diffs ONE proposed predicate against the original.\n * `sweepUnder` takes a **template** with one or more `{ $hole: \"name\" }`\n * markers and a set of candidate values, then replays the history once\n * per (cartesian-product) combination. The result is a response curve\n * over the parameter space plus the argmax under a user-supplied\n * objective — turning rule-tuning from guess-and-check into a one-call\n * optimization against recorded traffic.\n *\n * Pure module — imports only the predicate runtime and replay engine.\n * No engine / store / tracking dependency.\n */\n\nimport { MAX_PREDICATE_DEPTH } from \"./predicate.js\";\nimport { type PredicateBacktestReport, type ReplayFrame, replayUnder } from \"./replay-under.js\";\nimport type { FactPredicate } from \"./types/predicate.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** A placeholder inside a predicate template — substituted from `sweep` values. */\nexport interface SweepHole {\n readonly $hole: string;\n}\n\nexport interface SweepUnderOptions<F = Record<string, unknown>> {\n /** Recorded fact-state frames, in chronological order. */\n frames: readonly ReplayFrame<F>[];\n /** The constraint's current `when` predicate (baseline). */\n original: FactPredicate<F>;\n /**\n * Predicate template containing one or more `{ $hole: \"name\" }` markers.\n * Each marker is substituted by the corresponding value from `sweep` on\n * every point in the curve.\n *\n * @example\n * ```ts\n * { cartTotal: { $gte: { $hole: \"threshold\" } } }\n * ```\n */\n template: unknown;\n /**\n * Map of hole name → candidate values. Multiple holes produce the\n * cartesian product (grid search).\n *\n * @example\n * ```ts\n * { threshold: [25, 50, 100, 200] }\n * { riskScore: [0.5, 0.7, 0.9], minAge: [13, 18, 21] } // 3*3 = 9 points\n * ```\n */\n sweep: Readonly<Record<string, readonly unknown[]>>;\n /**\n * Score function for ranking. Higher is better. Default:\n * `(report) => report.proposed.matched` (maximize matched frames).\n */\n objective?: (report: PredicateBacktestReport) => number;\n /** Optional fact key to additionally report distinct-entity counts. */\n entityKey?: string;\n /**\n * Diff frames sampled per replay (default 0 — count-only for speed).\n * Set higher to inspect specific frames in the report.\n */\n maxSamples?: number;\n}\n\n/** One point on the sweep curve — one candidate value tuple. */\nexport interface SweepPoint {\n /** Hole name → value used at this point. */\n values: Readonly<Record<string, unknown>>;\n /** Full backtest report against this candidate. */\n report: PredicateBacktestReport;\n /** Computed objective score (higher is better). */\n score: number;\n}\n\nexport interface SweepReport {\n /** All points, in sweep order (cartesian-product traversal of sweep keys). */\n points: readonly SweepPoint[];\n /** Index of the highest-scoring point in `points`. */\n bestIndex: number;\n /** Convenience accessor: `points[bestIndex]`. */\n best: SweepPoint;\n /** The original predicate replayed against itself — score baseline for comparison. */\n baseline: SweepPoint;\n}\n\n/** Hard cap on points evaluated in a single sweep — protects against runaway grids. */\nexport const MAX_SWEEP_POINTS = 10_000;\n\n/**\n * Aggregate compute cap: `points × frames` per call. `MAX_SWEEP_POINTS`\n * (10k) and `MAX_REPLAY_FRAMES` (1M) bound each axis individually, but\n * their product would be 10B per-frame evaluations — minutes-to-hours of\n * compute. This caps the realistic upper bound at ~50M evaluations\n * (e.g. 50k frames × 1k points, or 5k frames × 10k points).\n */\nexport const MAX_SWEEP_EVALUATIONS = 50_000_000;\n\n// ============================================================================\n// Hole substitution\n// ============================================================================\n\nfunction isHole(v: unknown): v is SweepHole {\n return (\n v !== null &&\n typeof v === \"object\" &&\n !Array.isArray(v) &&\n Object.keys(v as object).length === 1 &&\n typeof (v as SweepHole).$hole === \"string\"\n );\n}\n\n/**\n * Walk `template`, replacing every `{ $hole: name }` marker with the value\n * looked up in `values`. Returns a new tree — does not mutate `template`.\n * Cycle-guarded; depth-capped at `MAX_PREDICATE_DEPTH`.\n *\n * Throws if a hole's name is not present in `values` — surfaces a typo'd\n * hole name up front rather than letting it land as `undefined` in the\n * evaluator.\n */\nfunction substitute(\n template: unknown,\n values: Record<string, unknown>,\n path: Set<object> = new Set(),\n depth = 0,\n): unknown {\n if (depth > MAX_PREDICATE_DEPTH) {\n throw new Error(\n `[Directive] sweepUnder: template exceeds MAX_PREDICATE_DEPTH (${MAX_PREDICATE_DEPTH}) — flatten the template or split the sweep`,\n );\n }\n\n if (isHole(template)) {\n const name = template.$hole;\n if (!(name in values)) {\n throw new Error(\n `[Directive] sweepUnder: template references hole \"${name}\" but sweep has no values for it`,\n );\n }\n\n // Don't recurse into the substituted value — sweep values are opaque\n // payloads, not templates. A value that itself looks like `{$hole:...}`\n // lands literally in the proposed predicate.\n return values[name];\n }\n\n if (template === null || typeof template !== \"object\") {\n return template;\n }\n\n // Cycle guard via DFS path Set — entries are removed on unwind so that\n // shared (non-cyclic) sub-trees still get substituted on every occurrence.\n if (path.has(template)) {\n throw new Error(\n \"[Directive] sweepUnder: template contains a cycle — predicate templates must be a tree\",\n );\n }\n path.add(template);\n\n try {\n if (Array.isArray(template)) {\n return template.map((entry) => substitute(entry, values, path, depth + 1));\n }\n\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(template)) {\n out[k] = substitute(v, values, path, depth + 1);\n }\n\n return out;\n } finally {\n path.delete(template);\n }\n}\n\n// ============================================================================\n// Cartesian product\n// ============================================================================\n\n/**\n * Iterate the cartesian product of the sweep map's value arrays, in\n * declaration order. Generator avoids materializing the whole grid for\n * large multi-hole sweeps.\n */\nfunction* cartesian(\n keys: readonly string[],\n sweep: Readonly<Record<string, readonly unknown[]>>,\n): Generator<Record<string, unknown>> {\n if (keys.length === 0) {\n yield {};\n\n return;\n }\n\n const head = keys[0] as string;\n const rest = keys.slice(1);\n const headValues = sweep[head] ?? [];\n for (const v of headValues) {\n for (const tail of cartesian(rest, sweep)) {\n yield { [head]: v, ...tail };\n }\n }\n}\n\nfunction gridSize(sweep: Readonly<Record<string, readonly unknown[]>>): number {\n let size = 1;\n for (const arr of Object.values(sweep)) {\n size *= arr.length;\n }\n\n return size;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Sweep a predicate template's hole(s) across candidate values and replay\n * the recorded history through each one. Returns the full response curve\n * plus the argmax under a user-supplied objective.\n *\n * The mechanism is a tight loop over `replayUnder`: walk the cartesian\n * product of sweep values, substitute each combination into the template,\n * and run a backtest. Same caveats as `replayUnder` apply (no cascade\n * modeling, survivorship bias) — see {@link replayUnder} docs.\n *\n * @example\n * ```ts\n * const report = sweepUnder({\n * frames: recordedSessions,\n * original: { cartTotal: { $gte: 100 } },\n * template: { cartTotal: { $gte: { $hole: \"threshold\" } } },\n * sweep: { threshold: [25, 50, 100, 200] },\n * });\n *\n * report.best.values; // { threshold: 25 } (assuming higher matched is better)\n * report.best.report.proposed.matched; // 9210\n * report.baseline.score; // 4217 — the original spec's matched count\n * report.points.length; // 4\n * ```\n *\n * Multi-hole sweeps grid-search:\n *\n * ```ts\n * sweepUnder({\n * frames,\n * original,\n * template: {\n * risk: { $gte: { $hole: \"minRisk\" } },\n * age: { $gte: { $hole: \"minAge\" } },\n * },\n * sweep: { minRisk: [0.5, 0.7, 0.9], minAge: [13, 18, 21] },\n * });\n * // → 9 points (3 × 3)\n * ```\n */\nexport function sweepUnder<F = Record<string, unknown>>(\n options: SweepUnderOptions<F>,\n): SweepReport {\n const {\n frames,\n original,\n template,\n sweep,\n objective = (r) => r.proposed.matched,\n entityKey,\n maxSamples = 0,\n } = options;\n\n const keys = Object.keys(sweep);\n if (keys.length === 0) {\n throw new Error(\n \"[Directive] sweepUnder: `sweep` must contain at least one hole name\",\n );\n }\n\n const total = gridSize(sweep);\n if (total > MAX_SWEEP_POINTS) {\n throw new Error(\n `[Directive] sweepUnder: grid has ${total} points, exceeds the MAX_SWEEP_POINTS limit (${MAX_SWEEP_POINTS}) — narrow the sweep ranges or split the run`,\n );\n }\n if (total === 0) {\n throw new Error(\n \"[Directive] sweepUnder: at least one hole has zero candidate values\",\n );\n }\n const evaluations = total * frames.length;\n if (evaluations > MAX_SWEEP_EVALUATIONS) {\n throw new Error(\n `[Directive] sweepUnder: ${total} points × ${frames.length} frames = ${evaluations} per-frame evaluations, exceeds the MAX_SWEEP_EVALUATIONS limit (${MAX_SWEEP_EVALUATIONS}) — narrow the sweep, down-sample the history, or split the run`,\n );\n }\n\n // Invoke the user's objective with a catch + finite-number guard.\n // A throw or non-finite return becomes -Infinity so the point sinks in\n // the ranking instead of corrupting it (and stays out of the argmax).\n let warnedObjective = false;\n const safeObjective = (report: PredicateBacktestReport): number => {\n let raw: unknown;\n try {\n raw = objective(report);\n } catch (err) {\n if (!warnedObjective) {\n warnedObjective = true;\n console.warn(\n `[Directive] sweepUnder: objective threw — point will not rank (${(err as Error).message})`,\n );\n }\n\n return Number.NEGATIVE_INFINITY;\n }\n if (typeof raw !== \"number\" || !Number.isFinite(raw)) {\n if (!warnedObjective) {\n warnedObjective = true;\n console.warn(\n `[Directive] sweepUnder: objective returned a non-finite number (${String(raw)}) — point will not rank`,\n );\n }\n\n return Number.NEGATIVE_INFINITY;\n }\n\n return raw;\n };\n\n // Baseline: replay original against itself so the caller has a\n // comparable score under the same objective. This is one extra\n // replayUnder() call regardless of grid size — cheap, useful.\n const baselineReport = replayUnder({\n frames,\n original,\n proposed: original,\n entityKey,\n maxSamples,\n });\n const baseline: SweepPoint = {\n values: {},\n report: baselineReport,\n score: safeObjective(baselineReport),\n };\n\n const points: SweepPoint[] = [];\n let bestIndex = 0;\n let bestScore = Number.NEGATIVE_INFINITY;\n\n for (const values of cartesian(keys, sweep)) {\n const proposed = substitute(template, values) as FactPredicate<F>;\n const report = replayUnder({\n frames,\n original,\n proposed,\n entityKey,\n maxSamples,\n });\n const score = safeObjective(report);\n if (score > bestScore) {\n bestScore = score;\n bestIndex = points.length;\n }\n points.push({ values, report, score });\n }\n\n // points is guaranteed non-empty here because total > 0 and the loop ran.\n const best = points[bestIndex] as SweepPoint;\n\n return {\n points,\n bestIndex,\n best,\n baseline,\n };\n}\n","/**\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 && typeof raw === \"object\" && !Array.isArray(raw) && \"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(\"[Directive] diffRules: constraint `id` must be a string\");\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\n ? `${pathPrefix}.${String(c.fact)}`\n : 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 * predict() — \"would this predicate fire against these facts, and if\n * not, what facts must change to make it fire?\"\n *\n * Closes the LLM-emit iteration loop: the model writes a rule,\n * `predict()` says \"this rule needs cartTotal ≥ 50 to fire; current\n * value is 30,\" and the model rewrites accordingly. A predicate-aware\n * preview that costs one walk of the predicate tree.\n *\n * Pure, sync, no engine dependency. Reuses `evaluatePredicateExplained`.\n */\n\nimport {\n evaluatePredicateExplained,\n} from \"./predicate.js\";\nimport type { ClauseResult, FactPredicate } from \"./types/predicate.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface PredictMissingChange {\n /** Dotted path to the fact. */\n readonly path: string;\n /** The operator that failed. */\n readonly op: string;\n /** What the predicate expected. */\n readonly expected: unknown;\n /** What the fact currently is. */\n readonly actual: unknown;\n /** Human-readable hint suitable for feeding back to an LLM or showing to a user. */\n readonly suggestion: string;\n}\n\nexport interface PredictResult<F> {\n /** True iff the predicate would fire against `facts`. */\n readonly wouldFire: boolean;\n /** Full clause-by-clause result (reuses the whenExplain payload). */\n readonly whenExplain: readonly ClauseResult[];\n /**\n * List of failing clauses, each with a `suggestion` describing the\n * smallest concrete change to `facts` that would make that clause pass.\n * Empty when `wouldFire === true`.\n */\n readonly missingChanges: readonly PredictMissingChange[];\n /** Reference to the predicate evaluated, for telemetry. */\n readonly predicate: FactPredicate<F>;\n}\n\n// ============================================================================\n// Suggestion synthesis\n// ============================================================================\n\nfunction fmt(v: unknown): string {\n if (v === null) return \"null\";\n if (v === undefined) return \"undefined\";\n if (v instanceof Date) return v.toISOString();\n if (typeof v === \"string\") return JSON.stringify(v);\n if (typeof v === \"object\") return JSON.stringify(v);\n\n return String(v);\n}\n\n/**\n * Per-operator suggestion templates. Each returns a short, imperative\n * line aimed at a developer or LLM consumer:\n *\n * \"set cartTotal to at least 50 (currently 30)\"\n * \"set status to one of [active, pending] (currently inactive)\"\n * \"remove tags so it's empty (currently has 3 items)\"\n */\nfunction suggestionFor(clause: ClauseResult): string {\n const path = clause.path;\n const expected = fmt(clause.expected);\n const actual = fmt(clause.actual);\n\n switch (clause.op) {\n case \"$eq\":\n return `set ${path} to ${expected} (currently ${actual})`;\n case \"$ne\":\n return `change ${path} to anything other than ${expected} (currently ${actual})`;\n case \"$gt\":\n return `set ${path} above ${expected} (currently ${actual})`;\n case \"$gte\":\n return `set ${path} to at least ${expected} (currently ${actual})`;\n case \"$lt\":\n return `set ${path} below ${expected} (currently ${actual})`;\n case \"$lte\":\n return `set ${path} to at most ${expected} (currently ${actual})`;\n case \"$in\":\n return `set ${path} to one of ${expected} (currently ${actual})`;\n case \"$nin\":\n return `set ${path} to something other than ${expected} (currently ${actual})`;\n case \"$exists\":\n return clause.expected === true\n ? `set ${path} to a non-null value (currently null/missing)`\n : `unset ${path} (currently ${actual})`;\n case \"$between\": {\n if (Array.isArray(clause.expected) && clause.expected.length === 2) {\n return `set ${path} between ${fmt(clause.expected[0])} and ${fmt(clause.expected[1])} (currently ${actual})`;\n }\n\n return `set ${path} within range ${expected} (currently ${actual})`;\n }\n case \"$startsWith\":\n return `set ${path} to start with ${expected} (currently ${actual})`;\n case \"$endsWith\":\n return `set ${path} to end with ${expected} (currently ${actual})`;\n case \"$contains\":\n return `set ${path} to contain ${expected} (currently ${actual})`;\n case \"$matches\":\n return `set ${path} to match the pattern ${expected} (currently ${actual})`;\n case \"$changed\":\n return `the previous-vs-current change of ${path} is required to differ (currently they match: ${actual})`;\n case \"$all\":\n case \"$any\":\n case \"$not\":\n // Combinators fail when their children's pattern fails — surface a generic suggestion.\n return `the ${clause.op} group at \"${path}\" did not pass — see its child clauses`;\n default:\n return `clause at ${path} (${clause.op}) failed: expected ${expected}, got ${actual}`;\n }\n}\n\n// ============================================================================\n// Collect failed leaves\n// ============================================================================\n\nfunction collectFailedLeaves(\n clauses: readonly ClauseResult[],\n out: PredictMissingChange[],\n): void {\n for (const c of clauses) {\n if (c.pass) continue;\n\n // Combinators: recurse into children — surface the leaves that actually failed.\n if ((c.op === \"$all\" || c.op === \"$any\" || c.op === \"$not\") && c.children) {\n // For $any: only one child needs to pass — emit the \"cheapest\" suggestion\n // (typically the first failed leaf) plus a hint about alternatives.\n // For $all and $not: every failing child is a required change.\n collectFailedLeaves(c.children, out);\n continue;\n }\n\n out.push({\n path: c.path,\n op: c.op,\n expected: c.expected,\n actual: c.actual,\n suggestion: suggestionFor(c),\n });\n }\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Run a predicate against the current fact state and report whether it\n * would fire — *and if not, which facts must change*.\n *\n * Designed for the LLM-iteration loop and for \"preview the impact of this\n * rule\" UIs.\n *\n * @example\n * ```ts\n * const predicate = { cartTotal: { $gte: 50 }, region: { $in: [\"US\", \"EU\"] } };\n * const facts = { cartTotal: 30, region: \"US\" };\n *\n * predict(predicate, facts);\n * // → {\n * // wouldFire: false,\n * // whenExplain: [ {path: \"cartTotal\", op: \"$gte\", pass: false, ...}, ... ],\n * // missingChanges: [\n * // { path: \"cartTotal\", op: \"$gte\", expected: 50, actual: 30,\n * // suggestion: \"set cartTotal to at least 50 (currently 30)\" },\n * // ],\n * // predicate: { cartTotal: { $gte: 50 }, region: { $in: [\"US\", \"EU\"] } },\n * // }\n * ```\n */\nexport function predict<F = Record<string, unknown>>(\n predicate: FactPredicate<F>,\n facts: F,\n prev?: F,\n): PredictResult<F> {\n const whenExplain = evaluatePredicateExplained(\n predicate as unknown,\n facts as unknown as Record<string, unknown>,\n prev as unknown as Record<string, unknown> | undefined,\n );\n const wouldFire = whenExplain.every((c) => c.pass);\n\n const missingChanges: PredictMissingChange[] = [];\n if (!wouldFire) {\n collectFailedLeaves(whenExplain, missingChanges);\n }\n\n return {\n wouldFire,\n whenExplain,\n missingChanges,\n predicate,\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 * - **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 never fires independently of the old).\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 * Pure, sync, no engine dependency.\n */\n\nimport { flattenPredicate, type LeafClause } 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 /** Hard contradictions — candidate never co-fires with existing rule. */\n readonly contradictions: readonly Contradiction[];\n /** Soft overlaps — shared facts with non-trivial intersection. */\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\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 (!deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) {\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 */\nfunction 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 { type: \"subset\", reason: `Both rules require ${cand.path} = ${JSON.stringify(cand.value)} — candidate is redundant.` };\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 = cand.op === \"$gt\" || cand.op === \"$gte\" ? cand.value : undefined;\n const candHi = 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: readonly ExistingConstraint[] | { 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 if (verdict.type === \"overlap\") {\n warnings.push(finding);\n } else {\n contradictions.push(finding);\n }\n }\n }\n }\n\n return { contradictions, warnings };\n },\n};\n","/**\n * Compile a `FactPredicate` to a parameterized Postgres-style SQL WHERE\n * clause. The same predicate that gates a constraint on the client can\n * filter rows on the server — *one source of truth, two execution sites*.\n *\n * Pure transformation. No engine, no driver, no string concatenation of\n * user values (all operands flow through the parameter array → safe\n * against SQL injection by construction).\n */\n\nimport { MAX_PREDICATE_DEPTH } from \"./predicate.js\";\nimport {\n PREDICATE_OPERATORS,\n type FactPredicate,\n} from \"./types/predicate.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface PredicateToSqlOptions {\n /** Table to query. Validated against the same identifier rule as columns. */\n table: string;\n /**\n * Allowlist of fact / column keys the predicate may reference. STRONGLY\n * RECOMMENDED for any predicate that crosses a trust boundary (AI\n * generation, user input, JSON-over-the-wire). Without an allowlist, a\n * predicate may reference any column the table has.\n */\n allowedKeys?: readonly string[];\n /**\n * Customize the `SELECT` projection. Default `\"*\"`. Accepts:\n * - `\"*\"`\n * - a column identifier (`\"id\"` or `\"users.id\"`)\n * - an array of column identifiers (`[\"id\", \"name\"]`) — joined with `,`\n * Free-form strings (e.g. `\"COUNT(*)\"`) are rejected — build the wrapper\n * SQL manually with {@link predicateToWhere} for those cases.\n */\n select?: string | readonly string[];\n /**\n * Parameter placeholder generator. Default is Postgres-style `$1`, `$2`.\n * Pass `() => \"?\"` for MySQL/SQLite, or supply your own scheme.\n */\n placeholder?: (oneBasedIndex: number) => string;\n}\n\nexport interface PredicateToSqlResult {\n /** Full `SELECT … FROM table WHERE …` statement. */\n sql: string;\n /** Just the `WHERE` clause body (without the literal `WHERE`). */\n where: string;\n /** Parameters, in `$1`-then-`$2`-then-… order. */\n params: unknown[];\n}\n\n// ============================================================================\n// Identifier safety\n// ============================================================================\n\n/**\n * Strict identifier check: alpha, digits, underscore, optional dot for\n * qualified names (`table.column`). No whitespace, no quotes, no\n * semicolons — anything not matching is rejected with a clear error.\n *\n * Identifiers are interpolated *literally* into the SQL string (the only\n * safe alternative is double-quoting, which changes case sensitivity).\n * This regex is the only thing standing between a column-name typo and a\n * SQL injection — keep it strict.\n */\nconst IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*)?$/;\n\nfunction assertIdentifier(name: string, kind: \"table\" | \"column\"): void {\n if (typeof name !== \"string\" || !IDENT_RE.test(name)) {\n throw new Error(\n `[Directive] predicateToSQL: invalid ${kind} identifier \"${name}\" — must match /^[A-Za-z_][A-Za-z0-9_]*(\\\\.[A-Za-z_][A-Za-z0-9_]*)?$/`,\n );\n }\n}\n\nfunction assertAllowed(\n name: string,\n allowed: readonly string[] | undefined,\n): void {\n if (allowed && !allowed.includes(name)) {\n throw new Error(\n `[Directive] predicateToSQL: column \"${name}\" is not in the allowedKeys list — add it to options.allowedKeys or remove it from the predicate`,\n );\n }\n}\n\nfunction validateSelect(select: string | readonly string[]): string {\n if (Array.isArray(select)) {\n if (select.length === 0) {\n throw new Error(`[Directive] predicateToSQL: select must not be empty`);\n }\n for (const col of select) {\n assertIdentifier(col, \"column\");\n }\n\n return select.join(\", \");\n }\n const s = select as string;\n if (s === \"*\") return \"*\";\n assertIdentifier(s, \"column\");\n\n return s;\n}\n\n// ============================================================================\n// Operator translation\n// ============================================================================\n\ninterface BuildContext {\n params: unknown[];\n placeholder: (i: number) => string;\n allowed?: readonly string[];\n}\n\nfunction nextParam(ctx: BuildContext, value: unknown): string {\n ctx.params.push(value);\n\n return ctx.placeholder(ctx.params.length);\n}\n\n/**\n * Render one operator on one column. `column` is already\n * identifier-validated; the operand goes through `nextParam` so it lands\n * in `params`, never in the SQL string.\n */\nfunction renderOp(\n column: string,\n op: string,\n operand: unknown,\n ctx: BuildContext,\n): string {\n switch (op) {\n case \"$eq\":\n return `${column} = ${nextParam(ctx, operand)}`;\n case \"$ne\":\n return `${column} <> ${nextParam(ctx, operand)}`;\n case \"$gt\":\n return `${column} > ${nextParam(ctx, operand)}`;\n case \"$gte\":\n return `${column} >= ${nextParam(ctx, operand)}`;\n case \"$lt\":\n return `${column} < ${nextParam(ctx, operand)}`;\n case \"$lte\":\n return `${column} <= ${nextParam(ctx, operand)}`;\n case \"$in\":\n if (!Array.isArray(operand)) {\n throw new Error(`[Directive] predicateToSQL: $in operand must be an array`);\n }\n return `${column} = ANY(${nextParam(ctx, operand)})`;\n case \"$nin\":\n if (!Array.isArray(operand)) {\n throw new Error(`[Directive] predicateToSQL: $nin operand must be an array`);\n }\n return `NOT (${column} = ANY(${nextParam(ctx, operand)}))`;\n case \"$exists\":\n return operand === true ? `${column} IS NOT NULL` : `${column} IS NULL`;\n case \"$between\": {\n if (!Array.isArray(operand) || operand.length !== 2) {\n throw new Error(\n `[Directive] predicateToSQL: $between operand must be a [low, high] tuple`,\n );\n }\n return `${column} BETWEEN ${nextParam(ctx, operand[0])} AND ${nextParam(ctx, operand[1])}`;\n }\n case \"$startsWith\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToSQL: $startsWith operand must be a string`,\n );\n }\n // ESCAPE '\\' makes the escape character deterministic regardless of\n // the server's standard_conforming_strings setting or MySQL's\n // NO_BACKSLASH_ESCAPES mode.\n return `${column} LIKE ${nextParam(ctx, escapeLike(operand))} || '%' ESCAPE '\\\\'`;\n case \"$endsWith\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToSQL: $endsWith operand must be a string`,\n );\n }\n return `${column} LIKE '%' || ${nextParam(ctx, escapeLike(operand))} ESCAPE '\\\\'`;\n case \"$contains\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToSQL: $contains only supports string operands — array containment requires a JOIN, not a predicate`,\n );\n }\n return `${column} LIKE '%' || ${nextParam(ctx, escapeLike(operand))} || '%' ESCAPE '\\\\'`;\n case \"$matches\": {\n if (!(operand instanceof RegExp)) {\n throw new Error(\n `[Directive] predicateToSQL: $matches operand must be a RegExp`,\n );\n }\n // Postgres uses ~ (case-sensitive) and ~* (case-insensitive). The\n // RegExp's `i` flag picks the operator; other flags are silently\n // dropped because their semantics differ between JS and Postgres.\n const operator = operand.flags.includes(\"i\") ? \"~*\" : \"~\";\n\n return `${column} ${operator} ${nextParam(ctx, operand.source)}`;\n }\n case \"$changed\":\n throw new Error(\n `[Directive] predicateToSQL: $changed is an effects-only operator — no server-side translation (a database row has no \"prev\" snapshot)`,\n );\n default:\n throw new Error(\n `[Directive] predicateToSQL: unknown operator \"${op}\" — known: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n}\n\n/**\n * Escape `%`, `_`, and `\\` in a LIKE operand. Paired with an explicit\n * `ESCAPE '\\'` clause for cross-database determinism.\n */\nfunction escapeLike(s: string): string {\n return s.replace(/[\\\\%_]/g, \"\\\\$&\");\n}\n\n// ============================================================================\n// Recursive walk\n// ============================================================================\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\nfunction isOperatorObject(v: unknown): v is Record<string, unknown> {\n if (!isPlainObject(v)) return false;\n const keys = Object.keys(v);\n if (keys.length === 0) return false;\n for (const k of keys) {\n if (!k.startsWith(\"$\")) return false;\n }\n\n return true;\n}\n\nfunction assertNoSiblingKeys(spec: Record<string, unknown>, combinator: string): void {\n const sibs = Object.keys(spec).filter((k) => k !== combinator);\n if (sibs.length > 0) {\n throw new Error(\n `[Directive] predicateToSQL: ${combinator} cannot coexist with sibling keys (${sibs.join(\", \")}) — wrap them in $all together, or move them inside the ${combinator} children`,\n );\n }\n}\n\nfunction buildWhere(spec: unknown, ctx: BuildContext, depth: number): string {\n if (depth > MAX_PREDICATE_DEPTH) {\n throw new Error(\n `[Directive] predicateToSQL: predicate depth limit (${MAX_PREDICATE_DEPTH}) exceeded — flatten the predicate or check for a cyclic spec object`,\n );\n }\n if (spec === null || typeof spec !== \"object\") {\n throw new Error(\n `[Directive] predicateToSQL: predicate must be an object or array, got ${typeof spec}`,\n );\n }\n\n // Array-form predicate ([{fact, op, value}, ...]) — implicit AND.\n if (Array.isArray(spec)) {\n if (spec.length === 0) return \"TRUE\";\n const parts = spec.map((clause) => {\n if (\n !clause ||\n typeof clause !== \"object\" ||\n !(\"fact\" in clause) ||\n !(\"op\" in clause)\n ) {\n throw new Error(\n `[Directive] predicateToSQL: array-form clause must be { fact, op, value }`,\n );\n }\n const c = clause as { fact: string; op: string; value: unknown };\n assertIdentifier(c.fact, \"column\");\n assertAllowed(c.fact, ctx.allowed);\n\n return renderOp(c.fact, c.op, c.value, ctx);\n });\n\n return parts.length === 1 ? parts[0]! : `(${parts.join(\" AND \")})`;\n }\n\n // Combinators — must be the *only* key on the object.\n if (\"$all\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$all\");\n const arr = (spec as { $all: unknown[] }).$all;\n if (!Array.isArray(arr)) {\n throw new Error(`[Directive] predicateToSQL: $all must be an array`);\n }\n if (arr.length === 0) return \"TRUE\";\n const parts = arr.map((p) => buildWhere(p, ctx, depth + 1));\n\n return parts.length === 1 ? parts[0]! : `(${parts.join(\" AND \")})`;\n }\n if (\"$any\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$any\");\n const arr = (spec as { $any: unknown[] }).$any;\n if (!Array.isArray(arr)) {\n throw new Error(`[Directive] predicateToSQL: $any must be an array`);\n }\n if (arr.length === 0) return \"FALSE\";\n const parts = arr.map((p) => buildWhere(p, ctx, depth + 1));\n\n return parts.length === 1 ? parts[0]! : `(${parts.join(\" OR \")})`;\n }\n if (\"$not\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$not\");\n const inner = (spec as { $not: unknown }).$not;\n\n return `NOT (${buildWhere(inner, ctx, depth + 1)})`;\n }\n\n // Object form — every key is a column, every value either a literal\n // (equality) or an operator object.\n const parts: string[] = [];\n for (const [key, value] of Object.entries(spec as Record<string, unknown>)) {\n assertIdentifier(key, \"column\");\n assertAllowed(key, ctx.allowed);\n\n if (isOperatorObject(value)) {\n for (const [op, operand] of Object.entries(value)) {\n if (!PREDICATE_OPERATORS.has(op)) {\n throw new Error(\n `[Directive] predicateToSQL: unknown operator \"${op}\" on column \"${key}\" — known: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n parts.push(renderOp(key, op, operand, ctx));\n }\n } else if (isPlainObject(value)) {\n throw new Error(\n `[Directive] predicateToSQL: nested predicate at \"${key}\" — cross-module / partial-match predicates have no SQL equivalent (single-table queries only in v1; pass a flat predicate or build JOIN by hand with predicateToWhere)`,\n );\n } else {\n parts.push(renderOp(key, \"$eq\", value, ctx));\n }\n }\n\n if (parts.length === 0) return \"TRUE\";\n if (parts.length === 1) return parts[0]!;\n\n return `(${parts.join(\" AND \")})`;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\nconst DEFAULT_PLACEHOLDER = (i: number) => `$${i}`;\n\n/**\n * Compile a {@link FactPredicate} to a parameterized SQL statement.\n *\n * Operand values **never** appear in the SQL string — they flow through\n * the `params` array. Table and column identifiers are regex-validated.\n *\n * @example\n * ```ts\n * const where = { age: { $gte: 18 }, status: { $in: [\"active\", \"pending\"] } };\n *\n * predicateToSQL(where, { table: \"users\" });\n * // → { sql: \"SELECT * FROM users WHERE (age >= $1 AND status = ANY($2))\",\n * // where: \"(age >= $1 AND status = ANY($2))\",\n * // params: [18, [\"active\", \"pending\"]] }\n *\n * // MySQL/SQLite placeholder:\n * predicateToSQL(where, { table: \"users\", placeholder: () => \"?\" });\n *\n * // Recommended for AI/user-supplied predicates:\n * predicateToSQL(where, { table: \"users\", allowedKeys: [\"age\", \"status\"] });\n * ```\n */\nexport function predicateToSQL<F = Record<string, unknown>>(\n predicate: FactPredicate<F>,\n options: PredicateToSqlOptions,\n): PredicateToSqlResult {\n const { table, allowedKeys } = options;\n const placeholder = options.placeholder ?? DEFAULT_PLACEHOLDER;\n const select = options.select ?? \"*\";\n\n assertIdentifier(table, \"table\");\n const projection = validateSelect(select);\n\n const ctx: BuildContext = { params: [], placeholder, allowed: allowedKeys };\n const where = buildWhere(predicate, ctx, 0);\n const sql = `SELECT ${projection} FROM ${table} WHERE ${where}`;\n\n return { sql, where, params: ctx.params };\n}\n\n/**\n * Lower-level variant — returns just the `WHERE` clause body and the\n * `params` array, no `SELECT ... FROM` wrapper. Use this when you need\n * to embed the WHERE in a larger query (JOIN, UPDATE, DELETE, COUNT).\n *\n * @example\n * ```ts\n * const { where, params } = predicateToWhere({ age: { $gte: 18 } });\n * await db.query(`UPDATE users SET tier = 'adult' WHERE ${where}`, params);\n * ```\n */\nexport function predicateToWhere<F = Record<string, unknown>>(\n predicate: FactPredicate<F>,\n options: Omit<PredicateToSqlOptions, \"table\" | \"select\"> = {},\n): { where: string; params: unknown[] } {\n const placeholder = options.placeholder ?? DEFAULT_PLACEHOLDER;\n const ctx: BuildContext = {\n params: [],\n placeholder,\n allowed: options.allowedKeys,\n };\n\n return { where: buildWhere(predicate, ctx, 0), params: ctx.params };\n}\n","/**\n * Compile a `FactPredicate` to a MongoDB query document. Most of\n * Directive's predicate operator set is already Mongo-compatible by\n * design — this translator handles the few ops that need rewriting\n * (`$startsWith`/`$endsWith`/`$contains` → `$regex`, `$between` →\n * `$gte`+`$lte`, `$matches` → `$regex`/`$options`).\n *\n * Combinators map cleanly: `$all` → `$and`, `$any` → `$or`, `$not` → `$nor`.\n *\n * Pure transformation. No driver dependency.\n */\n\nimport { MAX_PREDICATE_DEPTH } from \"./predicate.js\";\nimport {\n PREDICATE_OPERATORS,\n type FactPredicate,\n} from \"./types/predicate.js\";\n\nexport interface PredicateToMongoOptions {\n /**\n * Allowlist of fact / field keys the predicate may reference. STRONGLY\n * RECOMMENDED for any predicate that crosses a trust boundary.\n */\n allowedKeys?: readonly string[];\n /**\n * Allow `.` in field names (for sub-document traversal: `\"user.role\"`).\n * Default is `false` — `.` is rejected so the predicate cannot\n * accidentally read sub-document fields the developer did not anticipate.\n */\n allowDottedPaths?: boolean;\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\nfunction isOperatorObject(v: unknown): v is Record<string, unknown> {\n if (!isPlainObject(v)) return false;\n const keys = Object.keys(v);\n if (keys.length === 0) return false;\n for (const k of keys) {\n if (!k.startsWith(\"$\")) return false;\n }\n\n return true;\n}\n\nconst FIELD_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst FIELD_DOTTED_RE = /^[A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*)*$/;\n\n/**\n * Reject any field that starts with `$` — that's how Mongo's `$where`\n * JavaScript-evaluation injection lands a predicate-as-RCE. Also reject\n * non-identifier characters (`.`, ` `, etc.) unless dotted paths are\n * explicitly enabled.\n */\nfunction assertFieldName(name: string, opts: PredicateToMongoOptions): void {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(\n `[Directive] predicateToMongo: field name must be a non-empty string, got ${typeof name}`,\n );\n }\n if (name.startsWith(\"$\")) {\n throw new Error(\n `[Directive] predicateToMongo: field name \"${name}\" starts with \"$\" — reserved for Mongo operators (a top-level $where would be an injection vector)`,\n );\n }\n const re = opts.allowDottedPaths ? FIELD_DOTTED_RE : FIELD_RE;\n if (!re.test(name)) {\n throw new Error(\n `[Directive] predicateToMongo: invalid field name \"${name}\"${opts.allowDottedPaths ? \"\" : ' — pass options.allowDottedPaths=true to permit sub-document paths like \"user.role\"'}`,\n );\n }\n}\n\nfunction assertAllowed(\n field: string,\n allowed: readonly string[] | undefined,\n): void {\n if (allowed && !allowed.includes(field)) {\n throw new Error(\n `[Directive] predicateToMongo: field \"${field}\" is not in the allowedKeys list — add it to options.allowedKeys or remove it from the predicate`,\n );\n }\n}\n\nfunction assertNoSiblingKeys(spec: Record<string, unknown>, combinator: string): void {\n const sibs = Object.keys(spec).filter((k) => k !== combinator);\n if (sibs.length > 0) {\n throw new Error(\n `[Directive] predicateToMongo: ${combinator} cannot coexist with sibling keys (${sibs.join(\", \")}) — wrap them in $all together, or move them inside the ${combinator} children`,\n );\n }\n}\n\n/**\n * Translate a single operator/operand pair into the Mongo equivalent.\n * Returns the value side of `{ field: <here> }`.\n */\nfunction translateOp(op: string, operand: unknown): Record<string, unknown> {\n switch (op) {\n case \"$eq\":\n case \"$ne\":\n case \"$gt\":\n case \"$gte\":\n case \"$lt\":\n case \"$lte\":\n case \"$in\":\n case \"$nin\":\n case \"$exists\":\n return { [op]: operand };\n case \"$between\": {\n if (!Array.isArray(operand) || operand.length !== 2) {\n throw new Error(\n `[Directive] predicateToMongo: $between operand must be a [low, high] tuple`,\n );\n }\n return { $gte: operand[0], $lte: operand[1] };\n }\n case \"$startsWith\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToMongo: $startsWith operand must be a string`,\n );\n }\n return { $regex: `^${escapeRegex(operand)}` };\n case \"$endsWith\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToMongo: $endsWith operand must be a string`,\n );\n }\n return { $regex: `${escapeRegex(operand)}$` };\n case \"$contains\":\n if (typeof operand === \"string\") {\n return { $regex: escapeRegex(operand) };\n }\n throw new Error(\n `[Directive] predicateToMongo: $contains in Mongo expects a string operand — for array element membership use $elemMatch or $in directly`,\n );\n case \"$matches\": {\n if (operand instanceof RegExp) {\n return operand.flags\n ? { $regex: operand.source, $options: operand.flags }\n : { $regex: operand.source };\n }\n if (typeof operand === \"string\") {\n return { $regex: operand };\n }\n throw new Error(\n `[Directive] predicateToMongo: $matches operand must be a RegExp or string`,\n );\n }\n case \"$changed\":\n throw new Error(\n `[Directive] predicateToMongo: $changed is an effects-only operator — no MongoDB query equivalent`,\n );\n default:\n throw new Error(\n `[Directive] predicateToMongo: unknown operator \"${op}\" — known: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n}\n\nfunction buildQuery(\n spec: unknown,\n opts: PredicateToMongoOptions,\n depth: number,\n): Record<string, unknown> {\n if (depth > MAX_PREDICATE_DEPTH) {\n throw new Error(\n `[Directive] predicateToMongo: predicate depth limit (${MAX_PREDICATE_DEPTH}) exceeded — flatten the predicate or check for a cyclic spec object`,\n );\n }\n if (spec === null || typeof spec !== \"object\") {\n throw new Error(\n `[Directive] predicateToMongo: predicate must be an object or array, got ${typeof spec}`,\n );\n }\n\n // Array form → implicit AND.\n if (Array.isArray(spec)) {\n if (spec.length === 0) return {};\n const obj: Record<string, unknown> = {};\n const conflicts: Array<Record<string, unknown>> = [];\n for (const clause of spec) {\n if (\n !clause ||\n typeof clause !== \"object\" ||\n !(\"fact\" in clause) ||\n !(\"op\" in clause)\n ) {\n throw new Error(\n `[Directive] predicateToMongo: array-form clause must be { fact, op, value }`,\n );\n }\n const c = clause as { fact: string; op: string; value: unknown };\n assertFieldName(c.fact, opts);\n assertAllowed(c.fact, opts.allowedKeys);\n const translated = translateOp(c.op, c.value);\n\n if (c.fact in obj && isPlainObject(obj[c.fact])) {\n const existing = obj[c.fact] as Record<string, unknown>;\n const overlap = Object.keys(translated).some((k) => k in existing);\n if (overlap) {\n conflicts.push({ [c.fact]: translated });\n } else {\n obj[c.fact] = { ...existing, ...translated };\n }\n } else if (c.fact in obj) {\n conflicts.push({ [c.fact]: translated });\n } else {\n obj[c.fact] = translated;\n }\n }\n if (conflicts.length > 0) {\n const andClauses: Array<Record<string, unknown>> = [];\n for (const [k, v] of Object.entries(obj)) {\n andClauses.push({ [k]: v });\n }\n andClauses.push(...conflicts);\n\n return { $and: andClauses };\n }\n\n return obj;\n }\n\n // Combinators\n if (\"$all\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$all\");\n const arr = (spec as { $all: unknown[] }).$all;\n if (!Array.isArray(arr)) {\n throw new Error(`[Directive] predicateToMongo: $all must be an array`);\n }\n if (arr.length === 0) return {};\n if (arr.length === 1) return buildQuery(arr[0], opts, depth + 1);\n\n return { $and: arr.map((p) => buildQuery(p, opts, depth + 1)) };\n }\n if (\"$any\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$any\");\n const arr = (spec as { $any: unknown[] }).$any;\n if (!Array.isArray(arr)) {\n throw new Error(`[Directive] predicateToMongo: $any must be an array`);\n }\n // Tautological-false — stable across Mongo versions, no _id assumption.\n if (arr.length === 0) return { $expr: { $eq: [1, 0] } };\n if (arr.length === 1) return buildQuery(arr[0], opts, depth + 1);\n\n return { $or: arr.map((p) => buildQuery(p, opts, depth + 1)) };\n }\n if (\"$not\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$not\");\n const inner = (spec as { $not: unknown }).$not;\n // Mongo's top-level $not is restricted to per-field; $nor: [...]\n // is the portable equivalent.\n return { $nor: [buildQuery(inner, opts, depth + 1)] };\n }\n\n // Object form — every key is a field name (validated to NOT start with $).\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(spec as Record<string, unknown>)) {\n assertFieldName(key, opts);\n assertAllowed(key, opts.allowedKeys);\n\n if (isOperatorObject(value)) {\n const merged: Record<string, unknown> = {};\n for (const [op, operand] of Object.entries(value)) {\n if (!PREDICATE_OPERATORS.has(op)) {\n throw new Error(\n `[Directive] predicateToMongo: unknown operator \"${op}\" on field \"${key}\" — known: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n Object.assign(merged, translateOp(op, operand));\n }\n out[key] = merged;\n } else if (isPlainObject(value)) {\n out[key] = value;\n } else {\n out[key] = value;\n }\n }\n\n return out;\n}\n\n/**\n * Compile a {@link FactPredicate} to a MongoDB query document.\n *\n * Field names are validated to NOT start with `$` (which would land\n * `$where` and other server-side JS evaluation operators directly in the\n * query — an injection vector for AI/user-generated predicates).\n *\n * @example\n * ```ts\n * predicateToMongo({ age: { $gte: 18 }, status: { $in: [\"active\", \"pending\"] } })\n * // → { age: { $gte: 18 }, status: { $in: [\"active\", \"pending\"] } }\n *\n * predicateToMongo({ name: { $startsWith: \"Al\" } })\n * // → { name: { $regex: \"^Al\" } }\n *\n * predicateToMongo({ $any: [{ tier: \"gold\" }, { score: { $gte: 100 } }] })\n * // → { $or: [{ tier: \"gold\" }, { score: { $gte: 100 } }] }\n * ```\n */\nexport function predicateToMongo<F = Record<string, unknown>>(\n predicate: FactPredicate<F>,\n options: PredicateToMongoOptions = {},\n): Record<string, unknown> {\n return buildQuery(predicate, options, 0);\n}\n","/**\n * Compile a `FactPredicate` to a PostgREST querystring.\n *\n * PostgREST's filter grammar is column-scoped: `?age=gte.18&status=in.(active,pending)`.\n * Logical groups use `and=(...)` / `or=(...)` / `not.and=(...)`.\n *\n * Reference: https://postgrest.org/en/stable/api.html#operators\n */\n\nimport { MAX_PREDICATE_DEPTH } from \"./predicate.js\";\nimport {\n PREDICATE_OPERATORS,\n type FactPredicate,\n} from \"./types/predicate.js\";\n\nexport interface PredicateToPostgrestOptions {\n /** Allowlist of column keys the predicate may reference. */\n allowedKeys?: readonly string[];\n /**\n * Encoding mode for the returned string.\n * - `\"querystring\"` (default): a full querystring without a leading `?`,\n * with each clause value URL-encoded — drops straight into `fetch`.\n * - `\"raw\"`: the same content, leaving `(`, `)`, `,` unencoded for\n * readability. Use this only when you'll encode the result yourself.\n */\n mode?: \"querystring\" | \"raw\";\n}\n\nconst IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nfunction assertColumn(name: string, allowed?: readonly string[]): void {\n if (typeof name !== \"string\" || !IDENT_RE.test(name)) {\n throw new Error(\n `[Directive] predicateToPostgrest: invalid column identifier \"${name}\"`,\n );\n }\n if (allowed && !allowed.includes(name)) {\n throw new Error(\n `[Directive] predicateToPostgrest: column \"${name}\" is not in the allowedKeys list — add it to options.allowedKeys or remove it from the predicate`,\n );\n }\n}\n\nfunction assertNoSiblingKeys(spec: Record<string, unknown>, combinator: string): void {\n const sibs = Object.keys(spec).filter((k) => k !== combinator);\n if (sibs.length > 0) {\n throw new Error(\n `[Directive] predicateToPostgrest: ${combinator} cannot coexist with sibling keys (${sibs.join(\", \")}) — wrap them in $all together, or move them inside the ${combinator} children`,\n );\n }\n}\n\n/** Encode a single PostgREST value. Strings with reserved chars get quoted. */\nfunction encodeValue(v: unknown): string {\n if (v === null || v === undefined) return \"null\";\n if (typeof v === \"boolean\") return v ? \"true\" : \"false\";\n if (typeof v === \"number\" || typeof v === \"bigint\") return String(v);\n if (v instanceof Date) return v.toISOString();\n if (typeof v === \"string\") {\n // PostgREST treats `,` `.` `(` `)` and `:` as syntax; quote any\n // string containing them. Inside quotes, `\"` → `\\\"` and `\\` → `\\\\`.\n if (/[,.():\"\\\\\\s]/.test(v)) {\n return `\"${v.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n }\n\n return v;\n }\n throw new Error(\n `[Directive] predicateToPostgrest: cannot encode value of type ${typeof v}`,\n );\n}\n\nfunction encodeList(arr: readonly unknown[]): string {\n return `(${arr.map(encodeValue).join(\",\")})`;\n}\n\n/** Escape `\\`, `%`, `_`, `*` so they match literally instead of as wildcards. */\nfunction escapeLikeOperand(s: string): string {\n return s.replace(/[\\\\%_*]/g, \"\\\\$&\");\n}\n\n/**\n * Render the value side of one operator. Returns a string like\n * `gte.18` or `in.(a,b)` — without the column name.\n */\nfunction renderOp(op: string, operand: unknown): string {\n switch (op) {\n case \"$eq\":\n return `eq.${encodeValue(operand)}`;\n case \"$ne\":\n return `neq.${encodeValue(operand)}`;\n case \"$gt\":\n return `gt.${encodeValue(operand)}`;\n case \"$gte\":\n return `gte.${encodeValue(operand)}`;\n case \"$lt\":\n return `lt.${encodeValue(operand)}`;\n case \"$lte\":\n return `lte.${encodeValue(operand)}`;\n case \"$in\":\n if (!Array.isArray(operand)) {\n throw new Error(`[Directive] predicateToPostgrest: $in operand must be an array`);\n }\n return `in.${encodeList(operand)}`;\n case \"$nin\":\n if (!Array.isArray(operand)) {\n throw new Error(`[Directive] predicateToPostgrest: $nin operand must be an array`);\n }\n return `not.in.${encodeList(operand)}`;\n case \"$exists\":\n return operand === true ? \"not.is.null\" : \"is.null\";\n case \"$startsWith\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToPostgrest: $startsWith operand must be a string`,\n );\n }\n return `like.${encodeValue(escapeLikeOperand(operand) + \"*\")}`;\n case \"$endsWith\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToPostgrest: $endsWith operand must be a string`,\n );\n }\n return `like.${encodeValue(\"*\" + escapeLikeOperand(operand))}`;\n case \"$contains\":\n if (typeof operand !== \"string\") {\n throw new Error(\n `[Directive] predicateToPostgrest: $contains expects a string operand (array containment is the cs operator with a different shape — out of scope for v1)`,\n );\n }\n return `like.${encodeValue(\"*\" + escapeLikeOperand(operand) + \"*\")}`;\n case \"$matches\":\n if (operand instanceof RegExp) {\n const o = operand.flags.includes(\"i\") ? \"imatch\" : \"match\";\n\n return `${o}.${encodeValue(operand.source)}`;\n }\n if (typeof operand === \"string\") {\n return `match.${encodeValue(operand)}`;\n }\n throw new Error(\n `[Directive] predicateToPostgrest: $matches operand must be a RegExp or string`,\n );\n // $between is handled at the build() level by decomposing into $gte + $lte.\n case \"$changed\":\n throw new Error(\n `[Directive] predicateToPostgrest: $changed is an effects-only operator — no server query equivalent`,\n );\n default:\n throw new Error(\n `[Directive] predicateToPostgrest: unknown operator \"${op}\" — known: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\nfunction isOperatorObject(v: unknown): v is Record<string, unknown> {\n if (!isPlainObject(v)) return false;\n const keys = Object.keys(v);\n if (keys.length === 0) return false;\n for (const k of keys) {\n if (!k.startsWith(\"$\")) return false;\n }\n\n return true;\n}\n\nfunction colClause(column: string, opAndValue: string): string {\n return `${column}=${opAndValue}`;\n}\n\nfunction groupClause(\n logical: \"and\" | \"or\" | \"not.and\" | \"not.or\",\n parts: string[],\n): string {\n return `${logical}=(${parts.join(\",\")})`;\n}\n\n/**\n * Render one operator inside one column. For `$between`, decomposes into\n * two clauses ($gte + $lte) so the predicate's portability promise holds.\n */\nfunction renderColumnOps(\n column: string,\n op: string,\n operand: unknown,\n atTop: boolean,\n): string[] {\n if (op === \"$between\") {\n if (!Array.isArray(operand) || operand.length !== 2) {\n throw new Error(\n `[Directive] predicateToPostgrest: $between operand must be a [low, high] tuple`,\n );\n }\n const lo = atTop\n ? colClause(column, renderOp(\"$gte\", operand[0]))\n : `${column}.${renderOp(\"$gte\", operand[0])}`;\n const hi = atTop\n ? colClause(column, renderOp(\"$lte\", operand[1]))\n : `${column}.${renderOp(\"$lte\", operand[1])}`;\n\n return [lo, hi];\n }\n\n return [\n atTop\n ? colClause(column, renderOp(op, operand))\n : `${column}.${renderOp(op, operand)}`,\n ];\n}\n\n/**\n * Convert a predicate into PostgREST clause strings. Top-level returns a\n * list of `column=value` pairs (joined by `&`); nested returns\n * grouped/clause-list strings depending on the parent combinator.\n *\n * @param atTop When true, clauses are top-level (& separator).\n * When false, clauses are inside `and=(...)`/`or=(...)`\n * and must use `,` separator and `column.op.val` syntax.\n */\nfunction build(\n spec: unknown,\n allowed: readonly string[] | undefined,\n atTop: boolean,\n depth: number,\n): string[] {\n if (depth > MAX_PREDICATE_DEPTH) {\n throw new Error(\n `[Directive] predicateToPostgrest: predicate depth limit (${MAX_PREDICATE_DEPTH}) exceeded — flatten the predicate or check for a cyclic spec object`,\n );\n }\n if (spec === null || typeof spec !== \"object\") {\n throw new Error(\n `[Directive] predicateToPostgrest: predicate must be an object or array`,\n );\n }\n\n if (Array.isArray(spec)) {\n const out: string[] = [];\n for (const clause of spec) {\n if (\n !clause ||\n typeof clause !== \"object\" ||\n !(\"fact\" in clause) ||\n !(\"op\" in clause)\n ) {\n throw new Error(\n `[Directive] predicateToPostgrest: array-form clause must be { fact, op, value }`,\n );\n }\n const c = clause as { fact: string; op: string; value: unknown };\n assertColumn(c.fact, allowed);\n out.push(...renderColumnOps(c.fact, c.op, c.value, atTop));\n }\n\n return out;\n }\n\n if (\"$all\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$all\");\n const arr = (spec as { $all: unknown[] }).$all;\n if (!Array.isArray(arr)) {\n throw new Error(`[Directive] predicateToPostgrest: $all must be an array`);\n }\n if (atTop) {\n const out: string[] = [];\n for (const child of arr) {\n out.push(...build(child, allowed, true, depth + 1));\n }\n\n return out;\n }\n const parts: string[] = [];\n for (const child of arr) {\n parts.push(...build(child, allowed, false, depth + 1));\n }\n\n return [groupClause(\"and\", parts)];\n }\n if (\"$any\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$any\");\n const arr = (spec as { $any: unknown[] }).$any;\n if (!Array.isArray(arr)) {\n throw new Error(`[Directive] predicateToPostgrest: $any must be an array`);\n }\n // Empty $any is tautological-false. PostgREST has no clean way to\n // express \"match nothing\"; pick a stable contradiction.\n if (arr.length === 0) {\n // pg's `id` exists on every base table — match a value no row can have.\n return atTop\n ? [\"id=is.null\", \"id=not.is.null\"]\n : [groupClause(\"and\", [\"id.is.null\", \"id.not.is.null\"])];\n }\n const parts: string[] = [];\n for (const child of arr) {\n parts.push(...build(child, allowed, false, depth + 1));\n }\n\n return [groupClause(\"or\", parts)];\n }\n if (\"$not\" in spec) {\n assertNoSiblingKeys(spec as Record<string, unknown>, \"$not\");\n const inner = (spec as { $not: unknown }).$not;\n const parts = build(inner, allowed, false, depth + 1);\n\n return [groupClause(\"not.and\", parts)];\n }\n\n // Object form\n const out: string[] = [];\n for (const [key, value] of Object.entries(spec as Record<string, unknown>)) {\n assertColumn(key, allowed);\n if (isOperatorObject(value)) {\n for (const [op, operand] of Object.entries(value)) {\n if (!PREDICATE_OPERATORS.has(op)) {\n throw new Error(\n `[Directive] predicateToPostgrest: unknown operator \"${op}\" on column \"${key}\" — known: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n out.push(...renderColumnOps(key, op, operand, atTop));\n }\n } else if (isPlainObject(value)) {\n throw new Error(\n `[Directive] predicateToPostgrest: nested predicate at \"${key}\" — single-table queries only`,\n );\n } else {\n out.push(...renderColumnOps(key, \"$eq\", value, atTop));\n }\n }\n\n return out;\n}\n\n/**\n * Encode a clause string per PostgREST URL conventions.\n *\n * Splits on first `=` so the column/logical name is preserved verbatim\n * (it's identifier-validated) and only the value side is URL-encoded.\n */\nfunction encodeClause(c: string): string {\n const eq = c.indexOf(\"=\");\n if (eq < 0) return encodeURIComponent(c);\n const key = c.slice(0, eq);\n const value = c.slice(eq + 1);\n\n return `${key}=${encodeURIComponent(value)}`;\n}\n\n/**\n * Compile a {@link FactPredicate} to a PostgREST querystring.\n *\n * @example\n * ```ts\n * predicateToPostgrest({ age: { $gte: 18 }, status: { $in: [\"active\", \"pending\"] } })\n * // → \"age=gte.18&status=in.%28active%2Cpending%29\"\n *\n * // Raw mode for debugging / building URLs by hand:\n * predicateToPostgrest({ age: { $gte: 18 } }, { mode: \"raw\" })\n * // → \"age=gte.18\"\n *\n * predicateToPostgrest({ $any: [{ tier: \"gold\" }, { score: { $gte: 100 } }] }, { mode: \"raw\" })\n * // → \"or=(tier.eq.gold,score.gte.100)\"\n * ```\n */\nexport function predicateToPostgrest<F = Record<string, unknown>>(\n predicate: FactPredicate<F>,\n options: PredicateToPostgrestOptions = {},\n): string {\n const mode = options.mode ?? \"querystring\";\n const clauses = build(predicate, options.allowedKeys, true, 0);\n if (clauses.length === 0) return \"\";\n\n return mode === \"raw\" ? clauses.join(\"&\") : clauses.map(encodeClause).join(\"&\");\n}\n","/**\n * Schema Type Builders\n *\n * Provides type-safe schema definitions with optional runtime validation.\n * Used to define fact types, derivation types, event payload types, etc.\n *\n * This module has no dependency on the facts store or tracking system.\n */\n\nimport isDevelopment from \"#is-development\";\nimport type { SchemaKindNode } from \"./schema-introspection.js\";\nimport type { SchemaType } from \"./types.js\";\n\n// ============================================================================\n// Schema Type Builders\n// ============================================================================\n\n/** Brand symbol for branded types */\ndeclare const Brand: unique symbol;\n\n/** Branded type - adds a unique brand to a base type */\nexport type Branded<T, B extends string> = T & { readonly [Brand]: B };\n\n/** Extended SchemaType with type name for better error messages */\nexport interface ExtendedSchemaType<T> extends SchemaType<T> {\n readonly _typeName?: string;\n readonly _default?: T | (() => T);\n readonly _transform?: (value: unknown) => T;\n readonly _description?: string;\n readonly _refinements?: Array<{\n predicate: (value: T) => boolean;\n message: string;\n }>;\n /** Mutable - set by array validators to indicate which element failed */\n _lastFailedIndex?: number;\n /** Optional metadata for debugging and devtools (never read on hot path). */\n readonly _meta?: import(\"./types/meta.js\").DefinitionMeta;\n /**\n * Structured kind discriminant used by introspection-time consumers\n * (`predicateFromIntent`, `doctor`, `predicateToZod`). Optional for\n * back-compat with legacy / third-party builders; when absent, the\n * introspection layer parses `_typeName` instead.\n */\n readonly _kind?: SchemaKindNode;\n}\n\n/** Create a schema type builder with optional type name */\nfunction createSchemaType<T>(\n validators: Array<(v: T) => boolean> = [],\n typeName?: string,\n defaultValue?: T | (() => T),\n transform?: (value: unknown) => T,\n description?: string,\n refinements?: Array<{ predicate: (value: T) => boolean; message: string }>,\n meta?: import(\"./types/meta.js\").DefinitionMeta,\n): ExtendedSchemaType<T> {\n return {\n _type: undefined as unknown as T,\n _validators: validators,\n _typeName: typeName,\n _default: defaultValue,\n _transform: transform,\n _description: description,\n _refinements: refinements,\n _meta: meta,\n validate(fn: (value: T) => boolean) {\n return createSchemaType(\n [...validators, fn],\n typeName,\n defaultValue,\n transform,\n description,\n refinements,\n meta,\n );\n },\n };\n}\n\n/** Chainable schema type with all common methods */\nexport interface ChainableSchemaType<T> extends ExtendedSchemaType<T> {\n default(value: T | (() => T)): ChainableSchemaType<T>;\n transform<U>(fn: (value: T) => U): ChainableSchemaType<U>;\n brand<B extends string>(): ChainableSchemaType<Branded<T, B>>;\n describe(description: string): ChainableSchemaType<T>;\n refine(\n predicate: (value: T) => boolean,\n message: string,\n ): ChainableSchemaType<T>;\n nullable(): ChainableSchemaType<T | null>;\n optional(): ChainableSchemaType<T | undefined>;\n /** Attach metadata for debugging and devtools. */\n meta(meta: import(\"./types/meta.js\").DefinitionMeta): ChainableSchemaType<T>;\n}\n\n/** Create a chainable schema type with common methods */\nfunction createChainableType<T>(\n validators: Array<(v: T) => boolean>,\n typeName: string,\n defaultValue?: T | (() => T),\n transform?: (value: unknown) => T,\n description?: string,\n refinements?: Array<{ predicate: (value: T) => boolean; message: string }>,\n fieldMeta?: import(\"./types/meta.js\").DefinitionMeta,\n): ChainableSchemaType<T> {\n const base = createSchemaType<T>(\n validators,\n typeName,\n defaultValue,\n transform,\n description,\n refinements,\n fieldMeta,\n );\n return {\n ...base,\n default(value: T | (() => T)) {\n return createChainableType(\n validators,\n typeName,\n value,\n transform,\n description,\n refinements,\n fieldMeta,\n );\n },\n transform<U>(fn: (value: T) => U) {\n const newTransform = (v: unknown) => {\n const intermediate = transform ? transform(v) : (v as T);\n return fn(intermediate);\n };\n return createChainableType<U>(\n [],\n typeName,\n undefined,\n newTransform as (v: unknown) => U,\n description,\n undefined,\n fieldMeta,\n );\n },\n brand<B extends string>() {\n return createChainableType<Branded<T, B>>(\n validators as Array<(v: Branded<T, B>) => boolean>,\n `Branded<${typeName}>`,\n defaultValue as Branded<T, B> | (() => Branded<T, B>),\n transform as (value: unknown) => Branded<T, B>,\n description,\n refinements as Array<{\n predicate: (value: Branded<T, B>) => boolean;\n message: string;\n }>,\n fieldMeta,\n );\n },\n describe(desc: string) {\n return createChainableType(\n validators,\n typeName,\n defaultValue,\n transform,\n desc,\n refinements,\n fieldMeta,\n );\n },\n refine(predicate: (value: T) => boolean, message: string) {\n const newRefinements = [...(refinements ?? []), { predicate, message }];\n return createChainableType(\n [...validators, predicate],\n typeName,\n defaultValue,\n transform,\n description,\n newRefinements,\n fieldMeta,\n );\n },\n nullable() {\n return createChainableType<T | null>(\n [\n (v): v is T | null =>\n v === null || validators.every((fn) => fn(v as T)),\n ],\n `${typeName} | null`,\n defaultValue as (T | null) | (() => T | null),\n transform as (value: unknown) => T | null,\n description,\n undefined,\n fieldMeta,\n );\n },\n optional() {\n return createChainableType<T | undefined>(\n [\n (v): v is T | undefined =>\n v === undefined || validators.every((fn) => fn(v as T)),\n ],\n `${typeName} | undefined`,\n defaultValue as (T | undefined) | (() => T | undefined),\n transform as (value: unknown) => T | undefined,\n description,\n undefined,\n fieldMeta,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableType(\n validators,\n typeName,\n defaultValue,\n transform,\n description,\n refinements,\n m,\n );\n },\n };\n}\n\n/**\n * Two-form union schema constructor.\n *\n * Hoisted out of the `t` object literal because the overload-cast pattern\n * (`(impl) as { ovl1; ovl2 }`) inside an object literal triggers a TS\n * declaration-emit \"implicitly has type any\" cycle. Annotating the const\n * with the explicit overload type breaks the cycle so DTS can emit `t`'s\n * shape without recursing through the runtime expression.\n *\n * @internal\n */\ntype UnionFn = {\n <T = unknown>(): ChainableSchemaType<T>;\n <T extends SchemaType<unknown>[]>(\n ...types: T\n ): ChainableSchemaType<T[number] extends SchemaType<infer U> ? U : never>;\n};\n\nconst unionImpl: UnionFn = (<T extends SchemaType<unknown>[]>(...types: T) => {\n if (types.length === 0) {\n return createChainableType<unknown>([], \"union\");\n }\n type UnionType = T[number] extends SchemaType<infer U> ? U : never;\n const typeNames = types.map(\n (schemaType) =>\n (schemaType as ExtendedSchemaType<unknown>)._typeName ?? \"unknown\",\n );\n return createChainableType<UnionType>(\n [\n (v): v is UnionType =>\n types.some((schemaType) => schemaType._validators.every((fn) => fn(v))),\n ],\n typeNames.join(\" | \"),\n );\n}) as UnionFn;\n\n/**\n * Schema type builders for defining fact types.\n *\n * @remarks\n * Each builder returns a chainable {@link ExtendedSchemaType} with validation\n * methods (`.min()`, `.max()`, `.pattern()`, etc.) and dev-mode runtime\n * type checking. Validators are tree-shaken in production builds.\n *\n * @example\n * ```typescript\n * const module = createModule(\"example\", {\n * schema: {\n * name: t.string(),\n * age: t.number().min(0).max(150),\n * active: t.boolean(),\n * tags: t.array<string>().of(t.string()),\n * user: t.object<{ id: string; email: string }>(),\n * },\n * });\n * ```\n *\n * @public\n */\nexport const t = {\n /**\n * Create a string schema type.\n *\n * @example\n * ```typescript\n * // Basic string\n * schema: { name: t.string() }\n *\n * // String literal union (for type safety)\n * schema: { phase: t.string<\"red\" | \"green\" | \"yellow\">() }\n *\n * // With custom validation\n * schema: { email: t.string().validate(s => s.includes(\"@\")) }\n *\n * // With transform\n * schema: { trimmed: t.string().transform(s => s.trim()) }\n *\n * // With brand\n * schema: { userId: t.string().brand<\"UserId\">() }\n * ```\n */\n string<T extends string = string>() {\n type ChainableString = ChainableSchemaType<T> & {\n minLength(n: number): ChainableString;\n maxLength(n: number): ChainableString;\n pattern(regex: RegExp): ChainableString;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableString;\n };\n\n const createChainableString = (\n validators: Array<(v: T) => boolean>,\n defaultValue?: T | (() => T),\n transform?: (value: unknown) => T,\n description?: string,\n refinements?: Array<{\n predicate: (value: T) => boolean;\n message: string;\n }>,\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableString => {\n const chainable = createChainableType<T>(\n validators,\n \"string\",\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n return {\n ...chainable,\n minLength(n: number) {\n return createChainableString(\n [...validators, (v) => (v as string).length >= n],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n maxLength(n: number) {\n return createChainableString(\n [...validators, (v) => (v as string).length <= n],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n pattern(regex: RegExp) {\n return createChainableString(\n [...validators, (v) => regex.test(v as string)],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n default(value: T | (() => T)) {\n return createChainableString(\n validators,\n value,\n transform,\n description,\n refinements,\n fm,\n );\n },\n describe(desc: string) {\n return createChainableString(\n validators,\n defaultValue,\n transform,\n desc,\n refinements,\n fm,\n );\n },\n refine(predicate: (value: T) => boolean, message: string) {\n const newRefinements = [\n ...(refinements ?? []),\n { predicate, message },\n ];\n return createChainableString(\n [...validators, predicate],\n defaultValue,\n transform,\n description,\n newRefinements,\n fm,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableString(\n validators,\n defaultValue,\n transform,\n description,\n refinements,\n m,\n );\n },\n };\n };\n\n return createChainableString([(v): v is T => typeof v === \"string\"]);\n },\n\n /**\n * Create a number schema type with optional min/max constraints.\n *\n * @example\n * ```typescript\n * // Basic number\n * schema: { count: t.number() }\n *\n * // With range constraints\n * schema: { age: t.number().min(0).max(150) }\n *\n * // With custom validation\n * schema: { even: t.number().validate(n => n % 2 === 0) }\n *\n * // With default\n * schema: { count: t.number().default(0) }\n *\n * // With transform (from string)\n * schema: { age: t.number().transform(v => parseInt(String(v), 10)) }\n * ```\n */\n number() {\n type ChainableNumber = ChainableSchemaType<number> & {\n min(n: number): ChainableNumber;\n max(n: number): ChainableNumber;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableNumber;\n };\n\n const createChainableNumber = (\n validators: Array<(v: number) => boolean>,\n defaultValue?: number | (() => number),\n transform?: (value: unknown) => number,\n description?: string,\n refinements?: Array<{\n predicate: (value: number) => boolean;\n message: string;\n }>,\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableNumber => {\n const chainable = createChainableType<number>(\n validators,\n \"number\",\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n return {\n ...chainable,\n min(n: number) {\n return createChainableNumber(\n [...validators, (v) => v >= n],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n max(n: number) {\n return createChainableNumber(\n [...validators, (v) => v <= n],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n default(value: number | (() => number)) {\n return createChainableNumber(\n validators,\n value,\n transform,\n description,\n refinements,\n fm,\n );\n },\n describe(desc: string) {\n return createChainableNumber(\n validators,\n defaultValue,\n transform,\n desc,\n refinements,\n fm,\n );\n },\n refine(predicate: (value: number) => boolean, message: string) {\n const newRefinements = [\n ...(refinements ?? []),\n { predicate, message },\n ];\n return createChainableNumber(\n [...validators, predicate],\n defaultValue,\n transform,\n description,\n newRefinements,\n fm,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableNumber(\n validators,\n defaultValue,\n transform,\n description,\n refinements,\n m,\n );\n },\n };\n };\n return createChainableNumber([(v) => typeof v === \"number\"]);\n },\n\n /**\n * Create a boolean schema type.\n *\n * @example\n * ```typescript\n * schema: {\n * active: t.boolean(),\n * verified: t.boolean().default(false),\n * }\n * ```\n */\n boolean() {\n return createChainableType<boolean>(\n [(v) => typeof v === \"boolean\"],\n \"boolean\",\n );\n },\n\n /**\n * Create an array schema type.\n * Can be used with or without element validation:\n * - `t.array<string>()` - Type-only, no element validation\n * - `t.array<string>().of(t.string())` - With element validation\n */\n array<T>() {\n type ChainableArray = ChainableSchemaType<T[]> & {\n of(elementType: SchemaType<T>): ChainableArray;\n nonEmpty(): ChainableArray;\n maxLength(n: number): ChainableArray;\n minLength(n: number): ChainableArray;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableArray;\n _lastFailedIndex?: number;\n };\n\n const createChainableArray = (\n validators: Array<(v: T[]) => boolean>,\n elementType?: SchemaType<T>,\n defaultValue?: T[] | (() => T[]),\n description?: string,\n indexRef?: { value: number },\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableArray => {\n const chainable = createChainableType<T[]>(\n validators,\n \"array\",\n defaultValue,\n undefined,\n description,\n undefined,\n fm,\n );\n // Use ref for storing failed index (shared with validator closure)\n const ref = indexRef ?? { value: -1 };\n const result: ChainableArray = {\n ...chainable,\n get _lastFailedIndex() {\n return ref.value;\n },\n set _lastFailedIndex(v: number) {\n ref.value = v;\n },\n of(et: SchemaType<T>) {\n const newRef = { value: -1 };\n return createChainableArray(\n [\n ...validators,\n (v) => {\n for (let i = 0; i < v.length; i++) {\n if (!et._validators.every((validator) => validator(v[i]))) {\n newRef.value = i;\n return false;\n }\n }\n return true;\n },\n ],\n et,\n defaultValue,\n description,\n newRef,\n fm,\n );\n },\n nonEmpty() {\n return createChainableArray(\n [...validators, (v) => v.length > 0],\n elementType,\n defaultValue,\n description,\n ref,\n fm,\n );\n },\n maxLength(n: number) {\n return createChainableArray(\n [...validators, (v) => v.length <= n],\n elementType,\n defaultValue,\n description,\n ref,\n fm,\n );\n },\n minLength(n: number) {\n return createChainableArray(\n [...validators, (v) => v.length >= n],\n elementType,\n defaultValue,\n description,\n ref,\n fm,\n );\n },\n default(value: T[] | (() => T[])) {\n return createChainableArray(\n validators,\n elementType,\n value,\n description,\n ref,\n fm,\n );\n },\n describe(desc: string) {\n return createChainableArray(\n validators,\n elementType,\n defaultValue,\n desc,\n ref,\n fm,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableArray(\n validators,\n elementType,\n defaultValue,\n description,\n ref,\n m,\n );\n },\n };\n return result;\n };\n return createChainableArray([(v) => Array.isArray(v)]);\n },\n\n /**\n * Create an object schema type for any complex value.\n * Can be used with or without shape validation:\n * - `t.object<User>()` - Type-only, no property validation\n * - `t.object<User>().shape({ name: t.string(), age: t.number() })` - With property validation\n *\n * For arrays, prefer `t.array<T>()` which adds `Array.isArray` validation.\n */\n object<T>() {\n type ChainableObject = ChainableSchemaType<T> & {\n shape(schema: { [K in keyof T]?: SchemaType<T[K]> }): ChainableObject;\n nonNull(): ChainableObject;\n hasKeys(...keys: string[]): ChainableObject;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableObject;\n };\n\n const createChainableObject = (\n validators: Array<(v: T) => boolean>,\n defaultValue?: T | (() => T),\n description?: string,\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableObject => {\n const chainable = createChainableType<T>(\n validators,\n \"object\",\n defaultValue,\n undefined,\n description,\n undefined,\n fm,\n );\n return {\n ...chainable,\n shape(shapeSchema: { [K in keyof T]?: SchemaType<T[K]> }) {\n return createChainableObject(\n [\n ...validators,\n (v) => {\n for (const [key, schemaType] of Object.entries(shapeSchema)) {\n const value = (v as Record<string, unknown>)[key];\n const schemaT = schemaType as SchemaType<unknown>;\n if (\n schemaT &&\n !schemaT._validators.every((validator) => validator(value))\n ) {\n return false;\n }\n }\n return true;\n },\n ],\n defaultValue,\n description,\n fm,\n );\n },\n nonNull() {\n return createChainableObject(\n [...validators, (v) => v !== null && v !== undefined],\n defaultValue,\n description,\n fm,\n );\n },\n hasKeys(...keys: string[]) {\n return createChainableObject(\n [\n ...validators,\n (v) => keys.every((k) => k in (v as Record<string, unknown>)),\n ],\n defaultValue,\n description,\n fm,\n );\n },\n default(value: T | (() => T)) {\n return createChainableObject(validators, value, description, fm);\n },\n describe(desc: string) {\n return createChainableObject(validators, defaultValue, desc, fm);\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableObject(\n validators,\n defaultValue,\n description,\n m,\n );\n },\n };\n };\n return createChainableObject([\n (v) => typeof v === \"object\" && v !== null && !Array.isArray(v),\n ]);\n },\n\n /**\n * Create an enum schema type for string literal unions.\n *\n * @example\n * ```typescript\n * // Define allowed values\n * schema: { status: t.enum(\"idle\", \"loading\", \"success\", \"error\") }\n *\n * // Type is inferred as \"idle\" | \"loading\" | \"success\" | \"error\"\n * ```\n */\n enum<T extends string>(...values: T[]) {\n if (isDevelopment && values.length === 0) {\n console.warn(\n \"[Directive] t.enum() called with no values - this will reject all strings\",\n );\n }\n const valueSet = new Set(values);\n return createChainableType<T>(\n [(v): v is T => typeof v === \"string\" && valueSet.has(v as T)],\n `enum(${values.join(\"|\")})`,\n );\n },\n\n /**\n * Create a literal schema type for exact value matching.\n *\n * @example\n * ```typescript\n * // Exact string match\n * schema: { type: t.literal(\"user\") }\n *\n * // Exact number match\n * schema: { version: t.literal(1) }\n *\n * // Exact boolean\n * schema: { enabled: t.literal(true) }\n * ```\n */\n literal<T extends string | number | boolean>(value: T) {\n return createChainableType<T>(\n [(v): v is T => v === value],\n `literal(${String(value)})`,\n );\n },\n\n /**\n * Create a nullable schema type (T | null).\n *\n * @example\n * ```typescript\n * // Nullable string\n * schema: { name: t.nullable(t.string()) }\n *\n * // Nullable object\n * schema: { user: t.nullable(t.object<User>()) }\n * ```\n */\n nullable<T>(innerType: SchemaType<T>) {\n const innerTypeName =\n (innerType as ExtendedSchemaType<T>)._typeName ?? \"unknown\";\n return createSchemaType<T | null>(\n [\n (v): v is T | null => {\n if (v === null) {\n return true;\n }\n return innerType._validators.every((validator) => validator(v as T));\n },\n ],\n `${innerTypeName} | null`,\n ) as SchemaType<T | null>;\n },\n\n /**\n * Create an optional schema type (T | undefined).\n *\n * @example\n * ```typescript\n * // Optional string\n * schema: { nickname: t.optional(t.string()) }\n *\n * // Optional number\n * schema: { age: t.optional(t.number()) }\n * ```\n */\n optional<T>(innerType: SchemaType<T>) {\n const innerTypeName =\n (innerType as ExtendedSchemaType<T>)._typeName ?? \"unknown\";\n return createSchemaType<T | undefined>(\n [\n (v): v is T | undefined => {\n if (v === undefined) {\n return true;\n }\n return innerType._validators.every((validator) => validator(v as T));\n },\n ],\n `${innerTypeName} | undefined`,\n ) as SchemaType<T | undefined>;\n },\n\n /**\n * Create a union schema type.\n *\n * **Two forms:**\n * - `t.union(t.string(), t.number())` — variadic schema args; the runtime\n * validator checks that the value matches at least one inner schema.\n * - `t.union<string | number | boolean>()` — generic-only form with no\n * schema args; the runtime validator accepts ANY value (mirrors\n * {@link unknown} plus generic narrowing). Use this for polymorphic\n * payloads where the union is too dynamic to enumerate as inner schemas\n * (e.g. an `UPDATE_FIELD` event whose `value` may be `string | number |\n * boolean | Date`).\n *\n * Chainable methods (`.validate`, `.transform`, `.default`, `.describe`,\n * `.refine`, `.optional`, `.nullable`) work the same for both forms.\n *\n * @example\n * ```typescript\n * // Variadic — runtime validation against inner schemas\n * schema: { value: t.union(t.string(), t.number()) }\n *\n * // Generic-only — type-only narrowing, runtime accepts any value\n * schema: {\n * payload: t.union<string | number | boolean>(),\n * }\n *\n * // Add a custom predicate via .validate when you still want a runtime check\n * schema: {\n * strict: t.union<string | number>().validate(\n * (v) => typeof v === \"string\" || typeof v === \"number\",\n * ),\n * }\n * ```\n */\n union: unionImpl,\n\n /**\n * Create a record schema type for dynamic key-value maps.\n *\n * @example\n * ```typescript\n * // Record with string values\n * schema: { metadata: t.record(t.string()) }\n *\n * // Record with number values\n * schema: { scores: t.record(t.number()) }\n * ```\n */\n record<V>(valueType: SchemaType<V>) {\n const valueTypeName =\n (valueType as ExtendedSchemaType<V>)._typeName ?? \"unknown\";\n return createChainableType<Record<string, V>>(\n [\n (v): v is Record<string, V> => {\n if (typeof v !== \"object\" || v === null || Array.isArray(v))\n return false;\n return Object.values(v).every((val) =>\n valueType._validators.every((validator) => validator(val)),\n );\n },\n ],\n `Record<string, ${valueTypeName}>`,\n );\n },\n\n /**\n * Create a tuple schema type for fixed-length arrays with specific types.\n *\n * @example\n * ```typescript\n * // [string, number] tuple\n * schema: { coord: t.tuple(t.string(), t.number()) }\n *\n * // [x, y, z] coordinates\n * schema: { position: t.tuple(t.number(), t.number(), t.number()) }\n * ```\n */\n tuple<T extends SchemaType<unknown>[]>(...types: T) {\n if (isDevelopment && types.length === 0) {\n console.warn(\n \"[Directive] t.tuple() called with no types - this will only accept empty arrays\",\n );\n }\n type TupleType = {\n [K in keyof T]: T[K] extends SchemaType<infer U> ? U : never;\n };\n const typeNames = types.map(\n (schemaType) =>\n (schemaType as ExtendedSchemaType<unknown>)._typeName ?? \"unknown\",\n );\n return createChainableType<TupleType>(\n [\n (v): v is TupleType => {\n if (!Array.isArray(v) || v.length !== types.length) {\n return false;\n }\n return types.every((schemaType, i) =>\n schemaType._validators.every((validator) => validator(v[i])),\n );\n },\n ],\n `[${typeNames.join(\", \")}]`,\n );\n },\n\n /**\n * Create a date schema type.\n *\n * @example\n * ```typescript\n * schema: { createdAt: t.date() }\n * ```\n */\n date() {\n return createChainableType<Date>(\n [(v): v is Date => v instanceof Date && !Number.isNaN(v.getTime())],\n \"Date\",\n );\n },\n\n /**\n * Create a UUID schema type.\n *\n * @example\n * ```typescript\n * schema: { id: t.uuid() }\n * ```\n */\n uuid() {\n const uuidRegex =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return createChainableType<string>(\n [(v): v is string => typeof v === \"string\" && uuidRegex.test(v)],\n \"uuid\",\n );\n },\n\n /**\n * Create an email schema type.\n *\n * @example\n * ```typescript\n * schema: { email: t.email() }\n * ```\n */\n email() {\n // Simple email regex - for comprehensive validation use Zod\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return createChainableType<string>(\n [(v): v is string => typeof v === \"string\" && emailRegex.test(v)],\n \"email\",\n );\n },\n\n /**\n * Create a URL schema type.\n *\n * @example\n * ```typescript\n * schema: { website: t.url() }\n * ```\n */\n url() {\n return createChainableType<string>(\n [\n (v): v is string => {\n if (typeof v !== \"string\") {\n return false;\n }\n try {\n new URL(v);\n return true;\n } catch {\n return false;\n }\n },\n ],\n \"url\",\n );\n },\n\n /**\n * Create a bigint schema type.\n *\n * @example\n * ```typescript\n * schema: { largeNumber: t.bigint() }\n * ```\n */\n bigint() {\n return createChainableType<bigint>(\n [(v): v is bigint => typeof v === \"bigint\"],\n \"bigint\",\n );\n },\n\n /**\n * Create an `any` schema type that accepts all values without validation.\n *\n * @example\n * ```typescript\n * schema: { payload: t.any() }\n * ```\n */\n // biome-ignore lint/suspicious/noExplicitAny: Intentional any type for schema builder\n any() {\n return createChainableType<any>([], \"any\");\n },\n\n /**\n * Create an `unknown` schema type that accepts all values without validation.\n * Prefer `t.unknown()` over `t.any()` for stricter downstream type checking.\n *\n * @example\n * ```typescript\n * schema: { data: t.unknown() }\n * ```\n */\n unknown() {\n return createChainableType<unknown>([], \"unknown\");\n },\n};\n","/**\n * Module - The declarative API for defining Directive modules\n *\n * Modules group related facts, constraints, resolvers, effects, and derivations.\n */\n\nimport isDevelopment from \"#is-development\";\nimport { BLOCKED_PROPS } from \"./tracking.js\";\nimport type {\n CrossModuleConstraintsDef,\n CrossModuleDeps,\n CrossModuleDerivationsDef,\n CrossModuleEffectsDef,\n DefinitionMeta,\n EffectsDef,\n Facts,\n ModuleDef,\n ModuleHooks,\n ModuleSchema,\n TypedConstraintsDef,\n TypedDerivationsDef,\n TypedEventsDef,\n TypedResolversDef,\n} from \"./types.js\";\n\n// ============================================================================\n// Module Configuration\n// ============================================================================\n\n/**\n * Module configuration with consolidated schema.\n *\n * derive and events are optional - omit them if your schema has empty derivations/events.\n */\nexport interface ModuleConfig<M extends ModuleSchema> {\n schema: M;\n init?: (facts: Facts<M[\"facts\"]>) => void;\n derive?: TypedDerivationsDef<M>;\n events?: TypedEventsDef<M>;\n effects?: EffectsDef<M[\"facts\"]>;\n constraints?: TypedConstraintsDef<M>;\n resolvers?: TypedResolversDef<M>;\n hooks?: ModuleHooks<M>;\n /** Optional metadata for debugging and devtools (never read on hot path). */\n meta?: DefinitionMeta;\n /** History configuration — controls which events create snapshots for undo/redo. */\n history?: {\n /** Events that create history snapshots. Omit to snapshot all events. */\n snapshotEvents?: Array<\n keyof (M[\"events\"] extends Record<string, unknown>\n ? M[\"events\"]\n : Record<string, never>) &\n string\n >;\n };\n}\n\n/**\n * Module configuration with cross-module dependencies for type-safe access\n * to other modules' facts in effects and constraints.\n *\n * When crossModuleDeps is provided:\n * - Own module facts: `facts.self.*`\n * - Cross-module facts: `facts.{dep}.*`\n *\n * @example\n * ```typescript\n * import { authSchema } from './auth';\n * import { dataSchema } from './data';\n *\n * const uiModule = createModule(\"ui\", {\n * schema: uiSchema,\n * crossModuleDeps: { auth: authSchema, data: dataSchema },\n * effects: {\n * onAuthChange: {\n * run: (facts) => {\n * facts.self.notifications // ✅ own module via \"self\"\n * facts.auth.isAuthenticated // ✅ cross-module (namespaced)\n * facts.data.users // ✅ cross-module (namespaced)\n * }\n * }\n * },\n * constraints: {\n * fetchWhenAuth: {\n * when: (facts) => facts.auth.isAuthenticated && facts.self.users.length === 0,\n * require: { type: \"FETCH_USERS\" },\n * }\n * }\n * });\n * ```\n */\nexport interface ModuleConfigWithDeps<\n M extends ModuleSchema,\n Deps extends CrossModuleDeps,\n> {\n schema: M;\n /**\n * Cross-module dependencies for type-safe access in derive/effects/constraints.\n *\n * **Access patterns by context:**\n * - `derive`, `effects`, `constraints`: Use `facts.self.*` for own module, `facts.{dep}.*` for cross-module\n * - `init`, `events`, `resolvers`: Use flat access (`facts.myFact`) - no cross-module access\n *\n * This separation ensures initialization and event handling stay scoped to own module,\n * while observers (derive/effects/constraints) can see across modules.\n *\n * @example\n * ```typescript\n * crossModuleDeps: { auth: authSchema },\n * init: (facts) => { facts.users = []; }, // flat access\n * derive: { count: (facts) => facts.self.users.length }, // facts.self.*\n * effects: { log: { run: (facts) => console.log(facts.auth.token) } }, // facts.{dep}.*\n * ```\n */\n crossModuleDeps: Deps;\n /** Initialize module facts. Uses flat access (`facts.myFact`) to ensure modules initialize independently. */\n init?: (facts: Facts<M[\"facts\"]>) => void;\n /** Derivations with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n derive?: CrossModuleDerivationsDef<M, Deps>;\n /** Event handlers. Uses flat access (`facts.myFact`) to keep mutations scoped to own module. */\n events?: TypedEventsDef<M>;\n /** Effects with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n effects?: CrossModuleEffectsDef<M, Deps>;\n /** Constraints with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n constraints?: CrossModuleConstraintsDef<M, Deps>;\n /** Resolvers. Uses flat access (`ctx.facts.myFact`) to keep async mutations scoped to own module. */\n resolvers?: TypedResolversDef<M>;\n hooks?: ModuleHooks<M>;\n /** Optional metadata for debugging and devtools (never read on hot path). */\n meta?: DefinitionMeta;\n /** History configuration — controls which events create snapshots for undo/redo. */\n history?: {\n /** Events that create history snapshots. Omit to snapshot all events. */\n snapshotEvents?: Array<\n keyof (M[\"events\"] extends Record<string, unknown>\n ? M[\"events\"]\n : Record<string, never>) &\n string\n >;\n };\n}\n\n// ============================================================================\n// Module Validation Helpers (dev-mode only)\n// ============================================================================\n\n/** Validate module ID follows naming conventions */\nfunction validateModuleId(id: string): void {\n if (!id || typeof id !== \"string\") {\n console.warn(\"[Directive] Module ID must be a non-empty string\");\n\n return;\n }\n if (!/^(__[a-z][a-z0-9_-]*|[a-z][a-z0-9-]*)$/i.test(id)) {\n console.warn(\n `[Directive] Module ID \"${id}\" should follow kebab-case convention (e.g., \"my-module\")`,\n );\n }\n}\n\n/** Warn when keys in `implKeys` are missing from `schemaKeys` and vice versa */\nfunction validateKeyAlignment(\n implKeys: Set<string>,\n schemaKeys: Set<string>,\n implLabel: string,\n schemaLabel: string,\n missingImplMessage: string,\n): void {\n for (const key of implKeys) {\n if (!schemaKeys.has(key)) {\n console.warn(\n `[Directive] ${implLabel} \"${key}\" not declared in ${schemaLabel}`,\n );\n }\n }\n for (const key of schemaKeys) {\n if (!implKeys.has(key)) {\n console.warn(\n `[Directive] ${schemaLabel}[\"${key}\"] ${missingImplMessage}`,\n );\n }\n }\n}\n\n/** Validate history.snapshotEvents reference valid event names */\nfunction validateSnapshotEvents(\n snapshotEvents: string[],\n schemaEvents: Record<string, unknown>,\n): void {\n if (snapshotEvents.length === 0) {\n console.warn(\n \"[Directive] history.snapshotEvents is an empty array — no events will create history snapshots. \" +\n \"Omit history.snapshotEvents entirely to snapshot all events, or list specific events.\",\n );\n }\n const schemaEventKeys = new Set(Object.keys(schemaEvents));\n for (const eventName of snapshotEvents) {\n if (!schemaEventKeys.has(eventName)) {\n console.warn(\n `[Directive] history.snapshotEvents entry \"${eventName}\" not declared in schema.events. ` +\n `Available events: ${[...schemaEventKeys].join(\", \") || \"(none)\"}`,\n );\n }\n }\n}\n\n/** Validate resolvers reference valid requirement types */\nfunction validateResolverRequirements(\n resolvers: Record<string, unknown>,\n requirements: Record<string, unknown>,\n): void {\n const requirementTypes = new Set(Object.keys(requirements));\n for (const [resolverName, resolver] of Object.entries(resolvers)) {\n const resolverDef = resolver as { requirement?: string };\n if (\n typeof resolverDef.requirement === \"string\" &&\n !requirementTypes.has(resolverDef.requirement)\n ) {\n console.warn(\n `[Directive] Resolver \"${resolverName}\" references unknown requirement type \"${resolverDef.requirement}\". ` +\n `Available types: ${[...requirementTypes].join(\", \") || \"(none)\"}`,\n );\n }\n }\n}\n\n/**\n * Throw when a module's fact key conflicts with a reserved namespace pivot\n * or evaluation alias used by the data-form predicate runtime. Two classes:\n *\n * - The cross-module namespace pivots — `self` and every declared\n * `crossModuleDeps` namespace. A fact named after a pivot would make\n * `prefixPredicateSpec` mis-route the pivot's nested predicate against\n * the pivot's namespace instead of treating it as a literal fact lookup.\n * - The evaluation aliases `prev` and `current` — reserved for the\n * previous/live snapshot scopes (`$changed`, clobber baselines). A fact\n * with one of these names would shadow the alias in those scopes.\n *\n * Thrown unconditionally — this is a structural integrity check, not a dev\n * convenience. Production users running into this would otherwise see silent\n * mis-routing.\n */\nfunction validatePivotNameConflicts<M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): void {\n const facts = (config.schema?.facts ?? {}) as Record<string, unknown>;\n const factKeys = Object.keys(facts);\n if (factKeys.length === 0) {\n return;\n }\n const reserved = new Set<string>([\"self\", \"prev\", \"current\"]);\n const deps =\n \"crossModuleDeps\" in config && config.crossModuleDeps\n ? Object.keys(\n config.crossModuleDeps as Record<string, unknown>,\n )\n : [];\n for (const depName of deps) {\n reserved.add(depName);\n }\n for (const key of factKeys) {\n if (reserved.has(key)) {\n throw new Error(\n `[Directive] module '${id}': fact key '${key}' conflicts with a reserved namespace pivot or evaluation alias (self / prev / current / a crossModuleDep namespace). Three fixes:\\n` +\n ` 1. Rename the fact (e.g. ${key}_)\\n` +\n ` 2. Remove '${key}' from this module's crossModuleDeps if it's not actually needed\\n` +\n ` 3. Move the fact under a wrapping namespace (t.object({ inner: ... }))`,\n );\n }\n }\n}\n\n/**\n * Reject constraint `owns` entries that name a reserved property — a\n * `BLOCKED_PROPS` key (`__proto__`, `constructor`, `prototype`) or a\n * `$`-prefixed key. Such names can never be owned fact slots, so the\n * clobber-detection binding would silently no-op. A structural integrity\n * check — runs unconditionally, not just in dev.\n */\nfunction validateOwnsKeys<M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): void {\n const constraints = config.constraints as\n | Record<string, { owns?: readonly string[] }>\n | undefined;\n if (!constraints) {\n return;\n }\n for (const [cid, constraint] of Object.entries(constraints)) {\n const owns = constraint?.owns;\n if (!owns) {\n continue;\n }\n for (const key of owns) {\n if (BLOCKED_PROPS.has(key) || key.startsWith(\"$\")) {\n throw new Error(\n `[Directive] module '${id}' constraint '${cid}': owns key '${key}' is reserved (BLOCKED_PROPS or $-prefixed)`,\n );\n }\n }\n }\n}\n\n/** Run all dev-mode validations for a module config */\nfunction validateModuleConfig<M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): void {\n validateModuleId(id);\n\n if (!config.schema) {\n console.warn(\"[Directive] Module schema is required\");\n } else if (!config.schema.facts) {\n console.warn(\"[Directive] Module schema.facts is required\");\n }\n\n validateKeyAlignment(\n new Set(Object.keys(config.derive ?? {})),\n new Set(Object.keys(config.schema?.derivations ?? {})),\n \"Derivation\",\n \"schema.derivations\",\n \"has no matching implementation in derive\",\n );\n\n validateKeyAlignment(\n new Set(Object.keys(config.events ?? {})),\n new Set(Object.keys(config.schema?.events ?? {})),\n \"Event\",\n \"schema.events\",\n \"has no matching handler in events\",\n );\n\n if (config.history?.snapshotEvents) {\n validateSnapshotEvents(\n config.history.snapshotEvents as string[],\n config.schema?.events ?? {},\n );\n }\n\n if (config.resolvers && config.schema?.requirements) {\n validateResolverRequirements(\n config.resolvers as Record<string, unknown>,\n config.schema.requirements,\n );\n }\n}\n\n// ============================================================================\n// createModule\n// ============================================================================\n\n/**\n * Create a module definition with full type inference.\n *\n * The consolidated schema provides:\n * - Derivation composition (`derived.otherDerivation` is typed)\n * - Event dispatch (`system.dispatch({ type: \"...\" })` has autocomplete)\n * - Resolver requirements (`req.payload` is typed based on requirement type)\n *\n * @param id - Unique module identifier (kebab-case recommended)\n * @param config - Module configuration including schema, init, derive, constraints, resolvers, etc.\n * @returns A frozen module definition ready for use with `createSystem`\n *\n * @example\n * ```ts\n * const trafficLight = createModule(\"traffic-light\", {\n * schema: {\n * facts: {\n * phase: t.string<\"red\" | \"green\" | \"yellow\">(),\n * elapsed: t.number(),\n * },\n * derivations: {\n * isRed: t.boolean(),\n * timeRemaining: t.number(),\n * },\n * events: {\n * tick: {},\n * setPhase: { phase: t.string<\"red\" | \"green\" | \"yellow\">() },\n * },\n * requirements: {\n * TRANSITION: { to: t.string<\"red\" | \"green\" | \"yellow\">() },\n * },\n * },\n * init: (facts) => {\n * facts.phase = \"red\";\n * facts.elapsed = 0;\n * },\n * derive: {\n * isRed: (facts) => facts.phase === \"red\",\n * timeRemaining: (facts, derived) => {\n * // derived.isRed is typed as boolean!\n * return derived.isRed ? 30 - facts.elapsed : 0;\n * },\n * },\n * events: {\n * tick: (facts) => { facts.elapsed += 1; },\n * setPhase: (facts, { phase }) => { facts.phase = phase; }, // phase is typed!\n * },\n * constraints: {\n * shouldTransition: {\n * when: (facts) => facts.phase === \"red\" && facts.elapsed > 30,\n * require: { type: \"TRANSITION\", to: \"green\" },\n * },\n * },\n * resolvers: {\n * transition: {\n * requirement: \"TRANSITION\",\n * resolve: async (req, ctx) => {\n * ctx.facts.phase = req.to; // req.to is typed!\n * ctx.facts.elapsed = 0;\n * },\n * },\n * },\n * hooks: {\n * // Optional: observe resolver failures owned by this module.\n * // Fires AFTER retries are exhausted and the engine has handled the error\n * // (error boundary, plugin emit, retry decision). Use it as a side-channel\n * // observer for module-local logging/telemetry — not for recovery.\n * onResolverError: (error, requirement, ctx) => {\n * console.warn(`[traffic-light] resolver failed for ${requirement.type}`, error);\n * },\n * },\n * });\n * ```\n *\n * @example With cross-module dependencies\n * ```ts\n * import { authSchema } from './auth';\n *\n * const dataModule = createModule(\"data\", {\n * schema: dataSchema,\n * crossModuleDeps: { auth: authSchema },\n * constraints: {\n * fetchWhenAuth: {\n * when: (facts) => {\n * // facts.self.* for own module, facts.auth.* for cross-module\n * return facts.auth.isAuthenticated && facts.self.users.length === 0;\n * },\n * require: { type: \"FETCH_USERS\" },\n * },\n * },\n * derive: {\n * canFetch: (facts) => facts.auth.isAuthenticated && facts.self.users.length === 0,\n * },\n * });\n * ```\n *\n * @public\n */\n// Overload 1: With crossModuleDeps\nexport function createModule<\n const M extends ModuleSchema,\n const Deps extends CrossModuleDeps,\n>(id: string, config: ModuleConfigWithDeps<M, Deps>): ModuleDef<M>;\n\n// Overload 2: Without crossModuleDeps (original signature)\nexport function createModule<const M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M>,\n): ModuleDef<M>;\n\n// Overload 3: Union (used by createModuleFactory)\nexport function createModule<const M extends ModuleSchema>(\n id: string,\n config: ModuleConfigWithDeps<M, CrossModuleDeps> | ModuleConfig<M>,\n): ModuleDef<M>;\n\n/** @internal Implementation overload — see public overloads above. */\nexport function createModule<const M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): ModuleDef<M> {\n // Pivot-name conflicts are a structural integrity check, not a dev\n // convenience — run unconditionally.\n validatePivotNameConflicts(id, config);\n\n // Reserved `owns` keys would silently disable clobber-detection — a\n // structural integrity check, run unconditionally.\n validateOwnsKeys(id, config);\n\n if (isDevelopment) {\n validateModuleConfig(id, config);\n }\n\n // Extract crossModuleDeps if present (for runtime proxy creation)\n const crossModuleDeps =\n \"crossModuleDeps\" in config ? config.crossModuleDeps : undefined;\n\n return {\n id,\n schema: config.schema,\n init: config.init,\n // Cast to TypedDerivationsDef for ModuleDef compatibility (runtime handles both types)\n derive: (config.derive ?? {}) as TypedDerivationsDef<M>,\n events: config.events ?? ({} as TypedEventsDef<M>),\n effects: config.effects as EffectsDef<M[\"facts\"]> | undefined,\n constraints: config.constraints as TypedConstraintsDef<M> | undefined,\n resolvers: config.resolvers,\n hooks: config.hooks,\n meta: config.meta,\n history: config.history,\n // Store crossModuleDeps for runtime proxy creation\n crossModuleDeps: crossModuleDeps as CrossModuleDeps | undefined,\n };\n}\n\n/**\n * Create a module factory that produces named instances from a single definition.\n * Useful for multi-instance UIs (tabs, panels, multi-tenant) where you need\n * isolated state from the same schema.\n *\n * @param config - Module configuration (same shape as `createModule` minus the `id`)\n * @returns A factory function that accepts a name and returns a `ModuleDef`\n *\n * @example\n * ```typescript\n * const chatRoom = createModuleFactory({\n * schema: {\n * facts: { messages: t.array<string>(), users: t.array<string>() },\n * derivations: { count: t.number() },\n * },\n * init: (facts) => { facts.messages = []; facts.users = []; },\n * derive: { count: (facts) => facts.messages.length },\n * });\n *\n * const system = createSystem({\n * modules: {\n * lobby: chatRoom(\"lobby\"),\n * support: chatRoom(\"support\"),\n * },\n * });\n * ```\n *\n * @public\n */\nexport function createModuleFactory<const M extends ModuleSchema>(\n config: ModuleConfig<M>,\n): (name: string) => ModuleDef<M>;\nexport function createModuleFactory<\n const M extends ModuleSchema,\n const Deps extends CrossModuleDeps,\n>(config: ModuleConfigWithDeps<M, Deps>): (name: string) => ModuleDef<M>;\n/** @internal Implementation overload — see public overloads above. */\nexport function createModuleFactory<const M extends ModuleSchema>(\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): (name: string) => ModuleDef<M> {\n // Pass config directly — createModule's implementation overload handles both types.\n // Do NOT cast to ModuleConfig<M> which would strip crossModuleDeps.\n return (name: string) => createModule(name, config);\n}\n","/**\n * Requirement Status Utilities\n *\n * Provides reactive tracking of requirement status for UI feedback.\n */\n\nimport type { Plugin, RequirementWithId } from \"../core/types.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Status of a requirement type */\nexport interface RequirementTypeStatus {\n /** Number of pending (unmet) requirements of this type */\n pending: number;\n /** Number of inflight (being resolved) requirements of this type */\n inflight: number;\n /** Number of failed requirements of this type */\n failed: number;\n /** Whether any requirements of this type are loading (pending or inflight) */\n isLoading: boolean;\n /** Whether any requirements of this type have failed */\n hasError: boolean;\n /** Last error for this type (if any) */\n lastError: Error | null;\n}\n\n/** Status tracking state */\ninterface StatusState {\n pending: Map<string, Set<string>>; // type -> set of requirement IDs\n inflight: Map<string, Set<string>>; // type -> set of requirement IDs\n failed: Map<string, Set<string>>; // type -> set of requirement IDs\n errors: Map<string, Error>; // type -> last error\n listeners: Set<() => void>;\n}\n\n// ============================================================================\n// Requirement Status Plugin\n// ============================================================================\n\n/**\n * Create a plugin that tracks requirement status for reactive UI updates.\n *\n * @example\n * ```typescript\n * import { createRequirementStatusPlugin } from '@directive-run/core';\n *\n * const statusPlugin = createRequirementStatusPlugin();\n *\n * const system = createSystem({\n * modules: [myModule],\n * plugins: [statusPlugin.plugin],\n * });\n *\n * // Get status for a requirement type\n * const status = statusPlugin.getStatus(\"FETCH_USER\");\n * console.log(status.isLoading, status.hasError);\n *\n * // Subscribe to status changes\n * const unsubscribe = statusPlugin.subscribe(() => {\n * console.log(\"Status changed:\", statusPlugin.getStatus(\"FETCH_USER\"));\n * });\n * ```\n */\nexport function createRequirementStatusPlugin(): {\n plugin: Plugin<never>;\n getStatus: (type: string) => RequirementTypeStatus;\n getAllStatus: () => Map<string, RequirementTypeStatus>;\n subscribe: (listener: () => void) => () => void;\n reset: () => void;\n} {\n const state: StatusState = {\n pending: new Map(),\n inflight: new Map(),\n failed: new Map(),\n errors: new Map(),\n listeners: new Set(),\n };\n\n /** Notify all listeners */\n function notify(): void {\n for (const listener of state.listeners) {\n listener();\n }\n }\n\n /** Get or create a set for a type in a map */\n function getOrCreateSet(\n map: Map<string, Set<string>>,\n type: string,\n ): Set<string> {\n let set = map.get(type);\n if (!set) {\n set = new Set();\n map.set(type, set);\n }\n return set;\n }\n\n /** Get status for a requirement type */\n function getStatus(type: string): RequirementTypeStatus {\n const pendingSet = state.pending.get(type) ?? new Set();\n const inflightSet = state.inflight.get(type) ?? new Set();\n const failedSet = state.failed.get(type) ?? new Set();\n const lastError = state.errors.get(type) ?? null;\n\n return {\n pending: pendingSet.size,\n inflight: inflightSet.size,\n failed: failedSet.size,\n isLoading: pendingSet.size > 0 || inflightSet.size > 0,\n hasError: failedSet.size > 0,\n lastError,\n };\n }\n\n /** Get status for all tracked types */\n function getAllStatus(): Map<string, RequirementTypeStatus> {\n const allTypes = new Set([\n ...state.pending.keys(),\n ...state.inflight.keys(),\n ...state.failed.keys(),\n ]);\n\n const result = new Map<string, RequirementTypeStatus>();\n for (const type of allTypes) {\n result.set(type, getStatus(type));\n }\n return result;\n }\n\n /** Subscribe to status changes */\n function subscribe(listener: () => void): () => void {\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n }\n\n /** Reset all status */\n function reset(): void {\n state.pending.clear();\n state.inflight.clear();\n state.failed.clear();\n state.errors.clear();\n notify();\n }\n\n const plugin: Plugin<never> = {\n name: \"requirement-status\",\n\n onRequirementCreated(req: RequirementWithId) {\n const type = req.requirement.type;\n getOrCreateSet(state.pending, type).add(req.id);\n // Clear from failed when a new requirement is created\n state.failed.get(type)?.delete(req.id);\n notify();\n },\n\n onResolverStart(_resolver: string, req: RequirementWithId) {\n const type = req.requirement.type;\n // Move from pending to inflight\n state.pending.get(type)?.delete(req.id);\n getOrCreateSet(state.inflight, type).add(req.id);\n notify();\n },\n\n onResolverComplete(_resolver: string, req: RequirementWithId) {\n const type = req.requirement.type;\n // Remove from inflight\n state.inflight.get(type)?.delete(req.id);\n state.pending.get(type)?.delete(req.id);\n notify();\n },\n\n onResolverError(_resolver: string, req: RequirementWithId, error: unknown) {\n const type = req.requirement.type;\n // Move from inflight to failed\n state.inflight.get(type)?.delete(req.id);\n getOrCreateSet(state.failed, type).add(req.id);\n state.errors.set(\n type,\n error instanceof Error ? error : new Error(String(error)),\n );\n notify();\n },\n\n onResolverCancel(_resolver: string, req: RequirementWithId) {\n const type = req.requirement.type;\n // Remove from all tracking\n state.pending.get(type)?.delete(req.id);\n state.inflight.get(type)?.delete(req.id);\n notify();\n },\n\n onRequirementMet(req: RequirementWithId) {\n const type = req.requirement.type;\n // Clean up when requirement is met\n state.pending.get(type)?.delete(req.id);\n state.inflight.get(type)?.delete(req.id);\n notify();\n },\n };\n\n return {\n plugin,\n getStatus,\n getAllStatus,\n subscribe,\n reset,\n };\n}\n\n// ============================================================================\n// React Hook Helper (for use with React adapter)\n// ============================================================================\n\n/**\n * Create a hook factory for requirement status.\n * This is designed to be used with React's useSyncExternalStore.\n *\n * @example\n * ```typescript\n * import { useSyncExternalStore } from 'react';\n * import { createRequirementStatusPlugin, createStatusHook } from '@directive-run/core';\n *\n * const statusPlugin = createRequirementStatusPlugin();\n * const useRequirementStatus = createStatusHook(statusPlugin);\n *\n * function MyComponent() {\n * const status = useRequirementStatus(\"FETCH_USER\");\n * if (status.isLoading) return <Spinner />;\n * if (status.hasError) return <Error error={status.lastError} />;\n * return <Content />;\n * }\n * ```\n */\nexport function createStatusHook(\n statusPlugin: ReturnType<typeof createRequirementStatusPlugin>,\n): (type: string) => RequirementTypeStatus {\n // This returns a function that can be used with useSyncExternalStore\n // The actual hook implementation would be in the React adapter\n return (type: string) => statusPlugin.getStatus(type);\n}\n","/**\n * System with Status Plugin Helper\n *\n * Convenience function for creating a system with status tracking enabled.\n */\n\nimport { createSystem } from \"../core/system.js\";\nimport type {\n ErrorBoundaryConfig,\n ModuleDef,\n ModuleSchema,\n Plugin,\n SingleModuleSystem,\n TraceOption,\n} from \"../core/types.js\";\nimport { createRequirementStatusPlugin } from \"./requirement-status.js\";\n\n/** Options for createSystemWithStatus */\nexport interface CreateSystemWithStatusOptions<M extends ModuleSchema> {\n /** The module to use for the system */\n module: ModuleDef<M>;\n /** Additional plugins to include alongside the status plugin */\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic contravariance issues\n plugins?: Plugin<any>[];\n /** Trace: per-run reconciliation changelog */\n trace?: TraceOption;\n /** Error boundary configuration */\n errorBoundary?: ErrorBoundaryConfig;\n /** Tick interval in milliseconds */\n tickMs?: number;\n /** Enable zero-config mode */\n zeroConfig?: boolean;\n /** Initial facts to set on the system */\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies by module\n initialFacts?: Record<string, any>;\n}\n\n/** Return type for createSystemWithStatus */\nexport interface SystemWithStatus<M extends ModuleSchema> {\n /**\n * The Directive system instance.\n * This is a SingleModuleSystem - use system.facts, system.dispatch(), etc.\n */\n system: SingleModuleSystem<M>;\n /** The status plugin for use with useRequirementStatus hooks */\n statusPlugin: ReturnType<typeof createRequirementStatusPlugin>;\n}\n\n/**\n * Create a Directive system with a status plugin pre-configured.\n *\n * This is a convenience wrapper around `createSystem` and `createRequirementStatusPlugin`\n * that handles the wiring automatically. The status plugin is added to the system's\n * plugins array so it receives lifecycle events.\n *\n * @param options - System configuration options\n * @returns An object containing both the system and the statusPlugin\n *\n * @example\n * ```tsx\n * import { createSystemWithStatus } from '@directive-run/core';\n * import { useRequirementStatus, useFact } from '@directive-run/react';\n *\n * // Simple setup - no provider needed\n * const { system, statusPlugin } = createSystemWithStatus({\n * module: myModule,\n * });\n * system.start();\n *\n * function App() {\n * const data = useFact(system, \"data\");\n * return <LoadingIndicator />;\n * }\n *\n * function LoadingIndicator() {\n * const status = useRequirementStatus(statusPlugin, \"FETCH_DATA\");\n * if (status.isLoading) return <Spinner />;\n * if (status.hasError) return <Error message={status.lastError?.message} />;\n * return <Content />;\n * }\n * ```\n */\nexport function createSystemWithStatus<M extends ModuleSchema>(\n options: CreateSystemWithStatusOptions<M>,\n): SystemWithStatus<M> {\n // Create the status plugin\n const statusPlugin = createRequirementStatusPlugin();\n\n // Add the plugin to the options\n const existingPlugins = options.plugins ?? [];\n\n // Create the system with the status plugin included\n // Use type assertion to bypass overload resolution issues\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const allPlugins = [...existingPlugins, statusPlugin.plugin] as Plugin<any>[];\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const system = createSystem({\n module: options.module,\n plugins: allPlugins,\n trace: options.trace,\n errorBoundary: options.errorBoundary,\n tickMs: options.tickMs,\n zeroConfig: options.zeroConfig,\n initialFacts: options.initialFacts,\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n } as any);\n\n return {\n // The system returned by createSystem with a single module is a SingleModuleSystem\n system: system as SingleModuleSystem<M>,\n statusPlugin,\n };\n}\n","/**\n * SignalClock — injectable clock source for declarative timers (RFC 0001).\n *\n * The clock interface decouples Directive's timer primitives from any\n * single time source. Production uses `realClock()`. Tests use\n * `virtualClock()` which advances synchronously via `clock.advanceBy()`.\n * Replay / dehydrate scenarios use a clock seeded from the recorded\n * stream.\n *\n * Auto-detection: `defaultClock()` returns `virtualClock()` when running\n * under Vitest (process.env.VITEST === 'true'), otherwise `realClock()`.\n * Consumers can pass an explicit clock to `createSystem({ clock })` to\n * override.\n *\n * @see ../../docs/rfcs/0001-t-timer.md\n */\n\n/**\n * Stable interface for any time source.\n */\nexport interface SignalClock {\n /** Current time, in milliseconds since the Unix epoch. */\n now(): number;\n /**\n * Schedule a callback to fire after `ms` milliseconds. Returns a\n * cancellation function. Implementations may queue callbacks or fire\n * them on a tick boundary; the only contract is \"fires no earlier\n * than `ms` from now.\"\n */\n setTimeout(cb: () => void, ms: number): () => void;\n /**\n * (Test-only.) Synchronously advance the clock by `ms` milliseconds,\n * firing all scheduled callbacks whose deadlines fall within the\n * advanced window. Real clocks throw if called.\n */\n advanceBy?(ms: number): void;\n}\n\n/**\n * Production clock — wraps `Date.now()` and `globalThis.setTimeout`.\n * No mocking, no virtualization.\n */\nexport function realClock(): SignalClock {\n return {\n now: () => Date.now(),\n setTimeout: (cb, ms) => {\n const handle = globalThis.setTimeout(cb, ms);\n return () => globalThis.clearTimeout(handle);\n },\n };\n}\n\n/**\n * Virtual clock — advances only when `advanceBy(ms)` is called. All\n * scheduled callbacks fire synchronously in order of their deadlines.\n *\n * Two scheduled callbacks at the same deadline fire in registration order.\n * Cancellation is O(1).\n */\nexport function virtualClock(initialMs = 0): SignalClock {\n let nowMs = initialMs;\n let nextId = 0;\n interface Scheduled {\n id: number;\n deadlineMs: number;\n cb: () => void;\n canceled: boolean;\n }\n const queue: Scheduled[] = [];\n\n return {\n now: () => nowMs,\n setTimeout: (cb, ms) => {\n const entry: Scheduled = {\n id: nextId++,\n deadlineMs: nowMs + ms,\n cb,\n canceled: false,\n };\n queue.push(entry);\n return () => {\n entry.canceled = true;\n };\n },\n advanceBy: (ms) => {\n const targetMs = nowMs + ms;\n // Fire all callbacks whose deadlines fall in [nowMs, targetMs].\n // Sort live entries by deadline + registration order so ties\n // resolve deterministically.\n while (true) {\n const ready = queue\n .filter((e) => !e.canceled && e.deadlineMs <= targetMs)\n .sort((a, b) =>\n a.deadlineMs !== b.deadlineMs\n ? a.deadlineMs - b.deadlineMs\n : a.id - b.id,\n );\n if (ready.length === 0) break;\n const next = ready[0]!;\n // Advance \"now\" monotonically — never let a callback that\n // schedules another callback in the past pull `nowMs`\n // backward. Without this clamp, `setTimeout(cb2, -5)` from\n // inside a callback would make `clock.now()` return a smaller\n // value mid-advance, breaking elapsedMs (negative results)\n // and replay determinism. (R1 sec C3.)\n nowMs = Math.max(nowMs, next.deadlineMs);\n next.canceled = true;\n next.cb();\n }\n // Final advance — even if no callbacks fired in [nowMs, targetMs],\n // wall clock still moves forward.\n nowMs = Math.max(nowMs, targetMs);\n },\n };\n}\n\n/**\n * Returns `realClock()` always.\n *\n * Earlier drafts auto-detected vitest (`process.env.VITEST === 'true'`)\n * and returned a `virtualClock()` in that environment. AE review\n * flagged this as a footgun: tests that legitimately need real time\n * (sleep-based debounce checks, real-`setTimeout`-bound integration\n * fixtures) silently received a virtual clock that never advanced\n * unless the test author called `advanceBy()`, producing apparent\n * deadlocks indistinguishable from genuine bugs. Auto-detection is\n * therefore opt-in.\n *\n * Use {@link virtualClock} explicitly in tests:\n *\n * ```ts\n * const clock = virtualClock(0);\n * const sys = createSystem({ module, clock });\n * clock.advanceBy(1_000);\n * ```\n */\nexport function defaultClock(): SignalClock {\n return realClock();\n}\n","/**\n * Timer fact — a runtime container that advances over time on a\n * SignalClock (RFC 0001 v0.1).\n *\n * Produced by `createTimerFact(clock, opts)`. Holds the durable state\n * (startedAtMs, pausedDurationMs, status) and exposes a control surface\n * (start, pause, resume, reset) plus reactive reads (elapsedMs,\n * remainingMs, status).\n *\n * v0.1 SCOPE: timer is a \"thick fact\" — a single object you store in a\n * regular Directive fact (e.g. `t.object<TimerFactState>()`). The\n * engine doesn't auto-tick it; the consumer is responsible for calling\n * `timer.tick()` when they want elapsedMs / remainingMs to update.\n * Typical wiring: a setInterval in the consumer that calls `timer.tick()`\n * and dispatches an event when status changes.\n *\n * v0.2 (deferred): true `t.timer({ms})` schema integration where the\n * engine subscribes to the clock and writes the fact deltas itself,\n * eliminating the consumer-side tick wiring.\n *\n * @see ../../docs/rfcs/0001-t-timer.md\n */\n\n// SignalClock is the canonical time source for timer ops; consumers\n// pass `clock.now()` into the helpers below. Re-exported by index.ts\n// alongside this module so they can `import { realClock, timerOps,\n// initialTimerState } from \"@directive-run/core\"` together.\n\n/**\n * Persistent timer state — JSON-roundtrippable, suitable for storing\n * inside a Directive fact.\n */\nexport interface TimerFactState {\n /** Unix-ms when the timer last started or resumed. null = not running. */\n startedAtMs: number | null;\n /** Total ms accumulated while paused. */\n pausedDurationMs: number;\n /** ms when the timer was paused, if currently paused. null otherwise. */\n pausedAtMs: number | null;\n /**\n * - 'idle': not yet started, or reset.\n * - 'running': currently counting.\n * - 'paused': paused; pausedAtMs is set.\n * - 'completed': hit the deadline (countdown mode only).\n */\n status: \"idle\" | \"running\" | \"paused\" | \"completed\";\n /** Number of times the timer has fired (repeat mode only). */\n repeats: number;\n}\n\nexport interface TimerFactOpts {\n /** Duration in ms. Countdown mode counts this down; up mode counts up to ∞. */\n ms: number;\n /**\n * - 'down' (default): counts down from `ms` to 0; status → 'completed' at 0.\n * - 'up': counts elapsed time; never completes.\n * - 'repeat': fires every `ms`; increments `repeats`; status stays 'running'.\n */\n mode?: \"down\" | \"up\" | \"repeat\";\n}\n\n/**\n * Initial state for a newly-created timer. Pass this to your Directive\n * `init()` to seed the fact.\n */\nexport function initialTimerState(): TimerFactState {\n return {\n startedAtMs: null,\n pausedDurationMs: 0,\n pausedAtMs: null,\n status: \"idle\",\n repeats: 0,\n };\n}\n\n/**\n * Compute elapsed ms for a given timer state at a given clock-now.\n * Pure function — no side effects, no reads beyond its inputs.\n *\n * @example\n * ```ts\n * const elapsed = elapsedMs(facts.countdown, clock.now());\n * if (elapsed >= 60_000) {\n * facts.countdown = { ...facts.countdown, status: 'completed' };\n * }\n * ```\n */\nexport function elapsedMs(state: TimerFactState, nowMs: number): number {\n if (state.startedAtMs === null) return 0;\n // Clamp at 0 — a clock step-back (NTP correction, virtual-clock\n // re-entrancy, replay seeded from older snapshot) would otherwise\n // produce negative elapsed values that:\n // - make tickTimer never report 'complete' (because `elapsed >= ms`\n // stays false past the deadline)\n // - make remainingMs report values > the configured ms total\n // - silently wrap into pausedDurationMs accumulation downstream\n // (R1 sec C4.)\n if (state.status === \"paused\" && state.pausedAtMs !== null) {\n return Math.max(\n 0,\n state.pausedAtMs - state.startedAtMs - state.pausedDurationMs,\n );\n }\n return Math.max(0, nowMs - state.startedAtMs - state.pausedDurationMs);\n}\n\n/**\n * Compute remaining ms for a countdown timer at a given clock-now.\n * Returns 0 if the timer has hit zero or hasn't started.\n */\nexport function remainingMs(\n state: TimerFactState,\n nowMs: number,\n totalMs: number,\n): number {\n return Math.max(0, totalMs - elapsedMs(state, nowMs));\n}\n\n/**\n * Transition: start an idle (or reset) timer.\n *\n * No-op if already running, paused, or completed (use `reset()` first).\n */\nexport function startTimer(\n state: TimerFactState,\n nowMs: number,\n): TimerFactState {\n if (state.status === \"running\") return state;\n if (state.status === \"paused\") return state;\n return {\n ...state,\n startedAtMs: nowMs,\n pausedDurationMs: 0,\n pausedAtMs: null,\n status: \"running\",\n repeats: 0,\n };\n}\n\n/**\n * Transition: pause a running timer. Records the pause moment so a\n * later `resumeTimer()` can correctly extend pausedDurationMs.\n *\n * No-op if not running.\n */\nexport function pauseTimer(\n state: TimerFactState,\n nowMs: number,\n): TimerFactState {\n if (state.status !== \"running\") return state;\n return { ...state, pausedAtMs: nowMs, status: \"paused\" };\n}\n\n/**\n * Transition: resume a paused timer. Adds the time spent paused into\n * `pausedDurationMs` so elapsed/remaining math stays correct.\n *\n * No-op if not paused.\n */\nexport function resumeTimer(\n state: TimerFactState,\n nowMs: number,\n): TimerFactState {\n if (state.status !== \"paused\") return state;\n if (state.pausedAtMs === null) return state;\n // Clamp pausedFor at 0 — clock step-back between pause and resume\n // would otherwise produce a negative pausedDurationMs accumulation,\n // which propagates into elapsedMs (returns inflated values), which\n // prematurely completes countdowns. (R1 sec M1.)\n const pausedFor = Math.max(0, nowMs - state.pausedAtMs);\n return {\n ...state,\n pausedDurationMs: state.pausedDurationMs + pausedFor,\n pausedAtMs: null,\n status: \"running\",\n };\n}\n\n/**\n * Transition: reset a timer to idle. Loses all elapsed time + repeat\n * count. Equivalent to `initialTimerState()`.\n */\nexport function resetTimer(): TimerFactState {\n return initialTimerState();\n}\n\n/**\n * Transition: mark the timer completed. For countdown mode when\n * elapsed reaches `ms`; for repeat mode when consumer wants to halt.\n */\nexport function completeTimer(state: TimerFactState): TimerFactState {\n return { ...state, status: \"completed\" };\n}\n\n/**\n * Transition: register a repeat firing. Increments `repeats` and\n * advances `startedAtMs` by `ms` so the next interval lands at the\n * intended boundary (drift-free).\n */\nexport function registerRepeat(\n state: TimerFactState,\n ms: number,\n): TimerFactState {\n if (state.startedAtMs === null) return state;\n // Defensible-illegal: registerRepeat from a paused state would\n // otherwise advance startedAtMs while leaving status === 'paused',\n // producing an inconsistent state (logically running by clock math\n // but reads as paused). No-op instead. (R2 sec m-R2-2.)\n if (state.status === \"paused\") return state;\n // Reset pausedDurationMs on each repeat so accumulated pause time\n // from prior intervals does not double-count into the next\n // interval's elapsed math. Without this reset, every repeat after a\n // pause would arithmetic-drift the next deadline by the cumulative\n // pause window. (R1 sec M9.)\n return {\n ...state,\n startedAtMs: state.startedAtMs + ms,\n pausedDurationMs: 0,\n pausedAtMs: null,\n repeats: state.repeats + 1,\n };\n}\n\n/**\n * Higher-level helper: given a timer state, total ms, and the current\n * clock, return whether the timer should transition to 'completed' (for\n * countdown mode) or fire a repeat (for repeat mode).\n *\n * Pure — does not mutate state. Returns a structured signal the consumer\n * applies via `completeTimer` / `registerRepeat`.\n */\nexport function tickTimer(\n state: TimerFactState,\n nowMs: number,\n opts: TimerFactOpts,\n): { kind: \"no-op\" } | { kind: \"complete\" } | { kind: \"repeat\" } {\n if (state.status !== \"running\") return { kind: \"no-op\" };\n const elapsed = elapsedMs(state, nowMs);\n\n if (opts.mode === \"up\") {\n // 'up' never completes; consumer reads elapsedMs directly.\n return { kind: \"no-op\" };\n }\n\n if (opts.mode === \"repeat\") {\n if (elapsed >= opts.ms) return { kind: \"repeat\" };\n return { kind: \"no-op\" };\n }\n\n // 'down' (default)\n if (elapsed >= opts.ms) return { kind: \"complete\" };\n return { kind: \"no-op\" };\n}\n\n/**\n * Bundle of helpers for one timer in one module — convenience for\n * callers who want a single import. Each method takes the current\n * state and clock-now, returns the next state. No mutation.\n *\n * @example\n * ```ts\n * import {\n * createSystem,\n * t,\n * realClock,\n * timerOps,\n * initialTimerState,\n * type TimerFactState,\n * } from '@directive-run/core';\n *\n * const clock = realClock();\n * const ops = timerOps({ ms: 60_000, mode: 'down' });\n *\n * createModule('countdown', {\n * schema: { facts: { state: t.object<TimerFactState>() }, events: { START: {} } },\n * init: (f) => { f.state = initialTimerState(); },\n * events: {\n * START: (f) => { f.state = ops.start(f.state, clock.now()); },\n * },\n * });\n *\n * // In the consumer (React, Node, edge), tick periodically:\n * setInterval(() => {\n * const signal = ops.tick(f.state, clock.now());\n * if (signal.kind === 'complete') {\n * sys.dispatch({ type: 'TIMEOUT' });\n * }\n * }, 100);\n * ```\n */\nexport function timerOps(opts: TimerFactOpts) {\n return {\n initial: initialTimerState,\n start: startTimer,\n pause: pauseTimer,\n resume: resumeTimer,\n reset: resetTimer,\n complete: completeTimer,\n registerRepeat: (state: TimerFactState) => registerRepeat(state, opts.ms),\n tick: (state: TimerFactState, nowMs: number) =>\n tickTimer(state, nowMs, opts),\n elapsedMs,\n remainingMs: (state: TimerFactState, nowMs: number) =>\n remainingMs(state, nowMs, opts.ms),\n };\n}\n","/**\n * @directive-run/core\n *\n * Constraint-driven runtime for TypeScript.\n *\n * Also available:\n * - `@directive-run/core/internals` – Manager factories, engine, tracking, and internal types\n * - `@directive-run/core/plugins` – Logging, devtools, persistence, observability, circuit breaker\n * - `@directive-run/core/testing` – Mock resolvers, fake timers, assertion helpers\n * - `@directive-run/core/migration` – Redux/Zustand/XState migration scaffolding\n * - `@directive-run/core/adapter-utils` – Shared framework adapter utilities\n * - `@directive-run/core/worker` – Web Worker support\n *\n * @packageDocumentation\n */\n\n// ============================================================================\n// Core Types — what 90% of users need\n// ============================================================================\n\nexport type {\n // Schema\n Schema,\n SchemaType,\n InferSchemaType,\n // Module Schema (consolidated)\n ModuleSchema,\n InferFacts,\n InferDerivations,\n InferSelectorState,\n InferEvents,\n InferRequirements,\n InferRequirementTypes,\n // Facts\n Facts,\n FactsSnapshot,\n // Requirements\n Requirement,\n RequirementWithId,\n // Constraints + Resolvers (config types)\n RetryPolicy,\n BatchConfig,\n // Plugins\n Plugin,\n Snapshot,\n // Errors\n ErrorBoundaryConfig,\n // Module\n ModuleDef,\n ModuleHooks,\n // System\n System,\n SystemConfig,\n SystemInspection,\n SystemSnapshot,\n MetaAccessor,\n MetaMatch,\n ObservationEvent,\n // Trace\n TraceEntry,\n TraceOption,\n // History\n HistoryOption,\n HistoryAPI,\n HistoryState,\n // Composition (Namespaced Multi-Module)\n ModulesMap,\n NamespacedSystem,\n CreateSystemOptionsNamed,\n // Single Module\n CreateSystemOptionsSingle,\n SingleModuleSystem,\n // Type Guards\n SystemMode,\n AnySystem,\n // Cross-Module Dependencies\n CrossModuleDeps,\n // Dynamic Definitions\n DynamicConstraintDef,\n DynamicEffectDef,\n DynamicResolverDef,\n // Definition Meta\n DefinitionMeta,\n DerivationDefWithMeta,\n // Data-configuration predicates and templates\n FactPredicate,\n FactTemplate,\n KeySelector,\n PatchSpec,\n PayloadRef,\n PatchValue,\n OperatorObject,\n PredicateObject,\n PredicateClause,\n PredicateCombinator,\n PredicateCombinatorKey,\n PredicateOp,\n ClauseResult,\n // Distributable Snapshots\n DistributableSnapshot,\n DistributableSnapshotOptions,\n} from \"./core/types.js\";\n\n// Predicate / template runtime\nexport {\n applyPatch,\n memoizePredicate,\n evaluateKeySelector,\n evaluatePredicate,\n evaluatePredicateExplained,\n evaluateTemplate,\n extractDeps,\n extractTemplateKeys,\n isPredicate,\n isTemplate,\n validatePredicate,\n} from \"./core/predicate.js\";\n\n// Predicate backtest — rule-change impact replay\nexport {\n MAX_REPLAY_FRAMES,\n framesFromHistory,\n framesFromSnapshots,\n replayUnder,\n toReplayFrames,\n} from \"./core/replay-under.js\";\nexport type {\n PredicateBacktestReport,\n ReplayDiffSample,\n ReplayFrame,\n ReplayUnderOptions,\n} from \"./core/replay-under.js\";\n\n// Parameter sweep — grid-search predicate templates against recorded history\nexport { MAX_SWEEP_POINTS, sweepUnder } from \"./core/sweep-under.js\";\nexport type {\n SweepHole,\n SweepPoint,\n SweepReport,\n SweepUnderOptions,\n} from \"./core/sweep-under.js\";\n\n// Rules diff — structural diff of constraint whenSpec across two snapshots\nexport { diffClauses, diffRules, flattenPredicate, toRulesMap } from \"./core/rules-diff.js\";\nexport type {\n Change,\n ChangeKind,\n ConstraintDiff,\n ConstraintStatus,\n DiffRulesOptions,\n LeafClause,\n RulesDiffReport,\n RulesMapInput,\n} from \"./core/rules-diff.js\";\n\n// Schema introspection — runtime kind discriminant + operator matrix\nexport {\n getKind,\n getOperatorsForKind,\n getSchemaFieldKinds,\n listAllPredicateOperators,\n} from \"./core/schema-introspection.js\";\nexport type { SchemaKind, SchemaKindNode } from \"./core/schema-introspection.js\";\nexport { validatePredicateAgainstSchema } from \"./core/predicate.js\";\nexport type {\n SchemaValidationError,\n SchemaValidationOptions,\n SchemaValidationResult,\n} from \"./core/predicate.js\";\n\n// predict — \"would this predicate fire, and if not, which facts must change?\"\nexport { predict } from \"./core/predict.js\";\nexport type { PredictMissingChange, PredictResult } from \"./core/predict.js\";\n\n// doctor — structural contradiction detection between a candidate predicate and existing constraints\nexport { doctor } from \"./core/doctor.js\";\nexport type {\n CheckAgainstResult,\n Contradiction,\n ContradictionType,\n ExistingConstraint,\n} from \"./core/doctor.js\";\n\n// createAuditLedger — append-only, queryable, cryptographically-chained audit log\nexport {\n createAuditLedger,\n memorySink,\n} from \"./plugins/audit-ledger.js\";\nexport type {\n AuditEntry,\n AuditEntryKind,\n AuditLedger,\n AuditLedgerOptions,\n AuditLedgerSink,\n QueryFilter,\n} from \"./plugins/audit-ledger.js\";\n\n// Predicate codegen — one predicate, run on client AND server\nexport { predicateToSQL, predicateToWhere } from \"./core/predicate-to-sql.js\";\nexport type {\n PredicateToSqlOptions,\n PredicateToSqlResult,\n} from \"./core/predicate-to-sql.js\";\nexport { predicateToMongo } from \"./core/predicate-to-mongo.js\";\nexport type { PredicateToMongoOptions } from \"./core/predicate-to-mongo.js\";\nexport { predicateToPostgrest } from \"./core/predicate-to-pgrest.js\";\nexport type { PredicateToPostgrestOptions } from \"./core/predicate-to-pgrest.js\";\n\n// ============================================================================\n// Core Classes\n// ============================================================================\n\nexport { DirectiveError } from \"./core/types.js\";\n\n// ============================================================================\n// Schema Type Builders\n// ============================================================================\n\n/**\n * Schema type builders for defining fact types.\n *\n * @example\n * ```ts\n * import { t } from '@directive-run/core';\n *\n * const schema = {\n * facts: {\n * count: t.number().min(0).default(0),\n * name: t.string(),\n * status: t.enum(\"idle\", \"loading\", \"error\"),\n * user: t.object<User>().nullable(),\n * },\n * derivations: { doubled: t.number() },\n * events: { increment: {} },\n * requirements: { FETCH_USER: {} },\n * };\n * ```\n */\nexport {\n t,\n type Branded,\n type ExtendedSchemaType,\n type ChainableSchemaType,\n} from \"./core/schema-builders.js\";\n\n// ============================================================================\n// Module & System\n// ============================================================================\n\nexport {\n createModule,\n createModuleFactory,\n type ModuleConfig,\n type ModuleConfigWithDeps,\n} from \"./core/module.js\";\nexport { createSystem } from \"./core/system.js\";\nexport { createSystemWithStatus } from \"./utils/system-with-status.js\";\n\n// Helper factory functions for typed constraint/resolver definitions\nexport {\n typedConstraint,\n typedResolver,\n} from \"./core/types.js\";\n\n// ============================================================================\n// Requirements Helpers\n// ============================================================================\n\nexport {\n req,\n forType,\n isRequirementType,\n generateRequirementId,\n RequirementSet,\n} from \"./core/requirements.js\";\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nexport {\n isSingleModuleSystem,\n isNamespacedSystem,\n} from \"./core/types/composition.js\";\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/**\n * Backoff strategy constants for retry policies.\n *\n * @example\n * ```ts\n * import { Backoff } from '@directive-run/core';\n *\n * retry: { attempts: 3, backoff: Backoff.Exponential, initialDelay: 100 }\n * ```\n */\nexport const Backoff = {\n /** No delay between retries */\n None: \"none\",\n /** Linear delay increase (initialDelay * attempt) */\n Linear: \"linear\",\n /** Exponential delay increase (initialDelay * 2^attempt) */\n Exponential: \"exponential\",\n} as const;\n\n// ============================================================================\n// Requirement Status Utilities\n// ============================================================================\n\nexport {\n createRequirementStatusPlugin,\n createStatusHook,\n type RequirementTypeStatus,\n} from \"./utils/requirement-status.js\";\n\n// ============================================================================\n// Snapshot Utilities\n// ============================================================================\n\nexport {\n shallowEqual,\n isSnapshotExpired,\n validateSnapshot,\n diffSnapshots,\n signSnapshot,\n verifySnapshotSignature,\n isSignedSnapshot,\n type DistributableSnapshotLike,\n type SnapshotDiff,\n type SnapshotDiffEntry,\n type SignedSnapshot,\n} from \"./utils/utils.js\";\n\n// ============================================================================\n// Clock + Timer (RFC 0001 v0.1)\n// ============================================================================\n\nexport {\n type SignalClock,\n realClock,\n virtualClock,\n defaultClock,\n} from \"./core/clock.js\";\n\nexport {\n type TimerFactState,\n type TimerFactOpts,\n initialTimerState,\n elapsedMs,\n remainingMs,\n startTimer,\n pauseTimer,\n resumeTimer,\n resetTimer,\n completeTimer,\n registerRepeat,\n tickTimer,\n timerOps,\n} from \"./core/timer.js\";\n\n// ============================================================================\n// Lower-level APIs — use \"@directive-run/core/internals\" for these\n// ============================================================================\n// Manager factories, engine, tracking, and internal types are available at:\n// import { createEngine, createFacts, withTracking } from \"@directive-run/core/internals\"\n//\n// Internal types (FactsStore, FactChange, DerivationState, ConstraintState,\n// DerivationsDef, ConstraintsDef, ResolversDef, EventsDef, ReconcileResult,\n// RecoveryStrategy, ErrorSource, etc.) are also in internals.\n\n// Migration utilities available via \"@directive-run/core/migration\" subpath export.\n"]}