@directive-run/core 1.6.1 → 1.7.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/replay-under.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","createSchemaType","validators","typeName","defaultValue","transform","description","refinements","meta","fn","createChainableType","fieldMeta","value","v","intermediate","desc","predicate","newRefinements","m","unionImpl","types","typeNames","schemaType","t","createChainableString","fm","n","regex","createChainableNumber","createChainableArray","elementType","indexRef","chainable","ref","et","newRef","validator","createChainableObject","shapeSchema","schemaT","keys","k","values","dev_true_default","valueSet","innerType","innerTypeName","valueType","valueTypeName","val","uuidRegex","emailRegex","validateModuleId","id","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","constraints","cid","constraint","owns","BLOCKED_PROPS","validateModuleConfig","createModule","crossModuleDeps","createModuleFactory","name","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","e","a","b","next","defaultClock","initialTimerState","elapsedMs","remainingMs","totalMs","startTimer","pauseTimer","resumeTimer","pausedFor","resetTimer","completeTimer","registerRepeat","tickTimer","opts","elapsed","timerOps","Backoff"],"mappings":"yNAoCO,IAAMA,CAAAA,CAAoB,IAsFjC,SAASC,CAAAA,CACPC,CAAAA,CACAC,CAAAA,CACM,CACN,GAAI,CACFC,mBAAAA,CAAkBF,CAAI,EACxB,OAASG,CAAAA,CAAK,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,gCAA2BG,CAAO,CAAA,CACzE,CACF,CAEA,GAAI,CAACC,mBAAAA,CAAYL,CAAI,CAAA,CAAG,CACtB,IAAMM,CAAAA,CACJN,CAAAA,GAAS,IAAA,EAAQ,OAAOA,CAAAA,EAAS,SAC7B,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,EAEtC,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,SAASS,CAAAA,CAAWC,CAAAA,CAAI,CAEpBH,CAAAA,GAAc,MAAA,EACdG,CAAAA,CAAG,UAAA,CAAW,GAAG,CAAA,EACjB,CAACC,mBAAA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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 * 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// ============================================================================\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/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","createSchemaType","validators","typeName","defaultValue","transform","description","refinements","meta","fn","createChainableType","fieldMeta","value","intermediate","desc","predicate","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","id","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","constraints","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","e","a","b","next","defaultClock","initialTimerState","elapsedMs","remainingMs","totalMs","startTimer","pauseTimer","resumeTimer","pausedFor","resetTimer","completeTimer","registerRepeat","tickTimer","opts","elapsed","timerOps","Backoff"],"mappings":"yNAoCO,IAAMA,EAAoB,IAsFjC,SAASC,CAAAA,CACPC,CAAAA,CACAC,EACM,CACN,GAAI,CACFC,mBAAAA,CAAkBF,CAAI,EACxB,CAAA,MAASG,CAAAA,CAAK,CACZ,IAAMC,CAAAA,CAAUD,CAAAA,YAAe,KAAA,CAAQA,CAAAA,CAAI,QAAU,MAAA,CAAOA,CAAG,CAAA,CAE/D,MAAM,IAAI,KAAA,CACR,CAAA,6BAAA,EAAgCF,CAAK,CAAA,6BAAA,EAA2BG,CAAO,CAAA,CACzE,CACF,CAEA,GAAI,CAACC,oBAAYL,CAAI,CAAA,CAAG,CACtB,IAAMM,EACJN,CAAAA,GAAS,IAAA,EAAQ,OAAOA,CAAAA,EAAS,SAC7B,CAAA,EAAG,OAAOA,CAAI,CAAA,QAAA,EAAM,KAAK,SAAA,CAAUA,CAAI,CAAC,CAAA,CAAA,CACxC,KAAK,SAAA,CAAUA,CAAI,CAAA,CAAE,KAAA,CAAM,EAAG,EAAE,CAAA,CAEtC,MAAM,IAAI,MACR,CAAA,6BAAA,EAAgCC,CAAK,CAAA,6CAAA,EAAgDK,CAAO,GAC9F,CACF,CAKA,IAAIC,CAAAA,CAsBJ,GArBAC,oBAAcR,CAAAA,CAAM,CAClB,QAAA,CAASS,CAAAA,CAAWC,EAAI,CAEpBH,CAAAA,GAAc,MAAA,EACdG,CAAAA,CAAG,WAAW,GAAG,CAAA,EACjB,CAACC,mBAAAA,CAAoB,IAAID,CAAE,CAAA,GAE3B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AAQC,GACR,KAAA,CAAOE,EAAAA,CACP,QAAA,CAAUC,EAAAA,CACV,eAAiBlD,CAAAA,EAA0BmD,EAAAA,CAAenD,CAAAA,CAAOqD,CAAAA,CAAK,EAAE,CAAA,CACxE,IAAA,CAAM,CAACrD,EAAuB+B,CAAAA,GAC5BqB,EAAAA,CAAUpD,CAAAA,CAAO+B,CAAAA,CAAOsB,CAAI,CAAA,CAC9B,SAAA,CAAAX,CAAAA,CACA,YAAa,CAAC1C,CAAAA,CAAuB+B,CAAAA,GACnCY,CAAAA,CAAY3C,CAAAA,CAAO+B,CAAAA,CAAOsB,CAAAA,CAAK,EAAE,CACrC,CACF,CCxEO,IAAMG,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 * 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// ============================================================================\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"]}