@directive-run/core 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/types/errors.ts","../src/core/types/helpers.ts","../src/core/types/composition.ts","../src/core/tracking.ts","../src/core/facts.ts","../src/core/module.ts","../src/utils/utils.ts","../src/core/requirements.ts","../src/core/constraints.ts","../src/core/derivations.ts","../src/core/effects.ts","../src/core/errors.ts","../src/core/plugins.ts","../src/core/resolvers.ts","../src/utils/time-travel.ts","../src/core/engine.ts","../src/core/system.ts","../src/core/builder.ts","../src/core/constraint-builders.ts","../src/core/system-builder.ts","../src/utils/requirement-status.ts","../src/utils/system-with-status.ts","../src/utils/migration.ts","../src/index.ts"],"names":["DirectiveError","message","source","sourceId","context","recoverable","constraintFactory","constraint","resolverFactory","resolver","typedConstraint","typedResolver","isSingleModuleSystem","system","isNamespacedSystem","trackingStack","createTrackingContext","dependencies","key","nullContext","getCurrentTracker","isTracking","withTracking","fn","withoutTracking","saved","trackAccess","safeStringify","value","maxLength","warnedTypes","createSchemaType","validators","typeName","defaultValue","transform","description","refinements","createChainableType","v","intermediate","desc","predicate","newRefinements","t","createChainableNumber","n","createChainableArray","elementType","indexRef","chainable","ref","et","newRef","i","item","validator","createChainableObject","shapeSchema","schemaType","schemaT","keys","k","values","valueSet","innerType","innerTypeName","types","typeNames","valueType","valueTypeName","val","uuidRegex","emailRegex","createFactsStore","options","schema","onChange","onBatch","isTypeAssertionSchema","validate","strictKeys","redactErrors","map","knownKeys","keyListeners","allListeners","batching","batchChanges","dirtyKeys","isNotifying","pendingNonBatchedChanges","MAX_NOTIFY_ITERATIONS","isZodSchema","getExpectedType","st","def","formatValueForError","validateValue","result","valuePreview","errorMessage","expectedType","indexHint","validatorHint","notifyKey","listener","notifyAll","notifyNonBatched","prev","iterations","deferred","change","flush","store","keyStr","set","newSchema","BLOCKED_PROPS","createFactsProxy","snapshot","_","prop","createFacts","facts","createModule","id","config","schemaDerivations","deriveImpl","schemaDerivationKeys","deriveKeys","schemaEvents","eventImpl","schemaEventKeys","eventKeys","requirementTypes","resolverName","resolverDef","crossModuleDeps","createModuleFactory","name","withTimeout","promise","ms","timeoutId","timeoutPromise","reject","stableStringify","maxDepth","seen","stringify","depth","type","obj","isPrototypeSafe","dangerousKeys","check","objVal","shallowEqual","a","b","keysA","keysB","hashObject","str","hash","isSnapshotExpired","now","validateSnapshot","expiredAt","diffSnapshots","oldSnapshot","newSnapshot","changes","compare","oldObj","newObj","path","oldRecord","newRecord","allKeys","childPath","versionChanged","isSignedSnapshot","signSnapshot","secret","payload","signature","hmacSha256","verifySnapshotSignature","signedSnapshot","expectedSignature","timingSafeEqual","secretBytes","algorithm","messageBytes","generateRequirementId","req","keyFn","rest","sortedRest","createRequirementWithId","requirement","fromConstraint","props","isRequirementType","forType","RequirementSet","_RequirementSet","copy","other","added","removed","unchanged","DEFAULT_TIMEOUT","createConstraintsManager","definitions","requirementKeys","defaultTimeout","onEvaluate","onError","states","disabled","asyncConstraintIds","constraintDeps","factToConstraints","dirtyConstraints","latestWhenDeps","lastRequirements","hasEvaluated","resolvedConstraints","noFireConstraints","dependsOnMe","topologicalOrder","topologicalIndex","buildReverseDependencyMap","depId","detectCyclesAndComputeTopoOrder","visited","visiting","postOrder","visit","cycleStart","cycle","index","isAsyncConstraint","initState","isAsync","state","getState","updateDependencies","newDeps","oldDeps","dep","constraints","evaluateSync","tracked","asyncResult","error","evaluateAsync","timeout","depsSet","resultPromise","MAX_REQUIREMENTS_WARNING_THRESHOLD","normalizeRequirements","output","constraintId","filtered","r","getRequirements","requireDef","deps","mergeDependencies","additionalDeps","existingDeps","sortedConstraintIds","getSortedConstraintIds","stateA","priorityDiff","topoA","topoB","areAfterDependenciesSatisfied","changedKeys","requirements","allConstraintIds","constraintsToEvaluate","affected","dependentConstraints","lastReqs","processConstraintResult","active","whenDeps","reqs","requireDeps","combinedDeps","reqsWithId","reqWithId","evaluateConstraintBatch","constraintIds","blockedConstraints","readyToEvaluate","syncConstraints","asyncConstraints","unexpectedAsync","asyncResults","remainingToEvaluate","maxPasses","previousRemaining","factKey","dependents","newDefs","createDerivationsManager","_store","onCompute","onInvalidate","listeners","factToDerivedDeps","derivedToDerivedDeps","invalidationDepth","pendingNotifications","isFlushing","MAX_FLUSH_ITERATIONS","derivedProxy","computeDerivation","depSet","flushNotifications","remaining","ids","invalidateDerivation","dependent","factKeys","idStr","listenerSet","createEffectsManager","onRun","previousSnapshot","stopped","createSnapshot","shouldRun","runCleanup","storeCleanup","runEffect","effectPromise","trackedDeps","trackingResult","effectsToRun","effectIds","createRetryLaterManager","delayMs","maxRetries","backoffMultiplier","maxDelayMs","pendingRetries","calculateDelay","attempt","delay","callback","entry","dueRetries","DEFAULT_STRATEGIES","createErrorBoundaryManager","onRecovery","errors","maxErrors","retryLaterManager","retryAttempts","toDirectiveError","getStrategy","handler","e","directiveError","strategy","createPluginManager","plugins","safeCall","safeCallAsync","plugin","p","byResolver","duration","from","to","DEFAULT_RETRY","DEFAULT_BATCH","policy","backoff","initialDelay","maxDelay","createResolversManager","onStart","onComplete","onRetry","onCancel","onResolutionComplete","inflight","statuses","MAX_STATUSES","batches","resolversByType","MAX_RESOLVER_CACHE","cleanupStatuses","entriesToRemove","iterator","hasStringRequirement","hasFunctionRequirement","resolverHandles","findResolver","reqType","cached","oldest","typeResolvers","createContext","signal","executeResolve","resolverId","controller","retryPolicy","lastError","ctx","resolvePromise","resolve","abortHandler","executeBatch","batchConfig","startedAt","reqPayloads","results","hasFailures","addToBatch","batch","processBatch","requirementId","status","createTimeTravelManager","onSnapshot","onTimeTravel","isEnabled","maxSnapshots","snapshots","currentIndex","nextId","paused","restoring","changesets","pendingChangesetLabel","pendingChangesetStart","getCurrentFacts","serializeFacts","factsObj","deserializeFacts","serialized","trigger","steps","fromIndex","toIndex","cs","c","earlierCs","snapshotId","s","json","data","snap","label","createDisabledTimeTravel","noopSnapshot","createEngine","mergedSchema","mergedEvents","mergedDerive","mergedEffects","mergedConstraints","mergedResolvers","schemaOwners","module","validateKeys","section","existingOwner","derivationNames","pluginManager","errorBoundary","invalidateManyDerivations","timeTravelRef","scheduleReconcile","derivationsManager","effectsManager","constraintsManager","resolversManager","notifySettlementChange","timeTravelListeners","notifyTimeTravelChange","timeTravelManager","settlementListeners","MAX_RECONCILE_DEPTH","reconcileDepth","reconcile","keysForConstraints","currentRequirements","currentSet","inflightInfo","deriveAccessor","eventsAccessor","event","derivationId","derivationIds","unsubs","u","isEqual","previousValue","newValue","oldValue","next","old","unsub","timer","cleanup","current","constraintState","resolverStatus","relevantFacts","factsSnapshot","lines","reqDetails","factEntries","prefix","valueStr","maxWait","startTime","inspection","details","unmet","includeDerivations","excludeDerivations","includeFacts","ttlSeconds","metadata","includeVersion","allDerivationKeys","derivationKeys","unknown","excludeSet","allFactKeys","createdAt","previousVersion","registerModule","existingFactKeys","SEPARATOR","topologicalSort","modulesMap","namespaces","namespace","mod","depNamespace","moduleFactsProxyCache","namespacedFactsProxyCache","namespacedDeriveProxyCache","moduleDeriveProxyCache","createSystem","createSingleModuleSystem","namedOptions","createNamespacedSystem","moduleNamespaces","orderedNamespaces","initOrder","explicitOrder","missingModules","ns","debug","flatModules","hasCrossModuleDeps","depNamespaces","prefixedFacts","prefixedDerivations","prefixedEvents","prefixedInit","moduleFactsProxy","createModuleFactsProxy","prefixedDerive","derive","factsProxy","createCrossModuleFactsProxy","deriveProxy","createModuleDeriveProxy","prefixedEventHandlers","prefixedConstraints","constraintDef","prefixedResolvers","namespacedFacts","createNamespacedFactsProxy","prefixedEffects","effect","effectDef","prevProxy","m","hydratedFacts","engine","applyNamespacedFacts","namespaceKeysMap","moduleNamesCache","getModuleNames","namespacedFactsProxy","namespacedDeriveProxy","createNamespacedDeriveProxy","namespacedEventsProxy","createNamespacedEventsProxy","tickInterval","tickMs","loader","tickEventKey","toInternalKey","internalIds","internalOptions","namespacedData","sepIndex","localKey","moduleDef","namespaceCache","proxy","crossModuleFactsProxyCache","selfNamespace","cacheKey","depNamesSet","moduleEventsProxyCache","moduleEventsProxy","eventName","eventsProxy","_schema","_init","_events","_derive","_effects","_constraints","_resolvers","_hooks","builder","initFn","derivations","events","effects","resolvers","hooks","missingDerives","missingEvents","condition","_priority","_after","_deps","_timeout","_async","complete","createWhenConstraint","base","when","createSingleBuilder","mods","createNamespacedBuilder","_plugins","_debug","_errorBoundary","_tickMs","_zeroConfig","_initialFacts","enabled","_initOrder","order","createRequirementStatusPlugin","notify","getOrCreateSet","getStatus","pendingSet","inflightSet","failedSet","getAllStatus","allTypes","subscribe","reset","_resolver","createStatusHook","statusPlugin","createSystemWithStatus","allPlugins","analyzeReduxSlice","eventsCode","inferTypeString","reducerName","initCode","analyzeZustandStore","actionName","analyzeXStateMachine","deriveCode","stateName","derivationName","capitalize","eventTransitions","stateConfig","target","targetState","transitions","firstEntry","toState","cases","initLines","generateModuleCode","structure","schemaStr","code","generateMigrationChecklist","common","Backoff"],"mappings":"AAsCO,IAAMA,GAAN,cAA6B,KAAM,CACzC,WAAA,CACCC,CAAAA,CACgBC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EAAuB,IAAA,CACtC,CACD,MAAMJ,CAAO,CAAA,CALG,YAAAC,CAAAA,CACA,IAAA,CAAA,QAAA,CAAAC,EACA,IAAA,CAAA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAA,WAAA,CAAAC,CAAAA,CAGhB,KAAK,IAAA,CAAO,iBACb,CACD,EC8FO,SAASC,IAAsC,CACrD,OAAO,CAIN,MAAA,CACCC,CAAAA,CACwB,CACxB,OAAOA,CACR,CACD,CACD,CAmBO,SAASC,EAAAA,EAAoC,CACnD,OAAO,CAIN,OACCC,CAAAA,CACsB,CACtB,OAAOA,CACR,CACD,CACD,CAkBO,SAASC,GAGdH,CAAAA,CAA0D,CAC3D,OAAOA,CACR,CAgBO,SAASI,EAAAA,CAGdF,CAAAA,CAAoD,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CAAI,MAAA,CAAO,CAAC,CAAA,CAAE,WAAA,EAAY,CAAIA,CAAAA,CAAI,KAAA,CAAM,CAAC,CACjD,CASO,SAAS8hB,EAAAA,CACfjsB,CAAAA,CACW,CACX,IAAMksB,CAAAA,CAAS,CACd,2CAAA,CACA,0CAAA,CACA,mDAAA,CACA,+CAAA,CACA,8BAAA,CACA,sCAAA,CACA,iCAAA,CACA,sCACD,CAAA,CA2BA,OAAO,CAAC,GAzByC,CAChD,KAAA,CAAO,CACN,wCAAA,CACA,sCAAA,CACA,+CAAA,CACA,sCAAA,CACA,2CACD,CAAA,CACA,OAAA,CAAS,CACR,kCAAA,CACA,qCAAA,CACA,6CAAA,CACA,iDACD,CAAA,CACA,MAAA,CAAQ,CACP,8CAAA,CACA,0DAAA,CACA,wCAAA,CACA,oDAAA,CACA,wDAAA,CACA,6CACD,CACD,CAAA,CAEgClsB,CAAM,CAAA,EAAK,EAAC,CACvB,GAAGksB,CAAM,CAC/B,CClGO,IAAMC,EAAAA,CAAU,CAEtB,IAAA,CAAM,MAAA,CAEN,MAAA,CAAQ,QAAA,CAER,WAAA,CAAa,aACd","file":"index.js","sourcesContent":["/**\n * Error Types - Type definitions for error handling\n */\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\n/** Error source types */\nexport type ErrorSource = \"constraint\" | \"resolver\" | \"effect\" | \"derivation\" | \"system\";\n\n/**\n * Extended Error class with source tracking, recovery metadata, and\n * arbitrary context for structured error handling within Directive.\n *\n * Thrown or returned by the error boundary manager. The `source` and\n * `sourceId` fields identify where the error originated, and `recoverable`\n * indicates whether the engine can apply a recovery strategy.\n *\n * @param message - Human-readable error description\n * @param source - Which subsystem produced the error (`\"constraint\"`, `\"resolver\"`, `\"effect\"`, `\"derivation\"`, or `\"system\"`)\n * @param sourceId - The ID of the specific constraint, resolver, effect, or derivation that failed\n * @param context - Optional arbitrary data for debugging (e.g., the requirement that triggered a resolver error)\n * @param recoverable - Whether the error boundary can apply a recovery strategy (default `true`; `false` for system errors)\n *\n * @example\n * ```ts\n * try {\n * await system.settle();\n * } catch (err) {\n * if (err instanceof DirectiveError) {\n * console.log(err.source); // \"resolver\"\n * console.log(err.sourceId); // \"fetchUser\"\n * console.log(err.recoverable); // true\n * }\n * }\n * ```\n */\nexport class DirectiveError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly source: ErrorSource,\n\t\tpublic readonly sourceId: string,\n\t\tpublic readonly context?: unknown,\n\t\tpublic readonly recoverable: boolean = true,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"DirectiveError\";\n\t}\n}\n\n/** Recovery strategy for errors */\nexport type RecoveryStrategy = \"skip\" | \"retry\" | \"retry-later\" | \"disable\" | \"throw\";\n\n/**\n * Configuration for retry-later strategy.\n * When an error occurs, the system will wait for `delayMs` before retrying.\n */\nexport interface RetryLaterConfig {\n\t/** Delay in milliseconds before retrying (default: 1000) */\n\tdelayMs?: number;\n\t/** Maximum retries before giving up (default: 3) */\n\tmaxRetries?: number;\n\t/** Backoff multiplier for each retry (default: 2) */\n\tbackoffMultiplier?: number;\n\t/** Maximum delay in milliseconds (default: 30000) */\n\tmaxDelayMs?: number;\n}\n\n/**\n * Circuit breaker configuration for automatic failure protection.\n * After `failureThreshold` consecutive failures, the circuit opens\n * and all requests fail fast for `resetTimeoutMs`.\n */\nexport interface CircuitBreakerConfig {\n\t/** Number of consecutive failures before opening the circuit (default: 5) */\n\tfailureThreshold?: number;\n\t/** Time in milliseconds before attempting to close the circuit (default: 60000) */\n\tresetTimeoutMs?: number;\n\t/** Number of successful requests needed to close a half-open circuit (default: 1) */\n\tsuccessThreshold?: number;\n}\n\n/** Circuit breaker state */\nexport type CircuitBreakerState = \"closed\" | \"open\" | \"half-open\";\n\n/** Error boundary configuration */\nexport interface ErrorBoundaryConfig {\n\tonConstraintError?: RecoveryStrategy | ((error: Error, constraint: string) => void);\n\tonResolverError?: RecoveryStrategy | ((error: Error, resolver: string) => void);\n\tonEffectError?: RecoveryStrategy | ((error: Error, effect: string) => void);\n\tonDerivationError?: RecoveryStrategy | ((error: Error, derivation: string) => void);\n\tonError?: (error: DirectiveError) => void;\n\n\t/** Configuration for retry-later strategy */\n\tretryLater?: RetryLaterConfig;\n\n\t/** Circuit breaker configuration (applies to resolvers only) */\n\tcircuitBreaker?: CircuitBreakerConfig;\n}\n","/**\n * Type Helpers - External typed constraint and resolver definitions\n *\n * These types enable defining constraints and resolvers with full type safety\n * outside of module definitions, while maintaining proper type inference.\n */\n\nimport type { Schema } from \"./schema.js\";\nimport type { Facts } from \"./facts.js\";\nimport type { Requirement, RequirementOutput } from \"./requirements.js\";\nimport type { ResolverContext, RetryPolicy, BatchConfig } from \"./resolvers.js\";\n\n// ============================================================================\n// Typed Constraint Definition\n// ============================================================================\n\n/**\n * External constraint definition with full typing.\n * Use this when defining constraints outside of createModule().\n *\n * @typeParam S - The schema type\n * @typeParam R - The requirement type (defaults to Requirement)\n *\n * @example\n * ```typescript\n * // Define a typed constraint factory\n * const createMaxCountConstraint = <S extends Schema>(\n * maxCount: number\n * ): TypedConstraint<S, { type: \"RESET_COUNT\" }> => ({\n * priority: 10,\n * when: (facts) => (facts as { count: number }).count > maxCount,\n * require: { type: \"RESET_COUNT\" },\n * });\n *\n * // Use in module\n * const module = createModule(\"counter\", {\n * schema: { count: t.number() },\n * constraints: {\n * maxCount: createMaxCountConstraint(100),\n * },\n * });\n * ```\n */\nexport interface TypedConstraint<\n\tS extends Schema,\n\tR extends Requirement = Requirement,\n> {\n\t/** Priority for ordering (higher runs first) */\n\tpriority?: number;\n\t/** Mark this constraint as async (avoids runtime detection) */\n\tasync?: boolean;\n\t/** Condition function (sync or async) */\n\twhen: (facts: Facts<S>) => boolean | Promise<boolean>;\n\t/**\n\t * Requirement(s) to produce when condition is met.\n\t */\n\trequire: RequirementOutput<R> | ((facts: Facts<S>) => RequirementOutput<R>);\n\t/** Timeout for async constraints (ms) */\n\ttimeout?: number;\n\t/**\n\t * Constraint IDs whose resolvers must complete before this constraint is evaluated.\n\t * - If dependency's `when()` returns false, this constraint proceeds (nothing to wait for)\n\t * - If dependency's resolver fails, this constraint remains blocked until it succeeds\n\t * - Cross-module: use the constraint ID as it appears in the merged system\n\t */\n\tafter?: string[];\n}\n\n// ============================================================================\n// Typed Resolver Definition\n// ============================================================================\n\n/**\n * External resolver definition with full typing.\n * Use this when defining resolvers outside of createModule().\n *\n * @typeParam S - The schema type\n * @typeParam R - The requirement type (defaults to Requirement)\n *\n * @example\n * ```typescript\n * // Define a typed resolver factory\n * interface FetchUserReq extends Requirement {\n * type: \"FETCH_USER\";\n * userId: string;\n * }\n *\n * const createFetchUserResolver = <S extends Schema>(\n * fetchFn: (userId: string) => Promise<User>\n * ): TypedResolver<S, FetchUserReq> => ({\n * requirement: (req): req is FetchUserReq => req.type === \"FETCH_USER\",\n * key: (req) => `fetch-user-${req.userId}`,\n * retry: { attempts: 3, backoff: \"exponential\" },\n * resolve: async (req, ctx) => {\n * const user = await fetchFn(req.userId);\n * (ctx.facts as { user: User }).user = user;\n * },\n * });\n * ```\n */\nexport interface TypedResolver<\n\tS extends Schema,\n\tR extends Requirement = Requirement,\n> {\n\t/**\n\t * Requirement type to handle.\n\t * - String: matches `req.type` directly (e.g., `requirement: \"FETCH_USER\"`)\n\t * - Function: type guard predicate (e.g., `requirement: (req) => req.type === \"FETCH_USER\"`)\n\t */\n\trequirement: R[\"type\"] | ((req: Requirement) => req is R);\n\t/** Custom key function for deduplication */\n\tkey?: (req: R) => string;\n\t/** Retry policy */\n\tretry?: RetryPolicy;\n\t/** Timeout for resolver execution (ms) */\n\ttimeout?: number;\n\t/** Batch configuration */\n\tbatch?: BatchConfig;\n\t/** Resolve function for single requirement */\n\tresolve?: (req: R, ctx: ResolverContext<S>) => Promise<void>;\n\t/** Resolve function for batched requirements */\n\tresolveBatch?: (reqs: R[], ctx: ResolverContext<S>) => Promise<void>;\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create a typed constraint factory for a specific schema.\n * This enables creating reusable constraint definitions with proper typing.\n *\n * @example\n * ```typescript\n * const schema = { count: t.number(), threshold: t.number() };\n * const factory = constraintFactory<typeof schema>();\n *\n * const maxCountConstraint = factory.create({\n * when: (facts) => facts.count > facts.threshold,\n * require: { type: \"RESET\" },\n * });\n * ```\n */\nexport function constraintFactory<S extends Schema>() {\n\treturn {\n\t\t/**\n\t\t * Create a typed constraint\n\t\t */\n\t\tcreate<R extends Requirement = Requirement>(\n\t\t\tconstraint: TypedConstraint<S, R>,\n\t\t): TypedConstraint<S, R> {\n\t\t\treturn constraint;\n\t\t},\n\t};\n}\n\n/**\n * Create a typed resolver factory for a specific schema.\n * This enables creating reusable resolver definitions with proper typing.\n *\n * @example\n * ```typescript\n * const schema = { user: t.object<User>() };\n * const factory = resolverFactory<typeof schema>();\n *\n * const fetchUserResolver = factory.create<FetchUserReq>({\n * requirement: (req): req is FetchUserReq => req.type === \"FETCH_USER\",\n * resolve: async (req, ctx) => {\n * ctx.facts.user = await fetchUser(req.userId);\n * },\n * });\n * ```\n */\nexport function resolverFactory<S extends Schema>() {\n\treturn {\n\t\t/**\n\t\t * Create a typed resolver\n\t\t */\n\t\tcreate<R extends Requirement = Requirement>(\n\t\t\tresolver: TypedResolver<S, R>,\n\t\t): TypedResolver<S, R> {\n\t\t\treturn resolver;\n\t\t},\n\t};\n}\n\n// ============================================================================\n// Simple Helper Functions\n// ============================================================================\n\n/**\n * Type-safe constraint creator.\n * Simpler alternative to constraintFactory when you don't need a factory pattern.\n *\n * @example\n * ```typescript\n * const constraint = typedConstraint<typeof schema, { type: \"RESET\" }>({\n * when: (facts) => facts.count > 100,\n * require: { type: \"RESET\" },\n * });\n * ```\n */\nexport function typedConstraint<\n\tS extends Schema,\n\tR extends Requirement = Requirement,\n>(constraint: TypedConstraint<S, R>): TypedConstraint<S, R> {\n\treturn constraint;\n}\n\n/**\n * Type-safe resolver creator.\n * Simpler alternative to resolverFactory when you don't need a factory pattern.\n *\n * @example\n * ```typescript\n * const resolver = typedResolver<typeof schema, FetchUserReq>({\n * requirement: (req): req is FetchUserReq => req.type === \"FETCH_USER\",\n * resolve: async (req, ctx) => {\n * ctx.facts.user = await fetchUser(req.userId);\n * },\n * });\n * ```\n */\nexport function typedResolver<\n\tS extends Schema,\n\tR extends Requirement = Requirement,\n>(resolver: TypedResolver<S, R>): TypedResolver<S, R> {\n\treturn resolver;\n}\n","/**\n * Composition Types - Type definitions for single and multi-module systems\n *\n * Single module = direct access (no namespace):\n * @example\n * ```typescript\n * const system = createSystem({ modules: counterModule });\n * system.facts.count // Direct access\n * system.events.increment() // Direct events\n * ```\n *\n * Multiple modules = namespaced access:\n * @example\n * ```typescript\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n * system.facts.auth.token // Namespaced access\n * system.derive.data.userCount // Namespaced derivations\n * system.events.auth.login() // Namespaced events\n * ```\n */\n\nimport type {\n\tModuleSchema,\n\tInferFacts,\n\tInferDerivations,\n\tInferEvents,\n} from \"./schema.js\";\nimport type { Facts } from \"./facts.js\";\nimport type { ModuleDef } from \"./module.js\";\nimport type {\n\tDebugConfig,\n\tTimeTravelAPI,\n\tSystemInspection,\n\tSystemSnapshot,\n\tDistributableSnapshotOptions,\n\tDistributableSnapshot,\n} from \"./system.js\";\nimport type { Plugin } from \"./plugins.js\";\nimport type { ErrorBoundaryConfig } from \"./errors.js\";\n\n// ============================================================================\n// Module Map Types\n// ============================================================================\n\n/**\n * Extract the schema type from a module definition.\n */\nexport type ExtractSchema<M> = M extends ModuleDef<infer S> ? S : never;\n\n/**\n * Map of module name to module definition (object form).\n *\n * Uses `ModuleDef<any>` instead of `ModuleDef<ModuleSchema>` to preserve\n * specific schema types during inference. The actual schema types are\n * extracted via `ExtractSchema<M>` where needed.\n */\n// biome-ignore lint/suspicious/noExplicitAny: Required for TypeScript to preserve specific module schema types during inference\nexport type ModulesMap = Record<string, ModuleDef<any>>;\n\n// ============================================================================\n// Cross-Module Facts Types (for module-level type hints)\n// ============================================================================\n\n/**\n * Map of module name to schema (for cross-module typing).\n */\nexport type SchemasMap = Record<string, ModuleSchema>;\n\n/**\n * Create namespaced facts type from a map of schemas.\n * Use this to type cross-module effects and constraints within modules.\n *\n * @example\n * ```typescript\n * // types.ts - Create the combined type from schemas\n * import { authSchema } from './modules/auth';\n * import { dataSchema } from './modules/data';\n * import { uiSchema } from './modules/ui';\n * import type { CrossModuleFacts } from '@directive-run/core';\n *\n * export type AllFacts = CrossModuleFacts<{\n * auth: typeof authSchema;\n * data: typeof dataSchema;\n * ui: typeof uiSchema;\n * }>;\n *\n * // modules/ui.ts - Use the combined type in effects\n * import type { AllFacts } from '../types';\n *\n * effects: {\n * onAuthChange: {\n * run: (facts: AllFacts, prev: AllFacts | undefined) => {\n * facts.auth.isAuthenticated // ✅ typed!\n * facts.data.users // ✅ typed!\n * }\n * }\n * }\n * ```\n */\nexport type CrossModuleFacts<Schemas extends SchemasMap> = {\n\t[K in keyof Schemas]: InferFacts<Schemas[K]>;\n};\n\n/**\n * Create namespaced derivations type from a map of schemas.\n * Use this to type cross-module effects that read derivations.\n *\n * @example\n * ```typescript\n * import type { CrossModuleDerivations } from '@directive-run/core';\n *\n * export type AllDerivations = CrossModuleDerivations<{\n * auth: typeof authSchema;\n * data: typeof dataSchema;\n * }>;\n * ```\n */\nexport type CrossModuleDerivations<Schemas extends SchemasMap> = {\n\treadonly [K in keyof Schemas]: InferDerivations<Schemas[K]>;\n};\n\n// ============================================================================\n// Cross-Module Dependencies Types (for module-level crossModuleDeps)\n// ============================================================================\n\n/**\n * Map of namespace to schema for cross-module dependencies.\n * Used in module config to declare type-safe access to other modules' facts.\n */\nexport type CrossModuleDeps = Record<string, ModuleSchema>;\n\n/**\n * Cross-module facts type using \"self\" for own module.\n * Own module accessed via `facts.self.*`, dependencies via `facts.{dep}.*`.\n *\n * @example\n * ```typescript\n * // For a \"data\" module with crossModuleDeps: { auth: authSchema }\n * facts.self.users // ✅ own module via \"self\"\n * facts.auth.isAuthenticated // ✅ cross-module via namespace\n * ```\n */\nexport type CrossModuleFactsWithSelf<\n\tOwnSchema extends ModuleSchema,\n\tDeps extends CrossModuleDeps,\n> = { self: InferFacts<OwnSchema> } & {\n\t[K in keyof Deps]: InferFacts<Deps[K]>;\n};\n\n// ============================================================================\n// Namespaced Facts Types\n// ============================================================================\n\n/**\n * Namespace facts under module keys.\n * `facts.auth.token` instead of `facts.auth_token`\n */\nexport type NamespacedFacts<Modules extends ModulesMap> = {\n\treadonly [K in keyof Modules]: InferFacts<ExtractSchema<Modules[K]>>;\n};\n\n/**\n * Mutable version for constraint/resolver callbacks.\n */\nexport type MutableNamespacedFacts<Modules extends ModulesMap> = {\n\t[K in keyof Modules]: InferFacts<ExtractSchema<Modules[K]>>;\n};\n\n// ============================================================================\n// Namespaced Derivations Types\n// ============================================================================\n\n/**\n * Namespace derivations under module keys.\n * `derive.auth.status` instead of `derive.auth_status`\n */\nexport type NamespacedDerivations<Modules extends ModulesMap> = {\n\treadonly [K in keyof Modules]: InferDerivations<ExtractSchema<Modules[K]>>;\n};\n\n// ============================================================================\n// Union Event Types\n// ============================================================================\n\n/**\n * Union of all module events (not namespaced).\n * Events stay as discriminated union for dispatch.\n */\nexport type UnionEvents<Modules extends ModulesMap> = {\n\t[K in keyof Modules]: InferEvents<ExtractSchema<Modules[K]>>;\n}[keyof Modules];\n\n// ============================================================================\n// Namespaced System Options\n// ============================================================================\n\n/**\n * Options for createSystem with object modules (namespaced mode).\n */\nexport interface CreateSystemOptionsNamed<Modules extends ModulesMap> {\n\t/** Modules as object = namespaced access */\n\tmodules: Modules;\n\t/** Plugins to register */\n\tplugins?: Array<Plugin<ModuleSchema>>;\n\t/** Debug configuration */\n\tdebug?: DebugConfig;\n\t/** Error boundary configuration */\n\terrorBoundary?: ErrorBoundaryConfig;\n\t/**\n\t * Tick interval for time-based systems (ms).\n\t */\n\ttickMs?: number;\n\t/**\n\t * Enable zero-config mode with sensible defaults.\n\t */\n\tzeroConfig?: boolean;\n\t/**\n\t * Initial facts to set after module init (namespaced format).\n\t * Applied after all module `init()` functions but before reconciliation.\n\t *\n\t * @example\n\t * ```typescript\n\t * createSystem({\n\t * modules: { auth, data },\n\t * initialFacts: {\n\t * auth: { token: \"restored-token\", user: cachedUser },\n\t * data: { users: preloadedUsers },\n\t * },\n\t * });\n\t * ```\n\t */\n\tinitialFacts?: Partial<{\n\t\t[K in keyof Modules]: Partial<InferFacts<ExtractSchema<Modules[K]>>>;\n\t}>;\n\t/**\n\t * Init order strategy:\n\t * - \"auto\" (default): Sort by crossModuleDeps topology\n\t * - \"declaration\": Use object key order (current behavior)\n\t * - string[]: Explicit order by namespace\n\t */\n\tinitOrder?: \"auto\" | \"declaration\" | Array<keyof Modules & string>;\n}\n\n// ============================================================================\n// Namespaced System Interface\n// ============================================================================\n\n/**\n * System interface for namespaced modules.\n * Facts and derivations are accessed via module namespaces.\n */\nexport interface NamespacedSystem<Modules extends ModulesMap> {\n\t/** System mode discriminator for type guards */\n\treadonly _mode: \"namespaced\";\n\t/** Namespaced facts accessor: system.facts.auth.token */\n\treadonly facts: MutableNamespacedFacts<Modules>;\n\t/** Time-travel debugging API (if enabled) */\n\treadonly debug: TimeTravelAPI | null;\n\t/** Namespaced derivations accessor: system.derive.auth.status */\n\treadonly derive: NamespacedDerivations<Modules>;\n\t/** Events accessor (union of all module events) */\n\treadonly events: NamespacedEventsAccessor<Modules>;\n\n\t/** Start the system (initialize modules, begin reconciliation) */\n\tstart(): void;\n\t/** Stop the system (cancel resolvers, stop reconciliation) */\n\tstop(): void;\n\t/** Destroy the system (stop and cleanup) */\n\tdestroy(): void;\n\n\t/** Whether the system is currently running */\n\treadonly isRunning: boolean;\n\t/** Whether all resolvers have completed */\n\treadonly isSettled: boolean;\n\t/** Whether all modules have completed initialization */\n\treadonly isInitialized: boolean;\n\t/** Whether system has completed first reconciliation */\n\treadonly isReady: boolean;\n\n\t/** Wait for system to be fully ready (after first reconciliation) */\n\twhenReady(): Promise<void>;\n\n\t/**\n\t * Hydrate facts from async source (call before start).\n\t * Useful for restoring state from localStorage, API, etc.\n\t *\n\t * @example\n\t * ```typescript\n\t * const system = createSystem({ modules: { auth, data } });\n\t * await system.hydrate(async () => {\n\t * const stored = localStorage.getItem(\"app-state\");\n\t * return stored ? JSON.parse(stored) : {};\n\t * });\n\t * system.start();\n\t * ```\n\t */\n\thydrate(\n\t\tloader: () => Promise<Partial<{\n\t\t\t[K in keyof Modules]: Partial<InferFacts<ExtractSchema<Modules[K]>>>;\n\t\t}>> | Partial<{\n\t\t\t[K in keyof Modules]: Partial<InferFacts<ExtractSchema<Modules[K]>>>;\n\t\t}>,\n\t): Promise<void>;\n\n\t/** Dispatch an event (union of all module events) */\n\tdispatch(event: UnionEvents<Modules>): void;\n\n\t/** Batch multiple fact changes */\n\tbatch(fn: () => void): void;\n\n\t/**\n\t * Subscribe to settlement state changes.\n\t * Called whenever the system's settled state may have changed\n\t * (resolver starts/completes, reconcile starts/ends).\n\t */\n\tonSettledChange(listener: () => void): () => void;\n\n\t/** Subscribe to time-travel state changes (snapshot taken, navigation). */\n\tonTimeTravelChange(listener: () => void): () => void;\n\n\t/**\n\t * Read a derivation value by namespaced key.\n\t * Accepts \"namespace.key\" format (e.g., \"auth.status\").\n\t *\n\t * @example\n\t * system.read(\"auth.status\") // → \"authenticated\"\n\t * system.read(\"data.count\") // → 5\n\t */\n\tread<T = unknown>(derivationId: string): T;\n\n\t/**\n\t * Subscribe to fact or derivation changes using namespaced keys.\n\t * Keys are auto-detected — pass any mix of fact keys and derivation keys.\n\t * Accepts \"namespace.key\" format (e.g., \"auth.status\", \"auth.token\").\n\t * Supports wildcard \"namespace.*\" to subscribe to all keys in a module.\n\t *\n\t * @example\n\t * system.subscribe([\"auth.token\", \"data.count\"], () => {\n\t * console.log(\"Auth or data changed\");\n\t * });\n\t *\n\t * @example Wildcard\n\t * system.subscribe([\"game.*\"], () => render());\n\t */\n\tsubscribe(ids: string[], listener: () => void): () => void;\n\n\t/**\n\t * Subscribe to ALL fact and derivation changes in a module namespace.\n\t * Shorthand for subscribing to every key in a module.\n\t *\n\t * @example\n\t * system.subscribeModule(\"game\", () => render());\n\t * system.subscribeModule(\"chat\", () => render());\n\t */\n\tsubscribeModule(namespace: keyof Modules & string, listener: () => void): () => void;\n\n\t/**\n\t * Watch a fact or derivation for changes using namespaced key.\n\t * The key is auto-detected -- works with both fact keys and derivation keys.\n\t * Accepts \"namespace.key\" format (e.g., \"auth.status\", \"auth.token\").\n\t * Pass `options.equalityFn` for custom comparison (e.g., shallow equality for objects).\n\t *\n\t * @example\n\t * system.watch(\"auth.token\", (newVal, oldVal) => {\n\t * console.log(`Token changed from ${oldVal} to ${newVal}`);\n\t * });\n\t */\n\twatch<T = unknown>(\n\t\tid: string,\n\t\tcallback: (newValue: T, previousValue: T | undefined) => void,\n\t\toptions?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n\t): () => void;\n\n\t/**\n\t * Returns a promise that resolves when the predicate becomes true.\n\t * The predicate is evaluated against current facts and re-evaluated on every change.\n\t * Uses namespaced facts: `facts.auth.token`, `facts.data.count`, etc.\n\t * Optionally pass a timeout in ms -- rejects with an error if exceeded.\n\t *\n\t * @example\n\t * await system.when((facts) => facts.auth.token !== null);\n\t * await system.when((facts) => facts.auth.token !== null, { timeout: 5000 });\n\t */\n\twhen(\n\t\tpredicate: (facts: Readonly<MutableNamespacedFacts<Modules>>) => boolean,\n\t\toptions?: { timeout?: number },\n\t): Promise<void>;\n\n\t/** Inspect system state */\n\tinspect(): SystemInspection;\n\t/** Wait for system to settle (all resolvers complete) */\n\tsettle(maxWait?: number): Promise<void>;\n\t/** Explain why a requirement exists */\n\texplain(requirementId: string): string | null;\n\t/** Get serializable snapshot of system state */\n\tgetSnapshot(): SystemSnapshot;\n\t/** Restore system state from snapshot */\n\trestore(snapshot: SystemSnapshot): void;\n\n\t/**\n\t * Register a new module into a running system.\n\t * The module is initialized, wired into constraint/resolver/derivation graphs,\n\t * and reconciliation is triggered.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Lazy-load a module\n\t * const chatModule = await import('./modules/chat');\n\t * system.registerModule(\"chat\", chatModule.default);\n\t * ```\n\t */\n\tregisterModule<S extends ModuleSchema>(\n\t\tnamespace: string,\n\t\tmoduleDef: ModuleDef<S>,\n\t): void;\n\n\t/**\n\t * Get a distributable snapshot of computed derivations.\n\t * Use \"namespace.key\" format for derivation keys.\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = system.getDistributableSnapshot({\n\t * includeDerivations: ['auth.effectivePlan', 'auth.canUseFeature'],\n\t * ttlSeconds: 3600,\n\t * });\n\t * await redis.setex(`entitlements:${userId}`, 3600, JSON.stringify(snapshot));\n\t * ```\n\t */\n\tgetDistributableSnapshot<T = Record<string, unknown>>(\n\t\toptions?: DistributableSnapshotOptions,\n\t): DistributableSnapshot<T>;\n\n\t/**\n\t * Watch for changes to distributable snapshot derivations.\n\t * Calls the callback whenever any of the included derivations change.\n\t * Use \"namespace.key\" format for derivation keys.\n\t * Returns an unsubscribe function.\n\t *\n\t * @example\n\t * ```typescript\n\t * const unsubscribe = system.watchDistributableSnapshot(\n\t * { includeDerivations: ['auth.effectivePlan', 'auth.canUseFeature'] },\n\t * (snapshot) => {\n\t * await redis.setex(`entitlements:${userId}`, 3600, JSON.stringify(snapshot));\n\t * }\n\t * );\n\t * ```\n\t */\n\twatchDistributableSnapshot<T = Record<string, unknown>>(\n\t\toptions: DistributableSnapshotOptions,\n\t\tcallback: (snapshot: DistributableSnapshot<T>) => void,\n\t): () => void;\n}\n\n/**\n * Events accessor that groups event dispatchers by module namespace.\n */\nexport type NamespacedEventsAccessor<Modules extends ModulesMap> = {\n\treadonly [K in keyof Modules]: EventsDispatcherForModule<Modules[K]>;\n};\n\n/**\n * Event dispatcher functions for a single module.\n */\ntype EventsDispatcherForModule<M> = M extends ModuleDef<infer S>\n\t? S extends ModuleSchema\n\t\t? S[\"events\"] extends Record<string, unknown>\n\t\t\t? {\n\t\t\t\t\t[E in keyof S[\"events\"]]: S[\"events\"][E] extends Record<string, unknown>\n\t\t\t\t\t\t? keyof S[\"events\"][E] extends never\n\t\t\t\t\t\t\t? () => void\n\t\t\t\t\t\t\t: (payload: InferEventPayload<S[\"events\"][E]>) => void\n\t\t\t\t\t\t: () => void;\n\t\t\t\t}\n\t\t\t: Record<string, never>\n\t\t: Record<string, never>\n\t: Record<string, never>;\n\n/**\n * Infer event payload from event schema.\n */\ntype InferEventPayload<E> = E extends Record<string, unknown>\n\t? { [K in keyof E]: E[K] extends { _type: infer T } ? T : E[K] }\n\t: never;\n\n// ============================================================================\n// Merged Schema Type (for internal use)\n// ============================================================================\n\n/**\n * Merge multiple module schemas into a single flat schema.\n * Used internally by the engine for storage.\n *\n * @example\n * ```typescript\n * // auth: { facts: { token: string } }\n * // data: { facts: { users: User[] } }\n * // Merged: { auth_token: string, data_users: User[] }\n * ```\n */\nexport type MergedModuleSchema<Modules extends ModulesMap> = {\n\tfacts: MergeFactsWithPrefix<Modules>;\n\tderivations: MergeDerivationsWithPrefix<Modules>;\n\tevents: MergeEventsWithPrefix<Modules>;\n\trequirements: MergeRequirementsWithPrefix<Modules>;\n};\n\ntype MergeFactsWithPrefix<Modules extends ModulesMap> = {\n\t[K in keyof Modules as `${K & string}::${keyof ExtractSchema<Modules[K]>[\"facts\"] & string}`]: ExtractSchema<Modules[K]>[\"facts\"][keyof ExtractSchema<Modules[K]>[\"facts\"]];\n};\n\ntype MergeDerivationsWithPrefix<Modules extends ModulesMap> = {\n\t[K in keyof Modules as ExtractSchema<Modules[K]>[\"derivations\"] extends Record<string, unknown>\n\t\t? `${K & string}::${keyof ExtractSchema<Modules[K]>[\"derivations\"] & string}`\n\t\t: never]: ExtractSchema<Modules[K]>[\"derivations\"] extends Record<string, unknown>\n\t\t? ExtractSchema<Modules[K]>[\"derivations\"][keyof ExtractSchema<Modules[K]>[\"derivations\"]]\n\t\t: never;\n};\n\ntype MergeEventsWithPrefix<Modules extends ModulesMap> = {\n\t[K in keyof Modules as ExtractSchema<Modules[K]>[\"events\"] extends Record<string, unknown>\n\t\t? `${K & string}::${keyof ExtractSchema<Modules[K]>[\"events\"] & string}`\n\t\t: never]: ExtractSchema<Modules[K]>[\"events\"] extends Record<string, unknown>\n\t\t? ExtractSchema<Modules[K]>[\"events\"][keyof ExtractSchema<Modules[K]>[\"events\"]]\n\t\t: never;\n};\n\ntype MergeRequirementsWithPrefix<Modules extends ModulesMap> = {\n\t[K in keyof Modules as ExtractSchema<Modules[K]>[\"requirements\"] extends Record<string, unknown>\n\t\t? keyof ExtractSchema<Modules[K]>[\"requirements\"] & string\n\t\t: never]: ExtractSchema<Modules[K]>[\"requirements\"] extends Record<string, unknown>\n\t\t? ExtractSchema<Modules[K]>[\"requirements\"][keyof ExtractSchema<Modules[K]>[\"requirements\"]]\n\t\t: never;\n};\n\n// ============================================================================\n// Single Module Types (no namespace)\n// ============================================================================\n\n/**\n * Options for createSystem with a single module (no namespacing).\n */\nexport interface CreateSystemOptionsSingle<S extends ModuleSchema> {\n\t/** Single module = direct access (use `modules` for multiple) */\n\tmodule: ModuleDef<S>;\n\t/** Plugins to register */\n\tplugins?: Array<Plugin<ModuleSchema>>;\n\t/** Debug configuration */\n\tdebug?: DebugConfig;\n\t/** Error boundary configuration */\n\terrorBoundary?: ErrorBoundaryConfig;\n\t/** Tick interval for time-based systems (ms) */\n\ttickMs?: number;\n\t/** Enable zero-config mode with sensible defaults */\n\tzeroConfig?: boolean;\n\t/**\n\t * Initial facts to set after module init.\n\t * Applied after module `init()` but before reconciliation.\n\t */\n\tinitialFacts?: Partial<InferFacts<S>>;\n}\n\n/**\n * System interface for a single module (no namespace).\n * Facts, derivations, and events are accessed directly.\n */\nexport interface SingleModuleSystem<S extends ModuleSchema> {\n\t/** System mode discriminator for type guards */\n\treadonly _mode: \"single\";\n\t/** Direct facts accessor: system.facts.count */\n\treadonly facts: Facts<S[\"facts\"]>;\n\t/** Time-travel debugging API (if enabled) */\n\treadonly debug: TimeTravelAPI | null;\n\t/** Direct derivations accessor: system.derive.doubled */\n\treadonly derive: InferDerivations<S>;\n\t/** Direct events accessor: system.events.increment() */\n\treadonly events: SingleModuleEvents<S>;\n\n\t/** Start the system (initialize modules, begin reconciliation) */\n\tstart(): void;\n\t/** Stop the system (cancel resolvers, stop reconciliation) */\n\tstop(): void;\n\t/** Destroy the system (stop and cleanup) */\n\tdestroy(): void;\n\n\t/** Whether the system is currently running */\n\treadonly isRunning: boolean;\n\t/** Whether all resolvers have completed */\n\treadonly isSettled: boolean;\n\t/** Whether module has completed initialization */\n\treadonly isInitialized: boolean;\n\t/** Whether system has completed first reconciliation */\n\treadonly isReady: boolean;\n\n\t/** Wait for system to be fully ready (after first reconciliation) */\n\twhenReady(): Promise<void>;\n\n\t/**\n\t * Hydrate facts from async source (call before start).\n\t */\n\thydrate(\n\t\tloader: () => Promise<Partial<InferFacts<S>>> | Partial<InferFacts<S>>,\n\t): Promise<void>;\n\n\t/** Dispatch an event */\n\tdispatch(event: InferEvents<S>): void;\n\n\t/** Batch multiple fact changes */\n\tbatch(fn: () => void): void;\n\n\t/**\n\t * Subscribe to settlement state changes.\n\t * Called whenever the system's settled state may have changed\n\t * (resolver starts/completes, reconcile starts/ends).\n\t */\n\tonSettledChange(listener: () => void): () => void;\n\n\t/** Subscribe to time-travel state changes (snapshot taken, navigation). */\n\tonTimeTravelChange(listener: () => void): () => void;\n\n\t/**\n\t * Read a derivation value by key.\n\t * @example system.read(\"doubled\")\n\t */\n\tread<T = unknown>(derivationId: string): T;\n\n\t/**\n\t * Subscribe to fact or derivation changes.\n\t * Keys are auto-detected -- pass any mix of fact keys and derivation keys.\n\t * @example system.subscribe([\"count\", \"doubled\"], () => { ... })\n\t */\n\tsubscribe(ids: string[], listener: () => void): () => void;\n\n\t/**\n\t * Watch a fact or derivation for value changes.\n\t * The key is auto-detected -- works with both fact keys and derivation keys.\n\t * Pass `options.equalityFn` for custom comparison (e.g., shallow equality for objects).\n\t * @example system.watch(\"count\", (newVal, oldVal) => { ... })\n\t * @example system.watch(\"derived\", cb, { equalityFn: shallowEqual })\n\t */\n\twatch<T = unknown>(\n\t\tid: string,\n\t\tcallback: (newValue: T, previousValue: T | undefined) => void,\n\t\toptions?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n\t): () => void;\n\n\t/**\n\t * Returns a promise that resolves when the predicate becomes true.\n\t * The predicate is evaluated against current facts and re-evaluated on every change.\n\t * Optionally pass a timeout in ms -- rejects with an error if exceeded.\n\t *\n\t * @example\n\t * await system.when((facts) => facts.count > 10);\n\t * await system.when((facts) => facts.count > 10, { timeout: 5000 });\n\t */\n\twhen(\n\t\tpredicate: (facts: Readonly<InferFacts<S>>) => boolean,\n\t\toptions?: { timeout?: number },\n\t): Promise<void>;\n\n\t/** Inspect system state */\n\tinspect(): SystemInspection;\n\t/** Wait for system to settle (all resolvers complete) */\n\tsettle(maxWait?: number): Promise<void>;\n\t/** Explain why a requirement exists */\n\texplain(requirementId: string): string | null;\n\t/** Get serializable snapshot of system state */\n\tgetSnapshot(): SystemSnapshot;\n\t/** Restore system state from snapshot */\n\trestore(snapshot: SystemSnapshot): void;\n\n\t/**\n\t * Register a new module into a running system.\n\t * Module facts, derivations, effects, constraints, and resolvers are merged\n\t * into the existing engine and reconciliation is triggered.\n\t *\n\t * @example\n\t * ```typescript\n\t * const analyticsModule = await import('./modules/analytics');\n\t * system.registerModule(analyticsModule.default);\n\t * ```\n\t */\n\tregisterModule<S2 extends ModuleSchema>(moduleDef: ModuleDef<S2>): void;\n\n\t/**\n\t * Get a distributable snapshot of computed derivations.\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = system.getDistributableSnapshot({\n\t * includeDerivations: ['effectivePlan', 'canUseFeature'],\n\t * ttlSeconds: 3600,\n\t * });\n\t * await redis.setex(`entitlements:${userId}`, 3600, JSON.stringify(snapshot));\n\t * ```\n\t */\n\tgetDistributableSnapshot<T = Record<string, unknown>>(\n\t\toptions?: DistributableSnapshotOptions,\n\t): DistributableSnapshot<T>;\n\n\t/**\n\t * Watch for changes to distributable snapshot derivations.\n\t * Calls the callback whenever any of the included derivations change.\n\t * Returns an unsubscribe function.\n\t *\n\t * @example\n\t * ```typescript\n\t * const unsubscribe = system.watchDistributableSnapshot(\n\t * { includeDerivations: ['effectivePlan', 'canUseFeature'] },\n\t * (snapshot) => {\n\t * await redis.setex(`entitlements:${userId}`, 3600, JSON.stringify(snapshot));\n\t * }\n\t * );\n\t * ```\n\t */\n\twatchDistributableSnapshot<T = Record<string, unknown>>(\n\t\toptions: DistributableSnapshotOptions,\n\t\tcallback: (snapshot: DistributableSnapshot<T>) => void,\n\t): () => void;\n}\n\n/**\n * Events dispatcher for a single module (direct access).\n */\ntype SingleModuleEvents<S extends ModuleSchema> = S[\"events\"] extends Record<\n\tstring,\n\tunknown\n>\n\t? {\n\t\t\t[E in keyof S[\"events\"]]: S[\"events\"][E] extends Record<string, unknown>\n\t\t\t\t? keyof S[\"events\"][E] extends never\n\t\t\t\t\t? () => void\n\t\t\t\t\t: (payload: InferEventPayload<S[\"events\"][E]>) => void\n\t\t\t\t: () => void;\n\t\t}\n\t: Record<string, never>;\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * System mode discriminator.\n * - \"single\": Single module with direct access (`system.facts.count`)\n * - \"namespaced\": Multiple modules with namespaced access (`system.facts.auth.token`)\n */\nexport type SystemMode = \"single\" | \"namespaced\";\n\n/**\n * Base system type for type guards.\n * Use this for functions that accept either system type.\n */\nexport interface AnySystem {\n\treadonly _mode: SystemMode;\n\treadonly isRunning: boolean;\n\treadonly isSettled: boolean;\n\treadonly isInitialized: boolean;\n\treadonly isReady: boolean;\n\tstart(): void;\n\tstop(): void;\n\tdestroy(): void;\n}\n\n/**\n * Check if a system is a single module system.\n * Returns true if the system was created with `module:` (singular).\n *\n * @example\n * ```typescript\n * const system = createSystem({ module: counterModule });\n *\n * if (isSingleModuleSystem(system)) {\n * // system._mode === \"single\"\n * console.log(system.facts.count);\n * }\n * ```\n */\nexport function isSingleModuleSystem(system: AnySystem): boolean {\n\treturn system._mode === \"single\";\n}\n\n/**\n * Check if a system is a namespaced (multi-module) system.\n * Returns true if the system was created with `modules:` (plural, object).\n *\n * @example\n * ```typescript\n * const system = createSystem({ modules: { auth, data } });\n *\n * if (isNamespacedSystem(system)) {\n * // system._mode === \"namespaced\"\n * console.log(system.facts.auth.token);\n * }\n * ```\n */\nexport function isNamespacedSystem(system: AnySystem): boolean {\n\treturn system._mode === \"namespaced\";\n}\n","/**\n * Dependency tracking context for auto-tracking derivations\n *\n * Uses a stack-based approach to handle nested derivation computations.\n * When a derivation accesses a fact, the tracking context records it.\n */\n\nimport type { TrackingContext } from \"./types.js\";\n\n/** Stack of active tracking contexts */\nconst trackingStack: TrackingContext[] = [];\n\n/** Create a new tracking context */\nfunction createTrackingContext(): TrackingContext {\n\tconst dependencies = new Set<string>();\n\n\treturn {\n\t\tget isTracking() {\n\t\t\treturn true;\n\t\t},\n\t\ttrack(key: string) {\n\t\t\tdependencies.add(key);\n\t\t},\n\t\tgetDependencies() {\n\t\t\treturn dependencies;\n\t\t},\n\t};\n}\n\n/** Null tracking context when not tracking */\nconst nullContext: TrackingContext = {\n\tisTracking: false,\n\ttrack() {},\n\tgetDependencies() {\n\t\treturn new Set();\n\t},\n};\n\n/**\n * Get the current tracking context.\n * Returns null context if no tracking is active.\n */\nexport function getCurrentTracker(): TrackingContext {\n\treturn trackingStack[trackingStack.length - 1] ?? nullContext;\n}\n\n/**\n * Check if we're currently tracking dependencies.\n */\nexport function isTracking(): boolean {\n\treturn trackingStack.length > 0;\n}\n\n/**\n * Run a function with dependency tracking.\n * Returns the computed value and the set of dependencies accessed.\n */\nexport function withTracking<T>(fn: () => T): { value: T; deps: Set<string> } {\n\tconst context = createTrackingContext();\n\ttrackingStack.push(context);\n\n\ttry {\n\t\tconst value = fn();\n\t\treturn { value, deps: context.getDependencies() };\n\t} finally {\n\t\ttrackingStack.pop();\n\t}\n}\n\n/**\n * Run a function without tracking.\n * Useful for reading facts without creating dependencies.\n */\nexport function withoutTracking<T>(fn: () => T): T {\n\t// Temporarily clear the stack\n\tconst saved = trackingStack.splice(0, trackingStack.length);\n\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\t// Restore the stack\n\t\ttrackingStack.push(...saved);\n\t}\n}\n\n/**\n * Track a specific key in the current context.\n * No-op if not currently tracking.\n */\nexport function trackAccess(key: string): void {\n\tgetCurrentTracker().track(key);\n}\n","/**\n * Facts Store - Proxy-based reactive state with auto-tracking\n *\n * Features:\n * - Proxy-based access (facts.phase instead of facts.get(\"phase\"))\n * - Automatic dependency tracking via tracking context\n * - Batched updates with coalesced notifications\n * - Granular subscriptions by key\n * - Schema validation in development mode\n */\n\nimport { trackAccess, withoutTracking } from \"./tracking.js\";\nimport type {\n\tFacts,\n\tFactsSnapshot,\n\tFactsStore,\n\tInferSchema,\n\tSchema,\n\tSchemaType,\n} 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\treadonly _typeName?: string;\n\treadonly _default?: T | (() => T);\n\treadonly _transform?: (value: unknown) => T;\n\treadonly _description?: string;\n\treadonly _refinements?: Array<{ predicate: (value: T) => boolean; message: string }>;\n\t/** Mutable - set by array validators to indicate which element failed */\n\t_lastFailedIndex?: number;\n}\n\n/** Safely stringify a value for error messages */\nfunction safeStringify(value: unknown, maxLength = 100): string {\n\ttry {\n\t\treturn JSON.stringify(value)?.slice(0, maxLength) ?? String(value);\n\t} catch {\n\t\treturn \"[circular or non-serializable]\";\n\t}\n}\n\n/** Track types that have already warned to avoid spam */\nconst warnedTypes = new Set<string>();\n\n/** Create a schema type builder with optional type name */\nfunction createSchemaType<T>(\n\tvalidators: Array<(v: T) => boolean> = [],\n\ttypeName?: string,\n\tdefaultValue?: T | (() => T),\n\ttransform?: (value: unknown) => T,\n\tdescription?: string,\n\trefinements?: Array<{ predicate: (value: T) => boolean; message: string }>,\n): ExtendedSchemaType<T> {\n\treturn {\n\t\t_type: undefined as unknown as T,\n\t\t_validators: validators,\n\t\t_typeName: typeName,\n\t\t_default: defaultValue,\n\t\t_transform: transform,\n\t\t_description: description,\n\t\t_refinements: refinements,\n\t\tvalidate(fn: (value: T) => boolean) {\n\t\t\treturn createSchemaType([...validators, fn], typeName, defaultValue, transform, description, refinements);\n\t\t},\n\t};\n}\n\n/** Chainable schema type with all common methods */\nexport interface ChainableSchemaType<T> extends ExtendedSchemaType<T> {\n\tdefault(value: T | (() => T)): ChainableSchemaType<T>;\n\ttransform<U>(fn: (value: T) => U): ChainableSchemaType<U>;\n\tbrand<B extends string>(): ChainableSchemaType<Branded<T, B>>;\n\tdescribe(description: string): ChainableSchemaType<T>;\n\trefine(predicate: (value: T) => boolean, message: string): ChainableSchemaType<T>;\n\tnullable(): ChainableSchemaType<T | null>;\n\toptional(): ChainableSchemaType<T | undefined>;\n}\n\n/** Create a chainable schema type with common methods */\nfunction createChainableType<T>(\n\tvalidators: Array<(v: T) => boolean>,\n\ttypeName: string,\n\tdefaultValue?: T | (() => T),\n\ttransform?: (value: unknown) => T,\n\tdescription?: string,\n\trefinements?: Array<{ predicate: (value: T) => boolean; message: string }>,\n): ChainableSchemaType<T> {\n\tconst base = createSchemaType<T>(validators, typeName, defaultValue, transform, description, refinements);\n\treturn {\n\t\t...base,\n\t\tdefault(value: T | (() => T)) {\n\t\t\treturn createChainableType(validators, typeName, value, transform, description, refinements);\n\t\t},\n\t\ttransform<U>(fn: (value: T) => U) {\n\t\t\tconst newTransform = (v: unknown) => {\n\t\t\t\tconst intermediate = transform ? transform(v) : v as T;\n\t\t\t\treturn fn(intermediate);\n\t\t\t};\n\t\t\treturn createChainableType<U>([], typeName, undefined, newTransform as (v: unknown) => U, description);\n\t\t},\n\t\tbrand<B extends string>() {\n\t\t\treturn createChainableType<Branded<T, B>>(\n\t\t\t\tvalidators as Array<(v: Branded<T, B>) => boolean>,\n\t\t\t\t`Branded<${typeName}>`,\n\t\t\t\tdefaultValue as Branded<T, B> | (() => Branded<T, B>),\n\t\t\t\ttransform as (value: unknown) => Branded<T, B>,\n\t\t\t\tdescription,\n\t\t\t\trefinements as Array<{ predicate: (value: Branded<T, B>) => boolean; message: string }>,\n\t\t\t);\n\t\t},\n\t\tdescribe(desc: string) {\n\t\t\treturn createChainableType(validators, typeName, defaultValue, transform, desc, refinements);\n\t\t},\n\t\trefine(predicate: (value: T) => boolean, message: string) {\n\t\t\tconst newRefinements = [...(refinements ?? []), { predicate, message }];\n\t\t\treturn createChainableType(\n\t\t\t\t[...validators, predicate],\n\t\t\t\ttypeName,\n\t\t\t\tdefaultValue,\n\t\t\t\ttransform,\n\t\t\t\tdescription,\n\t\t\t\tnewRefinements,\n\t\t\t);\n\t\t},\n\t\tnullable() {\n\t\t\treturn createChainableType<T | null>(\n\t\t\t\t[(v): v is T | null => v === null || validators.every(fn => fn(v as T))],\n\t\t\t\t`${typeName} | null`,\n\t\t\t\tdefaultValue as (T | null) | (() => T | null),\n\t\t\t\ttransform as (value: unknown) => T | null,\n\t\t\t\tdescription,\n\t\t\t);\n\t\t},\n\t\toptional() {\n\t\t\treturn createChainableType<T | undefined>(\n\t\t\t\t[(v): v is T | undefined => v === undefined || validators.every(fn => fn(v as T))],\n\t\t\t\t`${typeName} | undefined`,\n\t\t\t\tdefaultValue as (T | undefined) | (() => T | undefined),\n\t\t\t\ttransform as (value: unknown) => T | undefined,\n\t\t\t\tdescription,\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * Schema type builders for defining fact types.\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 */\nexport const t = {\n\t/**\n\t * Create a string schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Basic string\n\t * schema: { name: t.string() }\n\t *\n\t * // String literal union (for type safety)\n\t * schema: { phase: t.string<\"red\" | \"green\" | \"yellow\">() }\n\t *\n\t * // With custom validation\n\t * schema: { email: t.string().validate(s => s.includes(\"@\")) }\n\t *\n\t * // With transform\n\t * schema: { trimmed: t.string().transform(s => s.trim()) }\n\t *\n\t * // With brand\n\t * schema: { userId: t.string().brand<\"UserId\">() }\n\t * ```\n\t */\n\tstring<T extends string = string>() {\n\t\treturn createChainableType<T>([\n\t\t\t(v): v is T => typeof v === \"string\",\n\t\t], \"string\") as ChainableSchemaType<T>;\n\t},\n\n\t/**\n\t * Create a number schema type with optional min/max constraints.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Basic number\n\t * schema: { count: t.number() }\n\t *\n\t * // With range constraints\n\t * schema: { age: t.number().min(0).max(150) }\n\t *\n\t * // With custom validation\n\t * schema: { even: t.number().validate(n => n % 2 === 0) }\n\t *\n\t * // With default\n\t * schema: { count: t.number().default(0) }\n\t *\n\t * // With transform (from string)\n\t * schema: { age: t.number().transform(v => parseInt(String(v), 10)) }\n\t * ```\n\t */\n\tnumber() {\n\t\ttype ChainableNumber = ChainableSchemaType<number> & {\n\t\t\tmin(n: number): ChainableNumber;\n\t\t\tmax(n: number): ChainableNumber;\n\t\t};\n\n\t\tconst createChainableNumber = (\n\t\t\tvalidators: Array<(v: number) => boolean>,\n\t\t\tdefaultValue?: number | (() => number),\n\t\t\ttransform?: (value: unknown) => number,\n\t\t\tdescription?: string,\n\t\t\trefinements?: Array<{ predicate: (value: number) => boolean; message: string }>,\n\t\t): ChainableNumber => {\n\t\t\tconst chainable = createChainableType<number>(validators, \"number\", defaultValue, transform, description, refinements);\n\t\t\treturn {\n\t\t\t\t...chainable,\n\t\t\t\tmin(n: number) {\n\t\t\t\t\treturn createChainableNumber([...validators, (v) => v >= n], defaultValue, transform, description, refinements);\n\t\t\t\t},\n\t\t\t\tmax(n: number) {\n\t\t\t\t\treturn createChainableNumber([...validators, (v) => v <= n], defaultValue, transform, description, refinements);\n\t\t\t\t},\n\t\t\t\tdefault(value: number | (() => number)) {\n\t\t\t\t\treturn createChainableNumber(validators, value, transform, description, refinements);\n\t\t\t\t},\n\t\t\t\tdescribe(desc: string) {\n\t\t\t\t\treturn createChainableNumber(validators, defaultValue, transform, desc, refinements);\n\t\t\t\t},\n\t\t\t\trefine(predicate: (value: number) => boolean, message: string) {\n\t\t\t\t\tconst newRefinements = [...(refinements ?? []), { predicate, message }];\n\t\t\t\t\treturn createChainableNumber([...validators, predicate], defaultValue, transform, description, newRefinements);\n\t\t\t\t},\n\t\t\t};\n\t\t};\n\t\treturn createChainableNumber([(v) => typeof v === \"number\"]);\n\t},\n\n\t/**\n\t * Create a boolean schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * schema: {\n\t * active: t.boolean(),\n\t * verified: t.boolean().default(false),\n\t * }\n\t * ```\n\t */\n\tboolean() {\n\t\treturn createChainableType<boolean>([(v) => typeof v === \"boolean\"], \"boolean\");\n\t},\n\n\t/**\n\t * Create an array schema type.\n\t * Can be used with or without element validation:\n\t * - `t.array<string>()` - Type-only, no element validation\n\t * - `t.array<string>().of(t.string())` - With element validation\n\t */\n\tarray<T>() {\n\t\ttype ChainableArray = ChainableSchemaType<T[]> & {\n\t\t\tof(elementType: SchemaType<T>): ChainableArray;\n\t\t\tnonEmpty(): ChainableArray;\n\t\t\tmaxLength(n: number): ChainableArray;\n\t\t\tminLength(n: number): ChainableArray;\n\t\t\t_lastFailedIndex?: number;\n\t\t};\n\n\t\tconst createChainableArray = (\n\t\t\tvalidators: Array<(v: T[]) => boolean>,\n\t\t\telementType?: SchemaType<T>,\n\t\t\tdefaultValue?: T[] | (() => T[]),\n\t\t\tdescription?: string,\n\t\t\tindexRef?: { value: number },\n\t\t): ChainableArray => {\n\t\t\tconst chainable = createChainableType<T[]>(validators, \"array\", defaultValue, undefined, description);\n\t\t\t// Use ref for storing failed index (shared with validator closure)\n\t\t\tconst ref = indexRef ?? { value: -1 };\n\t\t\tconst result: ChainableArray = {\n\t\t\t\t...chainable,\n\t\t\t\tget _lastFailedIndex() { return ref.value; },\n\t\t\t\tset _lastFailedIndex(v: number) { ref.value = v; },\n\t\t\t\tof(et: SchemaType<T>) {\n\t\t\t\t\t// Create a new ref for this chain\n\t\t\t\t\tconst newRef = { value: -1 };\n\t\t\t\t\treturn createChainableArray([\n\t\t\t\t\t\t...validators,\n\t\t\t\t\t\t(v) => {\n\t\t\t\t\t\t\tfor (let i = 0; i < v.length; i++) {\n\t\t\t\t\t\t\t\tconst item = v[i];\n\t\t\t\t\t\t\t\tif (!et._validators.every((validator) => validator(item))) {\n\t\t\t\t\t\t\t\t\tnewRef.value = i;\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t},\n\t\t\t\t\t], et, defaultValue, description, newRef);\n\t\t\t\t},\n\t\t\t\tnonEmpty() {\n\t\t\t\t\treturn createChainableArray([...validators, (v) => v.length > 0], elementType, defaultValue, description, ref);\n\t\t\t\t},\n\t\t\t\tmaxLength(n: number) {\n\t\t\t\t\treturn createChainableArray([...validators, (v) => v.length <= n], elementType, defaultValue, description, ref);\n\t\t\t\t},\n\t\t\t\tminLength(n: number) {\n\t\t\t\t\treturn createChainableArray([...validators, (v) => v.length >= n], elementType, defaultValue, description, ref);\n\t\t\t\t},\n\t\t\t\tdefault(value: T[] | (() => T[])) {\n\t\t\t\t\treturn createChainableArray(validators, elementType, value, description, ref);\n\t\t\t\t},\n\t\t\t\tdescribe(desc: string) {\n\t\t\t\t\treturn createChainableArray(validators, elementType, defaultValue, desc, ref);\n\t\t\t\t},\n\t\t\t};\n\t\t\treturn result;\n\t\t};\n\t\treturn createChainableArray([(v) => Array.isArray(v)]);\n\t},\n\n\t/**\n\t * Create an object schema type.\n\t * Can be used with or without shape validation:\n\t * - `t.object<User>()` - Type-only, no property validation\n\t * - `t.object<User>().shape({ name: t.string(), age: t.number() })` - With property validation\n\t */\n\tobject<T extends Record<string, unknown>>() {\n\t\ttype ChainableObject = ChainableSchemaType<T> & {\n\t\t\tshape(schema: { [K in keyof T]?: SchemaType<T[K]> }): ChainableObject;\n\t\t\tnonNull(): ChainableObject;\n\t\t\thasKeys(...keys: string[]): ChainableObject;\n\t\t};\n\n\t\tconst createChainableObject = (\n\t\t\tvalidators: Array<(v: T) => boolean>,\n\t\t\tdefaultValue?: T | (() => T),\n\t\t\tdescription?: string,\n\t\t): ChainableObject => {\n\t\t\tconst chainable = createChainableType<T>(validators, \"object\", defaultValue, undefined, description);\n\t\t\treturn {\n\t\t\t\t...chainable,\n\t\t\t\tshape(shapeSchema: { [K in keyof T]?: SchemaType<T[K]> }) {\n\t\t\t\t\treturn createChainableObject([\n\t\t\t\t\t\t...validators,\n\t\t\t\t\t\t(v) => {\n\t\t\t\t\t\t\tfor (const [key, schemaType] of Object.entries(shapeSchema)) {\n\t\t\t\t\t\t\t\tconst value = (v as Record<string, unknown>)[key];\n\t\t\t\t\t\t\t\tconst schemaT = schemaType as SchemaType<unknown>;\n\t\t\t\t\t\t\t\tif (schemaT && !schemaT._validators.every((validator) => validator(value))) {\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t},\n\t\t\t\t\t], defaultValue, description);\n\t\t\t\t},\n\t\t\t\tnonNull() {\n\t\t\t\t\treturn createChainableObject([...validators, (v) => v !== null && v !== undefined], defaultValue, description);\n\t\t\t\t},\n\t\t\t\thasKeys(...keys: string[]) {\n\t\t\t\t\treturn createChainableObject([\n\t\t\t\t\t\t...validators,\n\t\t\t\t\t\t(v) => keys.every((k) => k in (v as Record<string, unknown>)),\n\t\t\t\t\t], defaultValue, description);\n\t\t\t\t},\n\t\t\t\tdefault(value: T | (() => T)) {\n\t\t\t\t\treturn createChainableObject(validators, value, description);\n\t\t\t\t},\n\t\t\t\tdescribe(desc: string) {\n\t\t\t\t\treturn createChainableObject(validators, defaultValue, desc);\n\t\t\t\t},\n\t\t\t};\n\t\t};\n\t\treturn createChainableObject([\n\t\t\t(v) => typeof v === \"object\" && v !== null && !Array.isArray(v),\n\t\t]);\n\t},\n\n\t/**\n\t * Create an any-typed schema (bypasses all validation).\n\t *\n\t * @deprecated Use specific types (`t.string()`, `t.object()`, `t.union()`) for type safety.\n\t * This bypasses all runtime validation.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Use when type is complex or external\n\t * schema: {\n\t * externalApiResponse: t.any<ExternalAPIResponse>(),\n\t * }\n\t * ```\n\t */\n\tany<T>() {\n\t\tif (process.env.NODE_ENV !== \"production\" && !warnedTypes.has(\"any\")) {\n\t\t\twarnedTypes.add(\"any\");\n\t\t\tconsole.warn(\n\t\t\t\t\"[Directive] t.any() bypasses runtime validation. \" +\n\t\t\t\t\"Consider using t.object<T>(), t.union(), or a Zod schema for type safety.\"\n\t\t\t);\n\t\t}\n\t\treturn createSchemaType<T>([], \"any\");\n\t},\n\n\t/**\n\t * Create an enum schema type for string literal unions.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Define allowed values\n\t * schema: { status: t.enum(\"idle\", \"loading\", \"success\", \"error\") }\n\t *\n\t * // Type is inferred as \"idle\" | \"loading\" | \"success\" | \"error\"\n\t * ```\n\t */\n\tenum<T extends string>(...values: T[]) {\n\t\tif (process.env.NODE_ENV !== \"production\" && values.length === 0) {\n\t\t\tconsole.warn(\"[Directive] t.enum() called with no values - this will reject all strings\");\n\t\t}\n\t\tconst valueSet = new Set(values);\n\t\treturn createChainableType<T>([\n\t\t\t(v): v is T => typeof v === \"string\" && valueSet.has(v as T),\n\t\t], `enum(${values.join(\"|\")})`);\n\t},\n\n\t/**\n\t * Create a literal schema type for exact value matching.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Exact string match\n\t * schema: { type: t.literal(\"user\") }\n\t *\n\t * // Exact number match\n\t * schema: { version: t.literal(1) }\n\t *\n\t * // Exact boolean\n\t * schema: { enabled: t.literal(true) }\n\t * ```\n\t */\n\tliteral<T extends string | number | boolean>(value: T) {\n\t\treturn createChainableType<T>([\n\t\t\t(v): v is T => v === value,\n\t\t], `literal(${String(value)})`);\n\t},\n\n\t/**\n\t * Create a nullable schema type (T | null).\n\t *\n\t * @example\n\t * ```typescript\n\t * // Nullable string\n\t * schema: { name: t.nullable(t.string()) }\n\t *\n\t * // Nullable object\n\t * schema: { user: t.nullable(t.object<User>()) }\n\t * ```\n\t */\n\tnullable<T>(innerType: SchemaType<T>) {\n\t\tconst innerTypeName = (innerType as ExtendedSchemaType<T>)._typeName ?? \"unknown\";\n\t\treturn createSchemaType<T | null>([\n\t\t\t(v): v is T | null => {\n\t\t\t\tif (v === null) return true;\n\t\t\t\treturn innerType._validators.every((validator) => validator(v as T));\n\t\t\t},\n\t\t], `${innerTypeName} | null`) as SchemaType<T | null>;\n\t},\n\n\t/**\n\t * Create an optional schema type (T | undefined).\n\t *\n\t * @example\n\t * ```typescript\n\t * // Optional string\n\t * schema: { nickname: t.optional(t.string()) }\n\t *\n\t * // Optional number\n\t * schema: { age: t.optional(t.number()) }\n\t * ```\n\t */\n\toptional<T>(innerType: SchemaType<T>) {\n\t\tconst innerTypeName = (innerType as ExtendedSchemaType<T>)._typeName ?? \"unknown\";\n\t\treturn createSchemaType<T | undefined>([\n\t\t\t(v): v is T | undefined => {\n\t\t\t\tif (v === undefined) return true;\n\t\t\t\treturn innerType._validators.every((validator) => validator(v as T));\n\t\t\t},\n\t\t], `${innerTypeName} | undefined`) as SchemaType<T | undefined>;\n\t},\n\n\t/**\n\t * Create a union schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * // String or number\n\t * schema: { value: t.union(t.string(), t.number()) }\n\t *\n\t * // Multiple types\n\t * schema: { data: t.union(t.string(), t.number(), t.boolean()) }\n\t * ```\n\t */\n\tunion<T extends SchemaType<unknown>[]>(...types: T) {\n\t\tif (process.env.NODE_ENV !== \"production\" && types.length === 0) {\n\t\t\tconsole.warn(\"[Directive] t.union() called with no types - this will reject all values\");\n\t\t}\n\t\ttype UnionType = T[number] extends SchemaType<infer U> ? U : never;\n\t\tconst typeNames = types.map(schemaType => (schemaType as ExtendedSchemaType<unknown>)._typeName ?? \"unknown\");\n\t\treturn createChainableType<UnionType>([\n\t\t\t(v): v is UnionType => types.some(schemaType => schemaType._validators.every(fn => fn(v))),\n\t\t], typeNames.join(\" | \"));\n\t},\n\n\t/**\n\t * Create a record schema type for dynamic key-value maps.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Record with string values\n\t * schema: { metadata: t.record(t.string()) }\n\t *\n\t * // Record with number values\n\t * schema: { scores: t.record(t.number()) }\n\t * ```\n\t */\n\trecord<V>(valueType: SchemaType<V>) {\n\t\tconst valueTypeName = (valueType as ExtendedSchemaType<V>)._typeName ?? \"unknown\";\n\t\treturn createChainableType<Record<string, V>>([\n\t\t\t(v): v is Record<string, V> => {\n\t\t\t\tif (typeof v !== \"object\" || v === null || Array.isArray(v)) return false;\n\t\t\t\treturn Object.values(v).every(val =>\n\t\t\t\t\tvalueType._validators.every(validator => validator(val))\n\t\t\t\t);\n\t\t\t},\n\t\t], `Record<string, ${valueTypeName}>`);\n\t},\n\n\t/**\n\t * Create a tuple schema type for fixed-length arrays with specific types.\n\t *\n\t * @example\n\t * ```typescript\n\t * // [string, number] tuple\n\t * schema: { coord: t.tuple(t.string(), t.number()) }\n\t *\n\t * // [x, y, z] coordinates\n\t * schema: { position: t.tuple(t.number(), t.number(), t.number()) }\n\t * ```\n\t */\n\ttuple<T extends SchemaType<unknown>[]>(...types: T) {\n\t\tif (process.env.NODE_ENV !== \"production\" && types.length === 0) {\n\t\t\tconsole.warn(\"[Directive] t.tuple() called with no types - this will only accept empty arrays\");\n\t\t}\n\t\ttype TupleType = { [K in keyof T]: T[K] extends SchemaType<infer U> ? U : never };\n\t\tconst typeNames = types.map(schemaType => (schemaType as ExtendedSchemaType<unknown>)._typeName ?? \"unknown\");\n\t\treturn createChainableType<TupleType>([\n\t\t\t(v): v is TupleType => {\n\t\t\t\tif (!Array.isArray(v) || v.length !== types.length) return false;\n\t\t\t\treturn types.every((schemaType, i) =>\n\t\t\t\t\tschemaType._validators.every(validator => validator(v[i]))\n\t\t\t\t);\n\t\t\t},\n\t\t], `[${typeNames.join(\", \")}]`);\n\t},\n\n\t/**\n\t * Create a date schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * schema: { createdAt: t.date() }\n\t * ```\n\t */\n\tdate() {\n\t\treturn createChainableType<Date>([\n\t\t\t(v): v is Date => v instanceof Date && !isNaN(v.getTime()),\n\t\t], \"Date\");\n\t},\n\n\t/**\n\t * Create a UUID schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * schema: { id: t.uuid() }\n\t * ```\n\t */\n\tuuid() {\n\t\tconst uuidRegex = /^[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\t\treturn createChainableType<string>([\n\t\t\t(v): v is string => typeof v === \"string\" && uuidRegex.test(v),\n\t\t], \"uuid\");\n\t},\n\n\t/**\n\t * Create an email schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * schema: { email: t.email() }\n\t * ```\n\t */\n\temail() {\n\t\t// Simple email regex - for comprehensive validation use Zod\n\t\tconst emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\t\treturn createChainableType<string>([\n\t\t\t(v): v is string => typeof v === \"string\" && emailRegex.test(v),\n\t\t], \"email\");\n\t},\n\n\t/**\n\t * Create a URL schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * schema: { website: t.url() }\n\t * ```\n\t */\n\turl() {\n\t\treturn createChainableType<string>([\n\t\t\t(v): v is string => {\n\t\t\t\tif (typeof v !== \"string\") return false;\n\t\t\t\ttry {\n\t\t\t\t\tnew URL(v);\n\t\t\t\t\treturn true;\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t], \"url\");\n\t},\n\n\t/**\n\t * Create a bigint schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * schema: { largeNumber: t.bigint() }\n\t * ```\n\t */\n\tbigint() {\n\t\treturn createChainableType<bigint>([\n\t\t\t(v): v is bigint => typeof v === \"bigint\",\n\t\t], \"bigint\");\n\t},\n};\n\n// ============================================================================\n// Facts Store Implementation\n// ============================================================================\n\n/** Options for creating a facts store */\nexport interface CreateFactsStoreOptions<S extends Schema> {\n\tschema: S;\n\t/** Validate values against schema (default: process.env.NODE_ENV !== 'production') */\n\tvalidate?: boolean;\n\t/** Throw on unknown schema keys (default: true in dev mode) */\n\tstrictKeys?: boolean;\n\t/** Redact sensitive values in error messages */\n\tredactErrors?: boolean;\n\t/** Callback when facts change (for plugin hooks) */\n\tonChange?: (key: string, value: unknown, prev: unknown) => void;\n\t/** Callback for batch changes */\n\tonBatch?: (changes: Array<{ key: string; value: unknown; prev: unknown; type: \"set\" | \"delete\" }>) => void;\n}\n\n/**\n * Create a reactive facts store backed by a Map with schema validation,\n * batched mutations, and granular key-level subscriptions.\n *\n * The store is the low-level primitive that powers the `facts` proxy.\n * Most users should use {@link createFacts} or `createModule` instead.\n *\n * @param options - Store configuration including schema, validation settings, and change callbacks\n * @returns A `FactsStore<S>` with get/set/batch/subscribe methods and automatic schema validation\n *\n * @example\n * ```ts\n * const store = createFactsStore({\n * schema: { count: t.number(), name: t.string() },\n * });\n *\n * store.set(\"count\", 1);\n * store.get(\"count\"); // 1\n *\n * store.batch(() => {\n * store.set(\"count\", 2);\n * store.set(\"name\", \"hello\");\n * }); // listeners fire once after batch completes\n * ```\n */\nexport function createFactsStore<S extends Schema>(\n\toptions: CreateFactsStoreOptions<S>,\n): FactsStore<S> {\n\tconst { schema, onChange, onBatch } = options;\n\n\t// Detect if this is a type assertion schema (empty object with no keys)\n\tconst schemaKeys = Object.keys(schema);\n\tconst isTypeAssertionSchema = schemaKeys.length === 0;\n\n\t// Default strictKeys to false for type assertion schemas (they have no runtime keys)\n\tconst validate = options.validate ?? process.env.NODE_ENV !== \"production\";\n\tconst strictKeys = options.strictKeys ?? (process.env.NODE_ENV !== \"production\" && !isTypeAssertionSchema);\n\tconst redactErrors = options.redactErrors ?? false;\n\n\tconst map = new Map<string, unknown>();\n\tconst knownKeys = new Set<string>(); // Track all keys that have been set\n\tconst keyListeners = new Map<string, Set<() => void>>();\n\tconst allListeners = new Set<() => void>();\n\n\tlet batching = 0;\n\tconst batchChanges: Array<{ key: string; value: unknown; prev: unknown; type: \"set\" | \"delete\" }> = [];\n\tconst dirtyKeys = new Set<string>();\n\n\t// Notification coalescing: when notifyKey/notifyAll fires a listener that\n\t// calls store.set(), defer the new notification until the current cycle completes.\n\tlet isNotifying = false;\n\tconst pendingNonBatchedChanges: Array<{ key: string; value: unknown; prev: unknown }> = [];\n\tconst MAX_NOTIFY_ITERATIONS = 100;\n\n\t/** Check if a value is a Zod schema (robust detection) */\n\tfunction isZodSchema(v: unknown): v is { safeParse: (v: unknown) => { success: boolean; error?: { message?: string; issues?: Array<{ message: string }> } }; _def: unknown; parse: unknown } {\n\t\treturn (\n\t\t\tv !== null &&\n\t\t\ttypeof v === \"object\" &&\n\t\t\t\"safeParse\" in v && typeof (v as Record<string, unknown>).safeParse === \"function\" &&\n\t\t\t\"_def\" in v &&\n\t\t\t\"parse\" in v && typeof (v as Record<string, unknown>).parse === \"function\"\n\t\t);\n\t}\n\n\t/** Get expected type name from schema */\n\tfunction getExpectedType(schemaType: unknown): string {\n\t\t// Check for our SchemaType with _typeName\n\t\tconst st = schemaType as { _typeName?: string };\n\t\tif (st._typeName) return st._typeName;\n\n\t\t// Check for Zod schema\n\t\tif (isZodSchema(schemaType)) {\n\t\t\tconst def = (schemaType as { _def?: { typeName?: string } })._def;\n\t\t\tif (def?.typeName) {\n\t\t\t\t// Convert ZodString -> string, ZodNumber -> number, etc.\n\t\t\t\treturn def.typeName.replace(/^Zod/, \"\").toLowerCase();\n\t\t\t}\n\t\t}\n\n\t\treturn \"unknown\";\n\t}\n\n\t/** Format value for error message, respecting redactErrors option */\n\tfunction formatValueForError(value: unknown): string {\n\t\tif (redactErrors) return \"[redacted]\";\n\t\treturn safeStringify(value);\n\t}\n\n\t/** Validate a value against the schema */\n\tfunction validateValue(key: string, value: unknown): void {\n\t\tif (!validate) return;\n\n\t\tconst schemaType = schema[key];\n\t\tif (!schemaType) {\n\t\t\tif (strictKeys) {\n\t\t\t\tthrow new Error(`[Directive] Unknown fact key: \"${key}\". Key not defined in schema.`);\n\t\t\t}\n\t\t\tconsole.warn(`[Directive] Unknown fact key: \"${key}\"`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Check for Zod schema (robust detection: safeParse + _def + parse)\n\t\tif (isZodSchema(schemaType)) {\n\t\t\tconst result = schemaType.safeParse(value);\n\t\t\tif (!result.success) {\n\t\t\t\tconst valueType = value === null ? \"null\" : Array.isArray(value) ? \"array\" : typeof value;\n\t\t\t\tconst valuePreview = formatValueForError(value);\n\t\t\t\t// Extract error message safely from Zod error structure\n\t\t\t\tconst errorMessage = result.error?.message\n\t\t\t\t\t?? result.error?.issues?.[0]?.message\n\t\t\t\t\t?? \"Validation failed\";\n\t\t\t\tconst expectedType = getExpectedType(schemaType);\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Validation failed for \"${key}\": expected ${expectedType}, got ${valueType} ${valuePreview}. ${errorMessage}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Check for our SchemaType (has _validators array)\n\t\tconst st = schemaType as { _validators?: unknown; _typeName?: string; _lastFailedIndex?: number };\n\t\tconst validators = st._validators;\n\n\t\t// Ensure validators is an array before iterating\n\t\tif (!validators || !Array.isArray(validators) || validators.length === 0) {\n\t\t\treturn; // type assertion or empty validators - no validation\n\t\t}\n\n\t\tconst expectedType = st._typeName ?? \"unknown\";\n\n\t\tfor (let i = 0; i < validators.length; i++) {\n\t\t\tconst validator = validators[i];\n\t\t\tif (typeof validator !== \"function\") continue;\n\n\t\t\tif (!validator(value as never)) {\n\t\t\t\tconst valueType = value === null ? \"null\" : Array.isArray(value) ? \"array\" : typeof value;\n\t\t\t\tconst valuePreview = formatValueForError(value);\n\n\t\t\t\t// Check for array index failure from schema type\n\t\t\t\tlet indexHint = \"\";\n\t\t\t\tif (typeof st._lastFailedIndex === \"number\" && st._lastFailedIndex >= 0) {\n\t\t\t\t\tindexHint = ` (element at index ${st._lastFailedIndex} failed)`;\n\t\t\t\t\tst._lastFailedIndex = -1; // Reset for next validation\n\t\t\t\t}\n\n\t\t\t\t// Include expected type in error message\n\t\t\t\tconst validatorHint = i === 0 ? \"\" : ` (validator ${i + 1} failed)`;\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Validation failed for \"${key}\": expected ${expectedType}, got ${valueType} ${valuePreview}${validatorHint}${indexHint}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Notify listeners for a specific key */\n\tfunction notifyKey(key: string): void {\n\t\tkeyListeners.get(key)?.forEach((listener) => listener());\n\t}\n\n\t/** Notify all listeners */\n\tfunction notifyAll(): void {\n\t\tallListeners.forEach((listener) => listener());\n\t}\n\n\t/**\n\t * Run non-batched notifications with coalescing.\n\t * If a listener calls store.set(), the change is deferred and processed\n\t * after the current notification cycle completes.\n\t */\n\tfunction notifyNonBatched(key: string, value: unknown, prev: unknown): void {\n\t\tif (isNotifying) {\n\t\t\t// Re-entrant: defer to after current notification cycle\n\t\t\tpendingNonBatchedChanges.push({ key, value, prev });\n\t\t\treturn;\n\t\t}\n\n\t\tisNotifying = true;\n\t\ttry {\n\t\t\t// Fire onChange, notifyKey, notifyAll for the initial change\n\t\t\tonChange?.(key, value, prev);\n\t\t\tnotifyKey(key);\n\t\t\tnotifyAll();\n\n\t\t\t// Process any changes that were deferred during notification\n\t\t\tlet iterations = 0;\n\t\t\twhile (pendingNonBatchedChanges.length > 0) {\n\t\t\t\tif (++iterations > MAX_NOTIFY_ITERATIONS) {\n\t\t\t\t\tpendingNonBatchedChanges.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Infinite notification loop detected after ${MAX_NOTIFY_ITERATIONS} iterations. ` +\n\t\t\t\t\t\t\t`A listener is repeatedly mutating facts that re-trigger notifications.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst deferred = [...pendingNonBatchedChanges];\n\t\t\t\tpendingNonBatchedChanges.length = 0;\n\n\t\t\t\tfor (const change of deferred) {\n\t\t\t\t\tonChange?.(change.key, change.value, change.prev);\n\t\t\t\t\tnotifyKey(change.key);\n\t\t\t\t}\n\t\t\t\t// Single notifyAll for all deferred changes in this iteration\n\t\t\t\tnotifyAll();\n\t\t\t}\n\t\t} finally {\n\t\t\tisNotifying = false;\n\t\t}\n\t}\n\n\t/** Flush batched changes and notify */\n\tfunction flush(): void {\n\t\tif (batching > 0) return;\n\n\t\t// Notify batch callback\n\t\tif (onBatch && batchChanges.length > 0) {\n\t\t\tonBatch([...batchChanges]);\n\t\t}\n\n\t\t// Notify key-specific listeners (within coalescing guard)\n\t\tif (dirtyKeys.size > 0) {\n\t\t\tisNotifying = true;\n\t\t\ttry {\n\t\t\t\tfor (const key of dirtyKeys) {\n\t\t\t\t\tnotifyKey(key);\n\t\t\t\t}\n\t\t\t\tnotifyAll();\n\n\t\t\t\t// Process any changes deferred during flush notification\n\t\t\t\tlet iterations = 0;\n\t\t\t\twhile (pendingNonBatchedChanges.length > 0) {\n\t\t\t\t\tif (++iterations > MAX_NOTIFY_ITERATIONS) {\n\t\t\t\t\t\tpendingNonBatchedChanges.length = 0;\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`[Directive] Infinite notification loop detected during flush after ${MAX_NOTIFY_ITERATIONS} iterations.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst deferred = [...pendingNonBatchedChanges];\n\t\t\t\t\tpendingNonBatchedChanges.length = 0;\n\n\t\t\t\t\tfor (const change of deferred) {\n\t\t\t\t\t\tonChange?.(change.key, change.value, change.prev);\n\t\t\t\t\t\tnotifyKey(change.key);\n\t\t\t\t\t}\n\t\t\t\t\tnotifyAll();\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tisNotifying = false;\n\t\t\t}\n\t\t}\n\n\t\t// Clear batch state\n\t\tbatchChanges.length = 0;\n\t\tdirtyKeys.clear();\n\t}\n\n\tconst store: FactsStore<S> = {\n\t\tget<K extends keyof InferSchema<S>>(key: K): InferSchema<S>[K] | undefined {\n\t\t\t// Track access for auto-tracking\n\t\t\ttrackAccess(key as string);\n\t\t\treturn map.get(key as string) as InferSchema<S>[K] | undefined;\n\t\t},\n\n\t\thas(key: keyof InferSchema<S>): boolean {\n\t\t\t// Track access for auto-tracking\n\t\t\ttrackAccess(key as string);\n\t\t\treturn map.has(key as string);\n\t\t},\n\n\t\tset<K extends keyof InferSchema<S>>(key: K, value: InferSchema<S>[K]): void {\n\t\t\tvalidateValue(key as string, value);\n\n\t\t\tconst prev = map.get(key as string);\n\n\t\t\t// Skip if value hasn't changed (prevents unnecessary cascade)\n\t\t\tif (Object.is(prev, value)) return;\n\n\t\t\tmap.set(key as string, value);\n\t\t\tknownKeys.add(key as string); // Track known keys for serialization\n\n\t\t\t// Record change\n\t\t\tif (batching > 0) {\n\t\t\t\tbatchChanges.push({ key: key as string, value, prev, type: \"set\" });\n\t\t\t\tdirtyKeys.add(key as string);\n\t\t\t} else {\n\t\t\t\tnotifyNonBatched(key as string, value, prev);\n\t\t\t}\n\t\t},\n\n\t\tdelete(key: keyof InferSchema<S>): void {\n\t\t\tconst prev = map.get(key as string);\n\t\t\tmap.delete(key as string);\n\t\t\tknownKeys.delete(key as string); // Remove from known keys\n\n\t\t\t// Record change\n\t\t\tif (batching > 0) {\n\t\t\t\tbatchChanges.push({ key: key as string, value: undefined, prev, type: \"delete\" });\n\t\t\t\tdirtyKeys.add(key as string);\n\t\t\t} else {\n\t\t\t\tnotifyNonBatched(key as string, undefined, prev);\n\t\t\t}\n\t\t},\n\n\t\tbatch(fn: () => void): void {\n\t\t\tbatching++;\n\t\t\ttry {\n\t\t\t\tfn();\n\t\t\t} finally {\n\t\t\t\tbatching--;\n\t\t\t\tflush();\n\t\t\t}\n\t\t},\n\n\t\tsubscribe(\n\t\t\tkeys: Array<keyof InferSchema<S>>,\n\t\t\tlistener: () => void,\n\t\t): () => void {\n\t\t\tfor (const key of keys) {\n\t\t\t\tconst keyStr = key as string;\n\t\t\t\tif (!keyListeners.has(keyStr)) {\n\t\t\t\t\tkeyListeners.set(keyStr, new Set());\n\t\t\t\t}\n\t\t\t\tkeyListeners.get(keyStr)!.add(listener);\n\t\t\t}\n\n\t\t\treturn () => {\n\t\t\t\tfor (const key of keys) {\n\t\t\t\t\tconst set = keyListeners.get(key as string);\n\t\t\t\t\tif (set) {\n\t\t\t\t\t\tset.delete(listener);\n\t\t\t\t\t\tif (set.size === 0) {\n\t\t\t\t\t\t\tkeyListeners.delete(key as string);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\n\t\tsubscribeAll(listener: () => void): () => void {\n\t\t\tallListeners.add(listener);\n\t\t\treturn () => allListeners.delete(listener);\n\t\t},\n\n\t\ttoObject(): Record<string, unknown> {\n\t\t\tconst result: Record<string, unknown> = {};\n\t\t\tfor (const key of knownKeys) {\n\t\t\t\tif (map.has(key)) {\n\t\t\t\t\tresult[key] = map.get(key);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t};\n\n\t// Internal: register new schema keys for dynamic module registration.\n\t// Not part of the public FactsStore interface — used by engine.registerModule().\n\t(store as unknown as Record<string, unknown>).registerKeys = (newSchema: Record<string, unknown>) => {\n\t\tfor (const key of Object.keys(newSchema)) {\n\t\t\t// Defense-in-depth: skip prototype pollution keys\n\t\t\tif (BLOCKED_PROPS.has(key)) continue;\n\t\t\t// Add to schema for validation\n\t\t\t(schema as Record<string, unknown>)[key] = newSchema[key];\n\t\t\tknownKeys.add(key);\n\t\t}\n\t};\n\n\treturn store;\n}\n\n// ============================================================================\n// Proxy-based Facts Accessor\n// ============================================================================\n\n/** Prototype pollution guard - prevent access to dangerous properties */\nconst BLOCKED_PROPS = Object.freeze(new Set([\"__proto__\", \"constructor\", \"prototype\"]));\n\n/**\n * Create a Proxy wrapper around a {@link FactsStore} for clean property-style\n * access (`facts.phase`) with automatic dependency tracking.\n *\n * Reading a property calls `store.get()` (which tracks the access for\n * auto-tracked derivations). Writing a property calls `store.set()` (which\n * validates against the schema). The proxy also exposes `$store` for direct\n * store access and `$snapshot()` for untracked reads.\n *\n * @param store - The underlying facts store to wrap\n * @param schema - The schema definition (used for `ownKeys` enumeration)\n * @returns A `Facts<S>` proxy with property-style get/set and prototype pollution guards\n */\nexport function createFactsProxy<S extends Schema>(\n\tstore: FactsStore<S>,\n\tschema: S,\n): Facts<S> {\n\tconst snapshot = (): FactsSnapshot<S> => ({\n\t\tget: <K extends keyof InferSchema<S>>(key: K) =>\n\t\t\twithoutTracking(() => store.get(key)),\n\t\thas: (key: keyof InferSchema<S>) =>\n\t\t\twithoutTracking(() => store.has(key)),\n\t});\n\n\tconst proxy = new Proxy({} as Facts<S>, {\n\t\tget(_, prop: string | symbol) {\n\t\t\tif (prop === \"$store\") return store;\n\t\t\tif (prop === \"$snapshot\") return snapshot;\n\n\t\t\t// Special properties\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\n\t\t\t// Track and return the value\n\t\t\treturn store.get(prop as keyof InferSchema<S>);\n\t\t},\n\n\t\tset(_, prop: string | symbol, value: unknown) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\tif (prop === \"$store\" || prop === \"$snapshot\") return false;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\n\t\t\t// Validation is handled by store.set() when validate option is enabled\n\t\t\tstore.set(prop as keyof InferSchema<S>, value as InferSchema<S>[keyof InferSchema<S>]);\n\t\t\treturn true;\n\t\t},\n\n\t\tdeleteProperty(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\tif (prop === \"$store\" || prop === \"$snapshot\") return false;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\n\t\t\tstore.delete(prop as keyof InferSchema<S>);\n\t\t\treturn true;\n\t\t},\n\n\t\thas(_, prop: string | symbol) {\n\t\t\tif (prop === \"$store\" || prop === \"$snapshot\") return true;\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\n\t\t\treturn store.has(prop as keyof InferSchema<S>);\n\t\t},\n\n\t\townKeys() {\n\t\t\t// Return schema keys dynamically so Object.keys(facts) reflects\n\t\t\t// keys added via registerKeys (dynamic module registration)\n\t\t\treturn Object.keys(schema);\n\t\t},\n\n\t\tgetOwnPropertyDescriptor(_, prop: string | symbol) {\n\t\t\tif (prop === \"$store\" || prop === \"$snapshot\") {\n\t\t\t\treturn { configurable: true, enumerable: false, writable: false };\n\t\t\t}\n\t\t\treturn { configurable: true, enumerable: true, writable: true };\n\t\t},\n\t});\n\n\treturn proxy;\n}\n\n// ============================================================================\n// Combined Factory\n// ============================================================================\n\n/**\n * Convenience factory that creates both a {@link FactsStore} and its\n * {@link createFactsProxy | proxy wrapper} in a single call.\n *\n * This is the recommended entry point when you need low-level store access\n * outside of `createModule` / `createSystem`.\n *\n * @param options - Same options as {@link createFactsStore}\n * @returns An object with `store` (the reactive Map-backed store) and `facts` (the Proxy accessor)\n *\n * @example\n * ```ts\n * const { store, facts } = createFacts({\n * schema: { phase: t.string<\"red\" | \"green\">() },\n * });\n *\n * facts.phase = \"red\";\n * console.log(facts.phase); // \"red\"\n * store.subscribe([\"phase\"], () => console.log(\"phase changed\"));\n * ```\n */\nexport function createFacts<S extends Schema>(\n\toptions: CreateFactsStoreOptions<S>,\n): { store: FactsStore<S>; facts: Facts<S> } {\n\tconst store = createFactsStore(options);\n\tconst facts = createFactsProxy(store, options.schema);\n\treturn { store, facts };\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 type {\n\tModuleSchema,\n\tFacts,\n\tModuleDef,\n\tModuleHooks,\n\tEffectsDef,\n\tTypedDerivationsDef,\n\tTypedEventsDef,\n\tTypedConstraintsDef,\n\tTypedResolversDef,\n\tCrossModuleDeps,\n\tCrossModuleConstraintsDef,\n\tCrossModuleEffectsDef,\n\tCrossModuleDerivationsDef,\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\tschema: M;\n\tinit?: (facts: Facts<M[\"facts\"]>) => void;\n\tderive?: TypedDerivationsDef<M>;\n\tevents?: TypedEventsDef<M>;\n\teffects?: EffectsDef<M[\"facts\"]>;\n\tconstraints?: TypedConstraintsDef<M>;\n\tresolvers?: TypedResolversDef<M>;\n\thooks?: ModuleHooks<M>;\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\tM extends ModuleSchema,\n\tDeps extends CrossModuleDeps,\n> {\n\tschema: M;\n\t/**\n\t * Cross-module dependencies for type-safe access in derive/effects/constraints.\n\t *\n\t * **Access patterns by context:**\n\t * - `derive`, `effects`, `constraints`: Use `facts.self.*` for own module, `facts.{dep}.*` for cross-module\n\t * - `init`, `events`, `resolvers`: Use flat access (`facts.myFact`) - no cross-module access\n\t *\n\t * This separation ensures initialization and event handling stay scoped to own module,\n\t * while observers (derive/effects/constraints) can see across modules.\n\t *\n\t * @example\n\t * ```typescript\n\t * crossModuleDeps: { auth: authSchema },\n\t * init: (facts) => { facts.users = []; }, // flat access\n\t * derive: { count: (facts) => facts.self.users.length }, // facts.self.*\n\t * effects: { log: { run: (facts) => console.log(facts.auth.token) } }, // facts.{dep}.*\n\t * ```\n\t */\n\tcrossModuleDeps: Deps;\n\t/** Initialize module facts. Uses flat access (`facts.myFact`) to ensure modules initialize independently. */\n\tinit?: (facts: Facts<M[\"facts\"]>) => void;\n\t/** Derivations with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n\tderive?: CrossModuleDerivationsDef<M, Deps>;\n\t/** Event handlers. Uses flat access (`facts.myFact`) to keep mutations scoped to own module. */\n\tevents?: TypedEventsDef<M>;\n\t/** Effects with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n\teffects?: CrossModuleEffectsDef<M, Deps>;\n\t/** Constraints with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n\tconstraints?: CrossModuleConstraintsDef<M, Deps>;\n\t/** Resolvers. Uses flat access (`ctx.facts.myFact`) to keep async mutations scoped to own module. */\n\tresolvers?: TypedResolversDef<M>;\n\thooks?: ModuleHooks<M>;\n}\n\n/**\n * Create a module definition with full type inference.\n *\n * The consolidated schema provides:\n * - Derivation composition (`derive.otherDerivation` is typed)\n * - Event dispatch (`system.dispatch({ type: \"...\" })` has autocomplete)\n * - Resolver requirements (`req.payload` is typed based on requirement type)\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, derive) => {\n * // derive.isRed is typed as boolean!\n * return derive.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 * });\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// Overload 1: With crossModuleDeps\nexport function createModule<\n\tconst M extends ModuleSchema,\n\tconst Deps extends CrossModuleDeps,\n>(\n\tid: string,\n\tconfig: ModuleConfigWithDeps<M, Deps>,\n): ModuleDef<M>;\n\n// Overload 2: Without crossModuleDeps (original signature)\nexport function createModule<const M extends ModuleSchema>(\n\tid: string,\n\tconfig: ModuleConfig<M>,\n): ModuleDef<M>;\n\n// Overload 3: Union (used by createModuleFactory)\nexport function createModule<const M extends ModuleSchema>(\n\tid: string,\n\tconfig: ModuleConfigWithDeps<M, CrossModuleDeps> | ModuleConfig<M>,\n): ModuleDef<M>;\n\n// Implementation (must immediately follow overload declarations)\nexport function createModule<const M extends ModuleSchema>(\n\tid: string,\n\tconfig: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): ModuleDef<M> {\n\t// Dev-mode validations\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tif (!id || typeof id !== \"string\") {\n\t\t\tconsole.warn(\"[Directive] Module ID must be a non-empty string\");\n\t\t} else if (!/^[a-z][a-z0-9-]*$/i.test(id)) {\n\t\t\tconsole.warn(\n\t\t\t\t`[Directive] Module ID \"${id}\" should follow kebab-case convention (e.g., \"my-module\")`,\n\t\t\t);\n\t\t}\n\n\t\tif (!config.schema) {\n\t\t\tconsole.warn(\"[Directive] Module schema is required\");\n\t\t} else {\n\t\t\tif (!config.schema.facts) {\n\t\t\t\tconsole.warn(\"[Directive] Module schema.facts is required\");\n\t\t\t}\n\t\t\t// derivations, events, and requirements default to {} if not provided\n\t\t}\n\n\t\t// Validate derive keys match schema.derivations (if either is provided)\n\t\tconst schemaDerivations = config.schema?.derivations ?? {};\n\t\tconst deriveImpl = config.derive ?? {};\n\t\tconst schemaDerivationKeys = new Set(Object.keys(schemaDerivations));\n\t\tconst deriveKeys = new Set(Object.keys(deriveImpl));\n\n\t\tfor (const key of deriveKeys) {\n\t\t\tif (!schemaDerivationKeys.has(key)) {\n\t\t\t\tconsole.warn(`[Directive] Derivation \"${key}\" not declared in schema.derivations`);\n\t\t\t}\n\t\t}\n\t\tfor (const key of schemaDerivationKeys) {\n\t\t\tif (!deriveKeys.has(key)) {\n\t\t\t\tconsole.warn(`[Directive] schema.derivations[\"${key}\"] has no matching implementation in derive`);\n\t\t\t}\n\t\t}\n\n\t\t// Validate events keys match schema.events (if either is provided)\n\t\tconst schemaEvents = config.schema?.events ?? {};\n\t\tconst eventImpl = config.events ?? {};\n\t\tconst schemaEventKeys = new Set(Object.keys(schemaEvents));\n\t\tconst eventKeys = new Set(Object.keys(eventImpl));\n\n\t\tfor (const key of eventKeys) {\n\t\t\tif (!schemaEventKeys.has(key)) {\n\t\t\t\tconsole.warn(`[Directive] Event \"${key}\" not declared in schema.events`);\n\t\t\t}\n\t\t}\n\t\tfor (const key of schemaEventKeys) {\n\t\t\tif (!eventKeys.has(key)) {\n\t\t\t\tconsole.warn(`[Directive] schema.events[\"${key}\"] has no matching handler in events`);\n\t\t\t}\n\t\t}\n\n\t\t// Validate resolvers reference valid requirement types\n\t\tif (config.resolvers && config.schema?.requirements) {\n\t\t\tconst requirementTypes = new Set(Object.keys(config.schema.requirements));\n\t\t\tfor (const [resolverName, resolver] of Object.entries(config.resolvers)) {\n\t\t\t\tconst resolverDef = resolver as { requirement?: string };\n\t\t\t\tif (\n\t\t\t\t\ttypeof resolverDef.requirement === \"string\" &&\n\t\t\t\t\t!requirementTypes.has(resolverDef.requirement)\n\t\t\t\t) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] Resolver \"${resolverName}\" references unknown requirement type \"${resolverDef.requirement}\". ` +\n\t\t\t\t\t\t\t`Available types: ${[...requirementTypes].join(\", \") || \"(none)\"}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Extract crossModuleDeps if present (for runtime proxy creation)\n\tconst crossModuleDeps = \"crossModuleDeps\" in config ? config.crossModuleDeps : undefined;\n\n\treturn {\n\t\tid,\n\t\tschema: config.schema,\n\t\tinit: config.init,\n\t\t// Cast to TypedDerivationsDef for ModuleDef compatibility (runtime handles both types)\n\t\tderive: (config.derive ?? {}) as TypedDerivationsDef<M>,\n\t\tevents: config.events ?? ({} as TypedEventsDef<M>),\n\t\teffects: config.effects as EffectsDef<M[\"facts\"]> | undefined,\n\t\tconstraints: config.constraints as TypedConstraintsDef<M> | undefined,\n\t\tresolvers: config.resolvers,\n\t\thooks: config.hooks,\n\t\t// Store crossModuleDeps for runtime proxy creation\n\t\tcrossModuleDeps: crossModuleDeps as CrossModuleDeps | undefined,\n\t};\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 * @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 */\nexport function createModuleFactory<const M extends ModuleSchema>(\n\tconfig: ModuleConfig<M>,\n): (name: string) => ModuleDef<M>;\nexport function createModuleFactory<\n\tconst M extends ModuleSchema,\n\tconst Deps extends CrossModuleDeps,\n>(\n\tconfig: ModuleConfigWithDeps<M, Deps>,\n): (name: string) => ModuleDef<M>;\nexport function createModuleFactory<const M extends ModuleSchema>(\n\tconfig: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): (name: string) => ModuleDef<M> {\n\t// Pass config directly — createModule's implementation overload handles both types.\n\t// Do NOT cast to ModuleConfig<M> which would strip crossModuleDeps.\n\treturn (name: string) => createModule(name, config);\n}\n","/**\n * Shared utilities for Directive\n */\n\n/**\n * Execute a promise with a timeout, properly cleaning up the timer.\n * Used by both constraints and resolvers for timeout handling.\n *\n * @param promise - The promise to wrap with a timeout\n * @param ms - Timeout duration in milliseconds\n * @param errorMessage - Error message if timeout occurs\n * @returns The promise result\n * @throws Error if timeout is exceeded\n */\nexport async function withTimeout<T>(\n\tpromise: Promise<T>,\n\tms: number,\n\terrorMessage: string,\n): Promise<T> {\n\tlet timeoutId: ReturnType<typeof setTimeout>;\n\n\tconst timeoutPromise = new Promise<never>((_, reject) => {\n\t\ttimeoutId = setTimeout(() => reject(new Error(errorMessage)), ms);\n\t});\n\n\ttry {\n\t\treturn await Promise.race([promise, timeoutPromise]);\n\t} finally {\n\t\tclearTimeout(timeoutId!);\n\t}\n}\n\n/**\n * Normalize an error to an Error instance.\n * Ensures consistent error handling throughout the library.\n *\n * @param error - The error to normalize (can be anything)\n * @returns An Error instance\n */\nexport function normalizeError(error: unknown): Error {\n\tif (error instanceof Error) {\n\t\treturn error;\n\t}\n\treturn new Error(String(error));\n}\n\n/**\n * Create a stable JSON string with sorted keys.\n * Handles circular references and deeply nested objects safely.\n *\n * @param value - The value to stringify\n * @param maxDepth - Maximum nesting depth (default: 50)\n * @returns A stable JSON string\n */\nexport function stableStringify(value: unknown, maxDepth = 50): string {\n\tconst seen = new WeakSet();\n\n\tfunction stringify(val: unknown, depth: number): string {\n\t\tif (depth > maxDepth) {\n\t\t\treturn '\"[max depth exceeded]\"';\n\t\t}\n\n\t\tif (val === null) return \"null\";\n\t\tif (val === undefined) return \"undefined\";\n\n\t\tconst type = typeof val;\n\n\t\tif (type === \"string\") return JSON.stringify(val);\n\t\tif (type === \"number\" || type === \"boolean\") return String(val);\n\t\tif (type === \"function\") return '\"[function]\"';\n\t\tif (type === \"symbol\") return '\"[symbol]\"';\n\n\t\tif (Array.isArray(val)) {\n\t\t\t// Check for circular reference\n\t\t\tif (seen.has(val)) {\n\t\t\t\treturn '\"[circular]\"';\n\t\t\t}\n\t\t\tseen.add(val);\n\t\t\tconst result = `[${val.map((v) => stringify(v, depth + 1)).join(\",\")}]`;\n\t\t\tseen.delete(val);\n\t\t\treturn result;\n\t\t}\n\n\t\tif (type === \"object\") {\n\t\t\tconst obj = val as Record<string, unknown>;\n\t\t\t// Check for circular reference\n\t\t\tif (seen.has(obj)) {\n\t\t\t\treturn '\"[circular]\"';\n\t\t\t}\n\t\t\tseen.add(obj);\n\t\t\tconst keys = Object.keys(obj).sort();\n\t\t\tconst pairs = keys.map((k) => `${JSON.stringify(k)}:${stringify(obj[k], depth + 1)}`);\n\t\t\tconst result = `{${pairs.join(\",\")}}`;\n\t\t\tseen.delete(obj);\n\t\t\treturn result;\n\t\t}\n\n\t\treturn '\"[unknown]\"';\n\t}\n\n\treturn stringify(value, 0);\n}\n\n/**\n * Check for prototype pollution in an object, including nested objects.\n * Returns true if the object is safe, false if dangerous keys are found.\n *\n * @param obj - The object to check\n * @param maxDepth - Maximum nesting depth to check (default: 50)\n * @returns True if safe, false if dangerous keys found\n */\nexport function isPrototypeSafe(obj: unknown, maxDepth = 50): boolean {\n\tconst dangerousKeys = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\tconst seen = new WeakSet();\n\n\tfunction check(val: unknown, depth: number): boolean {\n\t\tif (depth > maxDepth) return false; // Fail safe at max depth - don't assume safety\n\t\tif (val === null || val === undefined) return true;\n\t\tif (typeof val !== \"object\") return true;\n\n\t\tconst objVal = val as Record<string, unknown>;\n\n\t\t// Check for circular reference\n\t\tif (seen.has(objVal)) return true;\n\t\tseen.add(objVal);\n\n\t\t// Check array elements\n\t\tif (Array.isArray(objVal)) {\n\t\t\tfor (const item of objVal) {\n\t\t\t\tif (!check(item, depth + 1)) {\n\t\t\t\t\tseen.delete(objVal);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tseen.delete(objVal);\n\t\t\treturn true;\n\t\t}\n\n\t\t// Check object keys and values\n\t\tfor (const key of Object.keys(objVal)) {\n\t\t\tif (dangerousKeys.has(key)) {\n\t\t\t\tseen.delete(objVal);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!check(objVal[key], depth + 1)) {\n\t\t\t\tseen.delete(objVal);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tseen.delete(objVal);\n\t\treturn true;\n\t}\n\n\treturn check(obj, 0);\n}\n\n/**\n * Shallow equality comparison for objects.\n * Used by React hooks to avoid unnecessary re-renders.\n *\n * @param a - First object\n * @param b - Second object\n * @returns True if objects are shallowly equal\n */\nexport function shallowEqual<T extends Record<string, unknown>>(a: T, b: T): boolean {\n\tif (a === b) return true;\n\tif (!a || !b) return false;\n\n\tconst keysA = Object.keys(a);\n\tconst keysB = Object.keys(b);\n\n\tif (keysA.length !== keysB.length) return false;\n\n\tfor (const key of keysA) {\n\t\tif (a[key] !== b[key]) return false;\n\t}\n\n\treturn true;\n}\n\n/**\n * Generate a simple hash string from an object.\n * Uses djb2 algorithm on the stable stringified value.\n *\n * **Limitations:**\n * - 32-bit hash output means collision probability increases with data set size\n * (birthday paradox: ~50% collision chance at ~77,000 distinct values)\n * - Suitable for: cache invalidation, change detection, deduplication of small sets\n * - NOT suitable for: cryptographic use, security-sensitive operations, large-scale deduplication\n *\n * For security-sensitive use cases requiring stronger collision resistance,\n * consider using a cryptographic hash like SHA-256.\n *\n * @param value - The value to hash\n * @returns A hex hash string (8 characters, 32 bits)\n */\nexport function hashObject(value: unknown): string {\n\tconst str = stableStringify(value);\n\tlet hash = 5381;\n\tfor (let i = 0; i < str.length; i++) {\n\t\thash = ((hash << 5) + hash) ^ str.charCodeAt(i);\n\t}\n\t// Convert to unsigned 32-bit and then to hex\n\treturn (hash >>> 0).toString(16);\n}\n\n// ============================================================================\n// Distributable Snapshot Utilities\n// ============================================================================\n\n/**\n * Distributable snapshot type for type-safe helper functions.\n */\nexport interface DistributableSnapshotLike<T = Record<string, unknown>> {\n\tdata: T;\n\tcreatedAt: number;\n\texpiresAt?: number;\n\tversion?: string;\n\tmetadata?: Record<string, unknown>;\n}\n\n/**\n * Check if a distributable snapshot has expired.\n * Returns false if the snapshot has no expiresAt field.\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({ ttlSeconds: 3600 });\n * // ... later ...\n * if (isSnapshotExpired(snapshot)) {\n * // Refresh the snapshot\n * }\n * ```\n *\n * @param snapshot - The snapshot to check\n * @param now - Optional current timestamp (defaults to Date.now())\n * @returns True if the snapshot has expired, false otherwise\n */\nexport function isSnapshotExpired<T>(\n\tsnapshot: DistributableSnapshotLike<T>,\n\tnow: number = Date.now(),\n): boolean {\n\treturn snapshot.expiresAt !== undefined && now > snapshot.expiresAt;\n}\n\n/**\n * Validate a distributable snapshot and return its data.\n * Throws if the snapshot is malformed or has expired.\n *\n * @example\n * ```typescript\n * const cached = JSON.parse(await redis.get(`entitlements:${userId}`));\n * try {\n * const data = validateSnapshot(cached);\n * // Use data.canUseFeature, etc.\n * } catch (e) {\n * // Snapshot invalid or expired, refresh it\n * }\n * ```\n *\n * @example Using custom timestamp for testing\n * ```typescript\n * const snapshot = { data: { test: true }, createdAt: 1000, expiresAt: 2000 };\n * validateSnapshot(snapshot, 1500); // Returns { test: true }\n * validateSnapshot(snapshot, 2500); // Throws: Snapshot expired\n * ```\n *\n * @param snapshot - The snapshot to validate\n * @param now - Optional current timestamp (defaults to Date.now())\n * @returns The snapshot data if valid\n * @throws Error if the snapshot is malformed or has expired\n */\nexport function validateSnapshot<T>(\n\tsnapshot: DistributableSnapshotLike<T>,\n\tnow: number = Date.now(),\n): T {\n\t// Structural validation\n\tif (!snapshot || typeof snapshot !== \"object\") {\n\t\tthrow new Error(\n\t\t\t\"[Directive] Invalid snapshot: expected an object with 'data' and 'createdAt' properties.\",\n\t\t);\n\t}\n\tif (!(\"data\" in snapshot)) {\n\t\tthrow new Error(\n\t\t\t\"[Directive] Invalid snapshot: missing required 'data' property.\",\n\t\t);\n\t}\n\tif (!(\"createdAt\" in snapshot) || typeof snapshot.createdAt !== \"number\") {\n\t\tthrow new Error(\n\t\t\t\"[Directive] Invalid snapshot: missing or invalid 'createdAt' property (expected number).\",\n\t\t);\n\t}\n\n\t// Expiration validation\n\tif (isSnapshotExpired(snapshot, now)) {\n\t\tconst expiredAt = new Date(snapshot.expiresAt!).toISOString();\n\t\tthrow new Error(\n\t\t\t`[Directive] Snapshot expired at ${expiredAt}. Obtain a fresh snapshot from the source.`,\n\t\t);\n\t}\n\treturn snapshot.data;\n}\n\n/**\n * Diff result for a single changed value.\n */\nexport interface SnapshotDiffEntry {\n\t/** The key path that changed (e.g., \"canUseApi\" or \"limits.apiCalls\") */\n\tpath: string;\n\t/** The value in the old snapshot */\n\toldValue: unknown;\n\t/** The value in the new snapshot */\n\tnewValue: unknown;\n\t/** Type of change: \"added\", \"removed\", or \"changed\" */\n\ttype: \"added\" | \"removed\" | \"changed\";\n}\n\n/**\n * Result of diffing two snapshots.\n */\nexport interface SnapshotDiff {\n\t/** Whether the snapshots are identical */\n\tidentical: boolean;\n\t/** List of changes between snapshots */\n\tchanges: SnapshotDiffEntry[];\n\t/** Whether the version changed (if both have versions) */\n\tversionChanged: boolean;\n\t/** Old version (if available) */\n\toldVersion?: string;\n\t/** New version (if available) */\n\tnewVersion?: string;\n}\n\n/**\n * Compare two distributable snapshots and return the differences.\n * Useful for debugging, audit logs, and webhook payloads.\n *\n * @example\n * ```typescript\n * const oldSnapshot = system.getDistributableSnapshot({ includeVersion: true });\n * system.dispatch({ type: \"upgradePlan\", plan: \"pro\" });\n * const newSnapshot = system.getDistributableSnapshot({ includeVersion: true });\n *\n * const diff = diffSnapshots(oldSnapshot, newSnapshot);\n * if (!diff.identical) {\n * console.log(\"Changes:\", diff.changes);\n * // [{ path: \"canUseApi\", oldValue: false, newValue: true, type: \"changed\" }]\n * }\n * ```\n *\n * @param oldSnapshot - The previous snapshot\n * @param newSnapshot - The new snapshot\n * @returns A diff result with all changes\n */\nexport function diffSnapshots<T = Record<string, unknown>>(\n\toldSnapshot: DistributableSnapshotLike<T>,\n\tnewSnapshot: DistributableSnapshotLike<T>,\n): SnapshotDiff {\n\tconst changes: SnapshotDiffEntry[] = [];\n\n\t// Deep compare function\n\tfunction compare(\n\t\toldObj: unknown,\n\t\tnewObj: unknown,\n\t\tpath: string,\n\t): void {\n\t\t// Handle null/undefined\n\t\tif (oldObj === null || oldObj === undefined) {\n\t\t\tif (newObj !== null && newObj !== undefined) {\n\t\t\t\tchanges.push({ path, oldValue: oldObj, newValue: newObj, type: \"added\" });\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (newObj === null || newObj === undefined) {\n\t\t\tchanges.push({ path, oldValue: oldObj, newValue: newObj, type: \"removed\" });\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle primitives\n\t\tif (typeof oldObj !== \"object\" || typeof newObj !== \"object\") {\n\t\t\tif (!Object.is(oldObj, newObj)) {\n\t\t\t\tchanges.push({ path, oldValue: oldObj, newValue: newObj, type: \"changed\" });\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle arrays\n\t\tif (Array.isArray(oldObj) && Array.isArray(newObj)) {\n\t\t\tif (oldObj.length !== newObj.length) {\n\t\t\t\tchanges.push({ path, oldValue: oldObj, newValue: newObj, type: \"changed\" });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (let i = 0; i < oldObj.length; i++) {\n\t\t\t\tcompare(oldObj[i], newObj[i], `${path}[${i}]`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle objects\n\t\tconst oldRecord = oldObj as Record<string, unknown>;\n\t\tconst newRecord = newObj as Record<string, unknown>;\n\t\tconst allKeys = new Set([...Object.keys(oldRecord), ...Object.keys(newRecord)]);\n\n\t\tfor (const key of allKeys) {\n\t\t\tconst childPath = path ? `${path}.${key}` : key;\n\t\t\tif (!(key in oldRecord)) {\n\t\t\t\tchanges.push({ path: childPath, oldValue: undefined, newValue: newRecord[key], type: \"added\" });\n\t\t\t} else if (!(key in newRecord)) {\n\t\t\t\tchanges.push({ path: childPath, oldValue: oldRecord[key], newValue: undefined, type: \"removed\" });\n\t\t\t} else {\n\t\t\t\tcompare(oldRecord[key], newRecord[key], childPath);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Compare data\n\tcompare(oldSnapshot.data, newSnapshot.data, \"\");\n\n\t// Check version change\n\tconst versionChanged = oldSnapshot.version !== newSnapshot.version &&\n\t\t(oldSnapshot.version !== undefined || newSnapshot.version !== undefined);\n\n\treturn {\n\t\tidentical: changes.length === 0,\n\t\tchanges,\n\t\tversionChanged,\n\t\toldVersion: oldSnapshot.version,\n\t\tnewVersion: newSnapshot.version,\n\t};\n}\n\n// ============================================================================\n// Snapshot Signing (HMAC)\n// ============================================================================\n\n/**\n * A signed distributable snapshot.\n * Contains the original snapshot plus a cryptographic signature.\n */\nexport interface SignedSnapshot<T = Record<string, unknown>>\n\textends DistributableSnapshotLike<T> {\n\t/** HMAC-SHA256 signature in hex format */\n\tsignature: string;\n\t/** Signing algorithm used */\n\talgorithm: \"hmac-sha256\";\n}\n\n/**\n * Check if a snapshot is signed.\n *\n * @param snapshot - The snapshot to check\n * @returns True if the snapshot has a signature\n */\nexport function isSignedSnapshot<T>(\n\tsnapshot: DistributableSnapshotLike<T> | SignedSnapshot<T>,\n): snapshot is SignedSnapshot<T> {\n\treturn \"signature\" in snapshot && typeof snapshot.signature === \"string\";\n}\n\n/**\n * Sign a distributable snapshot using HMAC-SHA256.\n * Creates a tamper-proof signature that can be verified later.\n *\n * **Security Notes:**\n * - Use a cryptographically random secret of at least 32 bytes\n * - Store the secret securely (environment variable, secrets manager)\n * - Never expose the secret to clients\n * - The signature covers all snapshot fields for integrity\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({\n * includeDerivations: ['canUseFeature', 'limits'],\n * ttlSeconds: 3600,\n * });\n *\n * // Sign the snapshot (server-side only)\n * const signed = await signSnapshot(snapshot, process.env.SNAPSHOT_SECRET);\n *\n * // Store in JWT, Redis, or send to client\n * const jwt = createJWT({ snapshot: signed });\n *\n * // Later, verify the signature\n * const isValid = await verifySnapshotSignature(signed, process.env.SNAPSHOT_SECRET);\n * if (!isValid) {\n * throw new Error('Snapshot has been tampered with');\n * }\n * ```\n *\n * @param snapshot - The snapshot to sign\n * @param secret - The HMAC secret (string or Uint8Array)\n * @returns A signed snapshot with the signature attached\n */\nexport async function signSnapshot<T>(\n\tsnapshot: DistributableSnapshotLike<T>,\n\tsecret: string | Uint8Array,\n): Promise<SignedSnapshot<T>> {\n\t// Create a canonical representation for signing\n\tconst payload = stableStringify({\n\t\tdata: snapshot.data,\n\t\tcreatedAt: snapshot.createdAt,\n\t\texpiresAt: snapshot.expiresAt,\n\t\tversion: snapshot.version,\n\t\tmetadata: snapshot.metadata,\n\t});\n\n\tconst signature = await hmacSha256(payload, secret);\n\n\treturn {\n\t\t...snapshot,\n\t\tsignature,\n\t\talgorithm: \"hmac-sha256\",\n\t};\n}\n\n/**\n * Verify the signature of a signed snapshot.\n * Returns true if the signature is valid, false otherwise.\n *\n * **Important:** Always verify signatures before trusting snapshot data,\n * especially if the snapshot was received from an untrusted source (client, cache).\n *\n * @example\n * ```typescript\n * // Receive signed snapshot from client or cache\n * const snapshot = JSON.parse(cachedData);\n *\n * // Verify before using\n * const isValid = await verifySnapshotSignature(snapshot, process.env.SNAPSHOT_SECRET);\n * if (!isValid) {\n * throw new Error('Invalid snapshot signature - possible tampering');\n * }\n *\n * // Now safe to use snapshot.data\n * if (snapshot.data.canUseFeature.api) {\n * // Grant access\n * }\n * ```\n *\n * @param signedSnapshot - The signed snapshot to verify\n * @param secret - The HMAC secret (must match the signing secret)\n * @returns True if signature is valid, false otherwise\n */\nexport async function verifySnapshotSignature<T>(\n\tsignedSnapshot: SignedSnapshot<T>,\n\tsecret: string | Uint8Array,\n): Promise<boolean> {\n\tif (!signedSnapshot.signature || signedSnapshot.algorithm !== \"hmac-sha256\") {\n\t\treturn false;\n\t}\n\n\t// Recreate the canonical payload (same as signing)\n\tconst payload = stableStringify({\n\t\tdata: signedSnapshot.data,\n\t\tcreatedAt: signedSnapshot.createdAt,\n\t\texpiresAt: signedSnapshot.expiresAt,\n\t\tversion: signedSnapshot.version,\n\t\tmetadata: signedSnapshot.metadata,\n\t});\n\n\tconst expectedSignature = await hmacSha256(payload, secret);\n\n\t// Use timing-safe comparison\n\treturn timingSafeEqual(signedSnapshot.signature, expectedSignature);\n}\n\n/**\n * Create HMAC-SHA256 signature of a message.\n * Uses Web Crypto API for cross-platform support (Node.js, browsers, Deno, Bun).\n */\nasync function hmacSha256(\n\tmessage: string,\n\tsecret: string | Uint8Array,\n): Promise<string> {\n\t// Convert secret to Uint8Array if string\n\tconst secretBytes: Uint8Array =\n\t\ttypeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\n\t// Import key for HMAC\n\tconst algorithm: HmacImportParams = { name: \"HMAC\", hash: { name: \"SHA-256\" } };\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tsecretBytes as unknown as ArrayBuffer,\n\t\talgorithm,\n\t\tfalse,\n\t\t[\"sign\"],\n\t);\n\n\t// Sign the message\n\tconst messageBytes = new TextEncoder().encode(message);\n\tconst signature = await crypto.subtle.sign(\"HMAC\", key, messageBytes);\n\n\t// Convert to hex string\n\treturn Array.from(new Uint8Array(signature))\n\t\t.map((b) => b.toString(16).padStart(2, \"0\"))\n\t\t.join(\"\");\n}\n\n/**\n * Timing-safe string comparison to prevent timing attacks.\n * Both strings should be the same length (hex signatures from same algorithm).\n */\nfunction timingSafeEqual(a: string, b: string): boolean {\n\tif (a.length !== b.length) {\n\t\treturn false;\n\t}\n\n\tlet result = 0;\n\tfor (let i = 0; i < a.length; i++) {\n\t\tresult |= a.charCodeAt(i) ^ b.charCodeAt(i);\n\t}\n\treturn result === 0;\n}\n","/**\n * Requirements - Typed requirement identity with custom dedupe keys\n *\n * Features:\n * - Type-safe requirement definitions\n * - Stable identity generation\n * - Custom key functions for deduplication control\n * - Requirement comparison and hashing\n */\n\nimport type { Requirement, RequirementKeyFn, RequirementWithId } from \"./types.js\";\nimport { stableStringify } from \"../utils/utils.js\";\n\n// ============================================================================\n// Requirement Identity\n// ============================================================================\n\n/**\n * Generate a stable ID for a requirement.\n * Uses type + sorted properties by default.\n */\nexport function generateRequirementId(\n\treq: Requirement,\n\tkeyFn?: RequirementKeyFn,\n): string {\n\t// Use custom key function if provided\n\tif (keyFn) {\n\t\treturn keyFn(req);\n\t}\n\n\t// Default: type + stable JSON of other properties\n\tconst { type, ...rest } = req;\n\tconst sortedRest = stableStringify(rest);\n\treturn `${type}:${sortedRest}`;\n}\n\n/**\n * Check if two requirements are equal by their IDs.\n */\nexport function requirementsEqual(\n\ta: RequirementWithId,\n\tb: RequirementWithId,\n): boolean {\n\treturn a.id === b.id;\n}\n\n/**\n * Create a requirement with its computed ID.\n */\nexport function createRequirementWithId(\n\trequirement: Requirement,\n\tfromConstraint: string,\n\tkeyFn?: RequirementKeyFn,\n): RequirementWithId {\n\treturn {\n\t\trequirement,\n\t\tid: generateRequirementId(requirement, keyFn),\n\t\tfromConstraint,\n\t};\n}\n\n// ============================================================================\n// Requirement Helpers\n// ============================================================================\n\n/**\n * Helper to create typed requirements with a fluent API.\n *\n * Creates a factory function that produces requirements with a specific type.\n * Useful for creating requirements in constraint definitions.\n *\n * @param type - The requirement type string\n * @returns A factory function that creates requirements with the given type\n *\n * @example\n * ```typescript\n * // Create a requirement factory\n * const fetchUser = req(\"FETCH_USER\");\n *\n * // Use in constraint definition\n * constraints: {\n * needsUser: {\n * when: (facts) => facts.userId && !facts.user,\n * require: fetchUser({ userId: 123, priority: \"high\" }),\n * },\n * }\n *\n * // Results in: { type: \"FETCH_USER\", userId: 123, priority: \"high\" }\n * ```\n */\nexport function req<T extends string>(type: T) {\n\treturn <P extends Record<string, unknown>>(props: P) => ({\n\t\ttype,\n\t\t...props,\n\t}) as Requirement & { type: T } & P;\n}\n\n/**\n * Check if a requirement matches a type.\n */\nexport function isRequirementType<T extends string>(\n\treq: Requirement,\n\ttype: T,\n): req is Requirement & { type: T } {\n\treturn req.type === type;\n}\n\n/**\n * Create a type guard for resolver `requirement` predicate.\n * Cleaner alternative to writing verbose type guards.\n *\n * @example\n * ```typescript\n * // With explicit requirement type (recommended for complex types)\n * interface FetchUserRequirement { type: \"FETCH_USER\"; userId: string }\n * requirement: forType<FetchUserRequirement>(\"FETCH_USER\"),\n * key: (req) => req.userId, // req is FetchUserRequirement\n *\n * // Or simple string literal (for basic types)\n * requirement: forType(\"FETCH_USER\"),\n * key: (req) => req.type, // req is Requirement & { type: \"FETCH_USER\" }\n * ```\n */\nexport function forType<R extends Requirement>(\n\ttype: R[\"type\"],\n): (req: Requirement) => req is R;\nexport function forType<T extends string>(\n\ttype: T,\n): (req: Requirement) => req is Requirement & { type: T };\nexport function forType<T extends string>(\n\ttype: T,\n): (req: Requirement) => req is Requirement & { type: T } {\n\treturn (req): req is Requirement & { type: T } => req.type === type;\n}\n\n// ============================================================================\n// Requirement Set Management\n// ============================================================================\n\n/**\n * A set of requirements with automatic deduplication by ID.\n *\n * Requirements are uniquely identified by their ID (generated from type + properties).\n * When adding a requirement with a duplicate ID, the first one wins.\n *\n * @example\n * ```typescript\n * const set = new RequirementSet();\n *\n * // Add requirements\n * set.add(createRequirementWithId({ type: \"FETCH_USER\", userId: 1 }, \"constraint1\"));\n * set.add(createRequirementWithId({ type: \"FETCH_USER\", userId: 1 }, \"constraint2\")); // Ignored (duplicate)\n *\n * // Check and retrieve\n * console.log(set.size); // 1\n * console.log(set.has(\"FETCH_USER:{\\\"userId\\\":1}\")); // true\n *\n * // Diff with another set\n * const newSet = new RequirementSet();\n * newSet.add(createRequirementWithId({ type: \"FETCH_USER\", userId: 2 }, \"constraint1\"));\n * const { added, removed } = newSet.diff(set);\n * // added: [{ type: \"FETCH_USER\", userId: 2 }]\n * // removed: [{ type: \"FETCH_USER\", userId: 1 }]\n * ```\n */\nexport class RequirementSet {\n\tprivate map = new Map<string, RequirementWithId>();\n\n\t/**\n\t * Add a requirement to the set.\n\t * If a requirement with the same ID already exists, it is ignored (first wins).\n\t * @param req - The requirement with its computed ID\n\t */\n\tadd(req: RequirementWithId): void {\n\t\t// If already exists, keep the existing one (first wins)\n\t\tif (!this.map.has(req.id)) {\n\t\t\tthis.map.set(req.id, req);\n\t\t}\n\t}\n\n\t/** Remove a requirement by ID */\n\tremove(id: string): boolean {\n\t\treturn this.map.delete(id);\n\t}\n\n\t/** Check if a requirement exists */\n\thas(id: string): boolean {\n\t\treturn this.map.has(id);\n\t}\n\n\t/** Get a requirement by ID */\n\tget(id: string): RequirementWithId | undefined {\n\t\treturn this.map.get(id);\n\t}\n\n\t/** Get all requirements */\n\tall(): RequirementWithId[] {\n\t\treturn [...this.map.values()];\n\t}\n\n\t/** Get all requirement IDs */\n\tids(): string[] {\n\t\treturn [...this.map.keys()];\n\t}\n\n\t/** Get the count of requirements */\n\tget size(): number {\n\t\treturn this.map.size;\n\t}\n\n\t/** Clear all requirements */\n\tclear(): void {\n\t\tthis.map.clear();\n\t}\n\n\t/** Create a copy */\n\tclone(): RequirementSet {\n\t\tconst copy = new RequirementSet();\n\t\tfor (const req of this.map.values()) {\n\t\t\tcopy.add(req);\n\t\t}\n\t\treturn copy;\n\t}\n\n\t/** Diff with another set - returns added and removed */\n\tdiff(other: RequirementSet): {\n\t\tadded: RequirementWithId[];\n\t\tremoved: RequirementWithId[];\n\t\tunchanged: RequirementWithId[];\n\t} {\n\t\tconst added: RequirementWithId[] = [];\n\t\tconst removed: RequirementWithId[] = [];\n\t\tconst unchanged: RequirementWithId[] = [];\n\n\t\t// Find added (in this but not in other)\n\t\tfor (const req of this.map.values()) {\n\t\t\tif (!other.has(req.id)) {\n\t\t\t\tadded.push(req);\n\t\t\t} else {\n\t\t\t\tunchanged.push(req);\n\t\t\t}\n\t\t}\n\n\t\t// Find removed (in other but not in this)\n\t\tfor (const req of other.map.values()) {\n\t\t\tif (!this.map.has(req.id)) {\n\t\t\t\tremoved.push(req);\n\t\t\t}\n\t\t}\n\n\t\treturn { added, removed, unchanged };\n\t}\n}\n","/**\n * Constraints - Rules that produce requirements when conditions aren't met\n *\n * Features:\n * - Sync and async constraint evaluation\n * - Priority ordering (higher runs first)\n * - Timeout handling for async constraints\n * - Error isolation\n */\n\nimport { createRequirementWithId, RequirementSet } from \"./requirements.js\";\nimport { withTracking } from \"./tracking.js\";\nimport type {\n\tConstraintsDef,\n\tConstraintState,\n\tFacts,\n\tRequirement,\n\tRequirementKeyFn,\n\tRequirementWithId,\n\tSchema,\n} from \"./types.js\";\nimport { withTimeout } from \"../utils/utils.js\";\n\n// Local type alias for requirement output (avoid type arg issues)\ntype RequirementOutput = Requirement | Requirement[] | null;\n\n// ============================================================================\n// Constraints Manager\n// ============================================================================\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ConstraintsManager<_S extends Schema> {\n\t/** Evaluate all constraints and return unmet requirements */\n\tevaluate(changedKeys?: Set<string>): Promise<RequirementWithId[]>;\n\t/** Get the current state of a constraint */\n\tgetState(id: string): ConstraintState | undefined;\n\t/** Get all constraint states */\n\tgetAllStates(): ConstraintState[];\n\t/** Disable a constraint */\n\tdisable(id: string): void;\n\t/** Enable a constraint */\n\tenable(id: string): void;\n\t/** Invalidate constraints that depend on the given fact key */\n\tinvalidate(factKey: string): void;\n\t/** Mark a constraint's resolver as completed (for `after` ordering) */\n\tmarkResolved(constraintId: string): void;\n\t/** Check if a constraint has been resolved (for `after` ordering) */\n\tisResolved(constraintId: string): boolean;\n\t/** Register new constraint definitions (for dynamic module registration) */\n\tregisterDefinitions(newDefs: ConstraintsDef<Schema>): void;\n}\n\n/** Options for creating a constraints manager */\nexport interface CreateConstraintsOptions<S extends Schema> {\n\tdefinitions: ConstraintsDef<S>;\n\tfacts: Facts<S>;\n\t/** Custom key functions for requirements (by constraint ID) */\n\trequirementKeys?: Record<string, RequirementKeyFn>;\n\t/** Default timeout for async constraints (ms) */\n\tdefaultTimeout?: number;\n\t/** Callback when a constraint is evaluated */\n\tonEvaluate?: (id: string, active: boolean) => void;\n\t/** Callback when a constraint errors */\n\tonError?: (id: string, error: unknown) => void;\n}\n\n/** Default async constraint timeout (5 seconds) */\nconst DEFAULT_TIMEOUT = 5000;\n\n/**\n * Create a manager that evaluates constraint rules and produces unmet\n * requirements.\n *\n * Constraints are evaluated in priority order (higher first), with\n * topological ordering for same-priority constraints connected by `after`\n * dependencies. Supports sync and async `when()` predicates, incremental\n * evaluation based on changed fact keys, and per-constraint enable/disable.\n *\n * @param options - Constraint definitions, facts proxy, custom requirement key functions, and lifecycle callbacks\n * @returns A `ConstraintsManager` with evaluate/invalidate/enable/disable/markResolved methods\n */\nexport function createConstraintsManager<S extends Schema>(\n\toptions: CreateConstraintsOptions<S>,\n): ConstraintsManager<S> {\n\tconst {\n\t\tdefinitions,\n\t\tfacts,\n\t\trequirementKeys = {},\n\t\tdefaultTimeout = DEFAULT_TIMEOUT,\n\t\tonEvaluate,\n\t\tonError,\n\t} = options;\n\n\t// Internal state for each constraint\n\tconst states = new Map<string, ConstraintState>();\n\tconst disabled = new Set<string>();\n\n\t// Track which constraints are async\n\tconst asyncConstraintIds = new Set<string>();\n\n\t// Dependency tracking: which facts each constraint depends on\n\tconst constraintDeps = new Map<string, Set<string>>();\n\t// Reverse mapping: which constraints depend on each fact\n\tconst factToConstraints = new Map<string, Set<string>>();\n\t// Track which constraints need re-evaluation\n\tconst dirtyConstraints = new Set<string>();\n\t// Cache latest when() deps so they can be combined with require() deps atomically\n\tconst latestWhenDeps = new Map<string, Set<string>>();\n\t// Track last requirements for each constraint (for incremental updates)\n\tconst lastRequirements = new Map<string, RequirementWithId[]>();\n\t// First evaluation flag\n\tlet hasEvaluated = false;\n\t// Track resolved constraints (for `after` ordering)\n\tconst resolvedConstraints = new Set<string>();\n\t// Track constraints that didn't fire (when() returned false) - they don't block\n\tconst noFireConstraints = new Set<string>();\n\t// Reverse dependency map: which constraints depend on this one (for O(1) markResolved)\n\tconst dependsOnMe = new Map<string, Set<string>>();\n\t// Topological order of constraints (dependencies before dependents)\n\tlet topologicalOrder: string[] = [];\n\t// Cached topological index map for O(1) lookups during sorting\n\tlet topologicalIndex: Map<string, number> = new Map();\n\n\t/**\n\t * Build reverse dependency map for O(1) lookups in markResolved.\n\t * Maps each constraint ID to the set of constraints that depend on it via `after`.\n\t */\n\tfunction buildReverseDependencyMap(): void {\n\t\tfor (const [id, def] of Object.entries(definitions)) {\n\t\t\tif (def.after) {\n\t\t\t\tfor (const depId of def.after) {\n\t\t\t\t\tif (definitions[depId]) {\n\t\t\t\t\t\tif (!dependsOnMe.has(depId)) {\n\t\t\t\t\t\t\tdependsOnMe.set(depId, new Set());\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdependsOnMe.get(depId)!.add(id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Detect cycles in the constraint dependency graph and compute topological order.\n\t * Uses DFS to find back edges and post-order for topological sort.\n\t *\n\t * The DFS visits dependencies first (via `after`), so post-order naturally gives us\n\t * topological order where dependencies appear before their dependents.\n\t */\n\tfunction detectCyclesAndComputeTopoOrder(): void {\n\t\tconst visited = new Set<string>();\n\t\tconst visiting = new Set<string>();\n\t\tconst postOrder: string[] = [];\n\n\t\tfunction visit(id: string, path: string[]): void {\n\t\t\tif (visited.has(id)) return;\n\n\t\t\tif (visiting.has(id)) {\n\t\t\t\tconst cycleStart = path.indexOf(id);\n\t\t\t\tconst cycle = [...path.slice(cycleStart), id].join(\" → \");\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Constraint cycle detected: ${cycle}. ` +\n\t\t\t\t\t`Remove one of the \\`after\\` dependencies to break the cycle.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tvisiting.add(id);\n\t\t\tpath.push(id);\n\n\t\t\tconst def = definitions[id];\n\t\t\tif (def?.after) {\n\t\t\t\tfor (const depId of def.after) {\n\t\t\t\t\t// Only check deps that exist in this manager\n\t\t\t\t\tif (definitions[depId]) {\n\t\t\t\t\t\tvisit(depId, path);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpath.pop();\n\t\t\tvisiting.delete(id);\n\t\t\tvisited.add(id);\n\t\t\tpostOrder.push(id);\n\t\t}\n\n\t\tfor (const id of Object.keys(definitions)) {\n\t\t\tvisit(id, []);\n\t\t}\n\n\t\t// Post-order with dependency-first traversal gives us topological order\n\t\t// (dependencies are added before dependents)\n\t\ttopologicalOrder = postOrder;\n\n\t\t// Build index map for O(1) lookups during sorting\n\t\ttopologicalIndex = new Map(topologicalOrder.map((id, index) => [id, index]));\n\t}\n\n\t// Validate constraint graph (always run - cycle in production would cause deadlock)\n\t// Also computes topological order for O(n) evaluation\n\tdetectCyclesAndComputeTopoOrder();\n\n\t// Build reverse dependency map for O(1) markResolved lookups\n\tbuildReverseDependencyMap();\n\n\t// Validate `after` references in dev mode (catch typos early)\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tfor (const [id, def] of Object.entries(definitions)) {\n\t\t\tif (def.after) {\n\t\t\t\tfor (const depId of def.after) {\n\t\t\t\t\tif (!definitions[depId]) {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[Directive] Constraint \"${id}\" references unknown constraint \"${depId}\" in \\`after\\`. ` +\n\t\t\t\t\t\t\t\t`This dependency will be ignored. Check for typos or ensure the constraint exists.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Determine if a constraint is async.\n\t * Uses the explicit `async` flag if provided, otherwise falls back to runtime detection.\n\t * Runtime detection is only used on first evaluation and logs a dev warning.\n\t */\n\tfunction isAsyncConstraint(id: string, def: ConstraintsDef<S>[string]): boolean {\n\t\t// Prefer explicit flag to avoid runtime detection side effects\n\t\tif (def.async !== undefined) {\n\t\t\treturn def.async;\n\t\t}\n\n\t\t// Check if we've already detected this constraint as async\n\t\tif (asyncConstraintIds.has(id)) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Runtime detection is deferred to first evaluation\n\t\t// We'll detect it in evaluateSync if it returns a Promise\n\t\treturn false;\n\t}\n\n\t/** Initialize state for a constraint */\n\tfunction initState(id: string): ConstraintState {\n\t\tconst def = definitions[id];\n\t\tif (!def) {\n\t\t\tthrow new Error(`[Directive] Unknown constraint: ${id}`);\n\t\t}\n\n\t\tconst isAsync = isAsyncConstraint(id, def);\n\t\tif (isAsync) {\n\t\t\tasyncConstraintIds.add(id);\n\t\t}\n\n\t\tconst state: ConstraintState = {\n\t\t\tid,\n\t\t\tpriority: def.priority ?? 0,\n\t\t\tisAsync,\n\t\t\tlastResult: null,\n\t\t\tisEvaluating: false,\n\t\t\terror: null,\n\t\t\tlastResolvedAt: null,\n\t\t\tafter: def.after ?? [],\n\t\t};\n\n\t\tstates.set(id, state);\n\t\treturn state;\n\t}\n\n\t/** Get or create state for a constraint */\n\tfunction getState(id: string): ConstraintState {\n\t\treturn states.get(id) ?? initState(id);\n\t}\n\n\t/** Update dependency tracking for a constraint */\n\tfunction updateDependencies(id: string, newDeps: Set<string>): void {\n\t\tconst oldDeps = constraintDeps.get(id) ?? new Set();\n\n\t\t// Remove old dependencies\n\t\tfor (const dep of oldDeps) {\n\t\t\tconst constraints = factToConstraints.get(dep);\n\t\t\tconstraints?.delete(id);\n\t\t\tif (constraints && constraints.size === 0) {\n\t\t\t\tfactToConstraints.delete(dep);\n\t\t\t}\n\t\t}\n\n\t\t// Add new dependencies\n\t\tfor (const dep of newDeps) {\n\t\t\tif (!factToConstraints.has(dep)) {\n\t\t\t\tfactToConstraints.set(dep, new Set());\n\t\t\t}\n\t\t\tfactToConstraints.get(dep)!.add(id);\n\t\t}\n\n\t\tconstraintDeps.set(id, newDeps);\n\t}\n\n\t/** Evaluate a single sync constraint */\n\tfunction evaluateSync(id: string): boolean | Promise<boolean> {\n\t\tconst def = definitions[id];\n\t\tif (!def) return false;\n\n\t\tconst state = getState(id);\n\n\t\tstate.isEvaluating = true;\n\t\tstate.error = null;\n\n\t\ttry {\n\t\t\t// If explicit deps are provided, skip auto-tracking overhead\n\t\t\tlet result: boolean | Promise<boolean>;\n\t\t\tif (def.deps) {\n\t\t\t\tresult = def.when(facts);\n\t\t\t\tlatestWhenDeps.set(id, new Set(def.deps));\n\t\t\t} else {\n\t\t\t\t// Track dependencies during evaluation\n\t\t\t\tconst tracked = withTracking(() => def.when(facts));\n\t\t\t\tresult = tracked.value;\n\t\t\t\t// Save when deps — combined with require deps in processConstraintResult\n\t\t\t\tlatestWhenDeps.set(id, tracked.deps);\n\t\t\t}\n\n\t\t\t// Runtime async detection: if this was thought to be sync but returns a Promise\n\t\t\tif (result instanceof Promise) {\n\t\t\t\t// Mark as async for future evaluations\n\t\t\t\tasyncConstraintIds.add(id);\n\t\t\t\tstate.isAsync = true;\n\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] Constraint \"${id}\" returned a Promise but was not marked as async. ` +\n\t\t\t\t\t\t\t`Add \\`async: true\\` to the constraint definition to avoid this warning and improve performance.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Return the promise to be handled as async\n\t\t\t\treturn result.then((asyncResult) => {\n\t\t\t\t\tstate.lastResult = asyncResult;\n\t\t\t\t\tstate.isEvaluating = false;\n\t\t\t\t\tonEvaluate?.(id, asyncResult);\n\t\t\t\t\treturn asyncResult;\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tstate.error = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\tstate.lastResult = false;\n\t\t\t\t\tstate.isEvaluating = false;\n\t\t\t\t\tonError?.(id, error);\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tstate.lastResult = result;\n\t\t\tstate.isEvaluating = false;\n\t\t\tonEvaluate?.(id, result);\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tstate.error = error instanceof Error ? error : new Error(String(error));\n\t\t\tstate.lastResult = false;\n\t\t\tstate.isEvaluating = false;\n\t\t\tonError?.(id, error);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** Evaluate a single async constraint with timeout */\n\tasync function evaluateAsync(id: string): Promise<boolean> {\n\t\tconst def = definitions[id];\n\t\tif (!def) return false;\n\n\t\tconst state = getState(id);\n\t\tconst timeout = def.timeout ?? defaultTimeout;\n\n\t\tstate.isEvaluating = true;\n\t\tstate.error = null;\n\n\t\t// Register explicit deps before await (auto-tracking can't work across async boundaries)\n\t\tif (def.deps?.length) {\n\t\t\tconst depsSet = new Set(def.deps);\n\t\t\tupdateDependencies(id, depsSet);\n\t\t\tlatestWhenDeps.set(id, depsSet);\n\t\t}\n\n\t\ttry {\n\t\t\tconst resultPromise = def.when(facts) as Promise<boolean>;\n\n\t\t\t// Race against timeout (with proper cleanup)\n\t\t\tconst result = await withTimeout(\n\t\t\t\tresultPromise,\n\t\t\t\ttimeout,\n\t\t\t\t`Constraint \"${id}\" timed out after ${timeout}ms`,\n\t\t\t);\n\n\t\t\tstate.lastResult = result;\n\t\t\tstate.isEvaluating = false;\n\t\t\tonEvaluate?.(id, result);\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tstate.error = error instanceof Error ? error : new Error(String(error));\n\t\t\tstate.lastResult = false;\n\t\t\tstate.isEvaluating = false;\n\t\t\tonError?.(id, error);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** Max requirements per constraint before warning in dev mode */\n\tconst MAX_REQUIREMENTS_WARNING_THRESHOLD = 10;\n\n\t/**\n\t * Normalize a requirement output to an array of requirements.\n\t * - null/undefined → []\n\t * - single requirement → [requirement]\n\t * - array → filtered to remove null/undefined\n\t */\n\tfunction normalizeRequirements(output: RequirementOutput, constraintId?: string): Requirement[] {\n\t\tif (output === null || output === undefined) {\n\t\t\treturn [];\n\t\t}\n\t\tif (Array.isArray(output)) {\n\t\t\t// Filter out null/undefined from arrays\n\t\t\tconst filtered = output.filter((r): r is Requirement => r !== null && r !== undefined);\n\n\t\t\t// Warn in dev mode if constraint produces many requirements\n\t\t\tif (\n\t\t\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\t\t\tfiltered.length > MAX_REQUIREMENTS_WARNING_THRESHOLD &&\n\t\t\t\tconstraintId\n\t\t\t) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] Constraint \"${constraintId}\" produced ${filtered.length} requirements. ` +\n\t\t\t\t\t\t`Consider splitting into multiple constraints for better performance.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn filtered;\n\t\t}\n\t\treturn [output];\n\t}\n\n\t/** Get the requirements for a constraint, tracking dependencies if require is a function */\n\tfunction getRequirements(id: string): { requirements: Requirement[]; deps: Set<string> } {\n\t\tconst def = definitions[id];\n\t\tif (!def) return { requirements: [], deps: new Set() };\n\n\t\tconst requireDef = def.require;\n\t\tif (typeof requireDef === \"function\") {\n\t\t\t// Track dependencies when require is a function\n\t\t\tconst { value: output, deps } = withTracking(() => requireDef(facts));\n\t\t\tconst requirements = normalizeRequirements(output as RequirementOutput, id);\n\t\t\treturn { requirements, deps };\n\t\t}\n\n\t\tconst requirements = normalizeRequirements(requireDef as RequirementOutput, id);\n\t\treturn { requirements, deps: new Set() };\n\t}\n\n\t/** Merge additional dependencies into existing constraint deps */\n\tfunction mergeDependencies(id: string, additionalDeps: Set<string>): void {\n\t\tif (additionalDeps.size === 0) return;\n\n\t\tconst existingDeps = constraintDeps.get(id) ?? new Set();\n\t\tfor (const dep of additionalDeps) {\n\t\t\texistingDeps.add(dep);\n\t\t\t// Update reverse mapping\n\t\t\tif (!factToConstraints.has(dep)) {\n\t\t\t\tfactToConstraints.set(dep, new Set());\n\t\t\t}\n\t\t\tfactToConstraints.get(dep)!.add(id);\n\t\t}\n\t\tconstraintDeps.set(id, existingDeps);\n\t}\n\n\t// Initialize all constraint states and cache sorted order\n\tlet sortedConstraintIds: string[] | null = null;\n\n\t/**\n\t * Get constraint IDs sorted by:\n\t * 1. Priority (higher first)\n\t * 2. Topological order (dependencies before dependents) for same priority\n\t * This enables O(n) evaluation in the best case when priorities align with dependencies.\n\t *\n\t * Uses cached topologicalIndex for O(1) lookups during comparison.\n\t */\n\tfunction getSortedConstraintIds(): string[] {\n\t\tif (!sortedConstraintIds) {\n\t\t\tsortedConstraintIds = Object.keys(definitions).sort((a, b) => {\n\t\t\t\tconst stateA = getState(a);\n\t\t\t\tconst stateB = getState(b);\n\n\t\t\t\t// Primary sort: priority (higher first)\n\t\t\t\tconst priorityDiff = stateB.priority - stateA.priority;\n\t\t\t\tif (priorityDiff !== 0) return priorityDiff;\n\n\t\t\t\t// Secondary sort: topological order (dependencies first)\n\t\t\t\t// Uses cached topologicalIndex for O(1) lookups\n\t\t\t\tconst topoA = topologicalIndex.get(a) ?? 0;\n\t\t\t\tconst topoB = topologicalIndex.get(b) ?? 0;\n\t\t\t\treturn topoA - topoB;\n\t\t\t});\n\t\t}\n\t\treturn sortedConstraintIds;\n\t}\n\n\tfor (const id of Object.keys(definitions)) {\n\t\tinitState(id);\n\t}\n\n\t// Dev-mode: warn about async constraints without explicit deps\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tfor (const [id, def] of Object.entries(definitions)) {\n\t\t\tif (def.async && !def.deps) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] Async constraint \"${id}\" has no \\`deps\\` declared. ` +\n\t\t\t\t\t`Auto-tracking cannot work across async boundaries. ` +\n\t\t\t\t\t`Add \\`deps: [\"key1\", \"key2\"]\\` to enable dependency tracking.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Check if a constraint's `after` dependencies are satisfied.\n\t * A dependency is satisfied if:\n\t * - It has been resolved (resolver completed successfully)\n\t * - It didn't fire (when() returned false) - nothing to wait for\n\t * - It is disabled - can't fire\n\t * - It doesn't exist in this manager (cross-module, handled externally)\n\t */\n\tfunction areAfterDependenciesSatisfied(id: string): boolean {\n\t\tconst state = states.get(id);\n\t\tif (!state || state.after.length === 0) return true;\n\n\t\tfor (const depId of state.after) {\n\t\t\t// Skip deps that don't exist (cross-module, handled externally)\n\t\t\tif (!definitions[depId]) continue;\n\n\t\t\t// Skip disabled deps - they can't fire\n\t\t\tif (disabled.has(depId)) continue;\n\n\t\t\t// If dep didn't fire (when returned false), no need to wait\n\t\t\tif (noFireConstraints.has(depId)) continue;\n\n\t\t\t// If dep hasn't been resolved yet, we're blocked\n\t\t\tif (!resolvedConstraints.has(depId)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tconst manager: ConstraintsManager<S> = {\n\t\tasync evaluate(changedKeys?: Set<string>): Promise<RequirementWithId[]> {\n\t\t\tconst requirements = new RequirementSet();\n\n\t\t\t// Note: resolvedConstraints persists across reconcile cycles intentionally.\n\t\t\t// `after` ordering means \"wait until dependency's resolver has completed\",\n\t\t\t// and that completion happens in a different cycle than the evaluation.\n\t\t\t// noFireConstraints is re-populated during each evaluation pass.\n\t\t\tnoFireConstraints.clear();\n\n\t\t\t// Get all enabled constraints (use cached sort order)\n\t\t\tconst allConstraintIds = getSortedConstraintIds().filter((id) => !disabled.has(id));\n\n\t\t\t// Determine which constraints to evaluate\n\t\t\tlet constraintsToEvaluate: string[];\n\n\t\t\tif (!hasEvaluated || !changedKeys || changedKeys.size === 0) {\n\t\t\t\t// First evaluation or no specific changes: evaluate all\n\t\t\t\tconstraintsToEvaluate = allConstraintIds;\n\t\t\t\thasEvaluated = true;\n\t\t\t} else {\n\t\t\t\t// Incremental: only evaluate constraints affected by changed keys\n\t\t\t\tconst affected = new Set<string>();\n\t\t\t\tfor (const key of changedKeys) {\n\t\t\t\t\tconst dependentConstraints = factToConstraints.get(key);\n\t\t\t\t\tif (dependentConstraints) {\n\t\t\t\t\t\tfor (const id of dependentConstraints) {\n\t\t\t\t\t\t\tif (!disabled.has(id)) {\n\t\t\t\t\t\t\t\taffected.add(id);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Also include any dirty constraints\n\t\t\t\tfor (const id of dirtyConstraints) {\n\t\t\t\t\tif (!disabled.has(id)) {\n\t\t\t\t\t\taffected.add(id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdirtyConstraints.clear();\n\t\t\t\tconstraintsToEvaluate = [...affected];\n\n\t\t\t\t// For constraints NOT being re-evaluated, add their last requirements\n\t\t\t\tfor (const id of allConstraintIds) {\n\t\t\t\t\tif (!affected.has(id)) {\n\t\t\t\t\t\tconst lastReqs = lastRequirements.get(id);\n\t\t\t\t\t\tif (lastReqs) {\n\t\t\t\t\t\t\tfor (const req of lastReqs) {\n\t\t\t\t\t\t\t\trequirements.add(req);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Process a constraint result: handle requirements and track no-fire state\n\t\t\t */\n\t\t\tfunction processConstraintResult(id: string, active: boolean): void {\n\t\t\t\tif (disabled.has(id)) return;\n\n\t\t\t\tconst whenDeps = latestWhenDeps.get(id);\n\n\t\t\t\tif (!active) {\n\t\t\t\t\t// when() returned false — update with just when deps (no require deps needed)\n\t\t\t\t\tif (whenDeps !== undefined) {\n\t\t\t\t\t\tupdateDependencies(id, whenDeps);\n\t\t\t\t\t}\n\t\t\t\t\tnoFireConstraints.add(id);\n\t\t\t\t\tlastRequirements.set(id, []);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Remove from no-fire tracking since it fired\n\t\t\t\tnoFireConstraints.delete(id);\n\n\t\t\t\tlet reqs: Requirement[];\n\t\t\t\tlet requireDeps: Set<string>;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = getRequirements(id);\n\t\t\t\t\treqs = result.requirements;\n\t\t\t\t\trequireDeps = result.deps;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tonError?.(id, error);\n\t\t\t\t\tif (whenDeps !== undefined) {\n\t\t\t\t\t\tupdateDependencies(id, whenDeps);\n\t\t\t\t\t}\n\t\t\t\t\tlastRequirements.set(id, []);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// Combine when() + require() deps atomically to prevent\n\t\t\t\t// require deps from being temporarily lost between updates\n\t\t\t\tif (whenDeps !== undefined) {\n\t\t\t\t\tconst combinedDeps = new Set(whenDeps);\n\t\t\t\t\tfor (const dep of requireDeps) {\n\t\t\t\t\t\tcombinedDeps.add(dep);\n\t\t\t\t\t}\n\t\t\t\t\tupdateDependencies(id, combinedDeps);\n\t\t\t\t} else {\n\t\t\t\t\t// Async constraint (no when deps tracked) — merge additively\n\t\t\t\t\tmergeDependencies(id, requireDeps);\n\t\t\t\t}\n\t\t\t\tif (reqs.length > 0) {\n\t\t\t\t\tconst keyFn = requirementKeys[id];\n\t\t\t\t\tconst reqsWithId = reqs.map((req) => createRequirementWithId(req, id, keyFn));\n\t\t\t\t\tfor (const reqWithId of reqsWithId) {\n\t\t\t\t\t\trequirements.add(reqWithId);\n\t\t\t\t\t}\n\t\t\t\t\tlastRequirements.set(id, reqsWithId);\n\t\t\t\t} else {\n\t\t\t\t\tlastRequirements.set(id, []);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Evaluate constraints, respecting `after` dependencies.\n\t\t\t * Returns list of constraints that are still blocked after this pass.\n\t\t\t */\n\t\t\tasync function evaluateConstraintBatch(constraintIds: string[]): Promise<string[]> {\n\t\t\t\t// Filter out constraints blocked by `after` dependencies\n\t\t\t\tconst blockedConstraints: string[] = [];\n\t\t\t\tconst readyToEvaluate: string[] = [];\n\n\t\t\t\tfor (const id of constraintIds) {\n\t\t\t\t\tif (areAfterDependenciesSatisfied(id)) {\n\t\t\t\t\t\treadyToEvaluate.push(id);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblockedConstraints.push(id);\n\t\t\t\t\t\t// Keep last requirements for blocked constraints\n\t\t\t\t\t\tconst lastReqs = lastRequirements.get(id);\n\t\t\t\t\t\tif (lastReqs) {\n\t\t\t\t\t\t\tfor (const req of lastReqs) {\n\t\t\t\t\t\t\t\trequirements.add(req);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (readyToEvaluate.length === 0) {\n\t\t\t\t\treturn blockedConstraints;\n\t\t\t\t}\n\n\t\t\t\t// Separate sync and async constraints from ready-to-evaluate\n\t\t\t\tconst syncConstraints: string[] = [];\n\t\t\t\tconst asyncConstraints: string[] = [];\n\n\t\t\t\tfor (const id of readyToEvaluate) {\n\t\t\t\t\tconst state = getState(id);\n\t\t\t\t\tif (state.isAsync) {\n\t\t\t\t\t\tasyncConstraints.push(id);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsyncConstraints.push(id);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Evaluate sync constraints first (they're fast)\n\t\t\t\t// Some may turn out to be async at runtime - collect those for async evaluation\n\t\t\t\tconst unexpectedAsync: Array<{ id: string; promise: Promise<boolean> }> = [];\n\n\t\t\t\tfor (const id of syncConstraints) {\n\t\t\t\t\tconst result = evaluateSync(id);\n\n\t\t\t\t\t// Handle runtime-detected async constraints\n\t\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\t\tunexpectedAsync.push({ id, promise: result });\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tprocessConstraintResult(id, result);\n\t\t\t\t}\n\n\t\t\t\t// Handle any sync constraints that turned out to be async\n\t\t\t\tif (unexpectedAsync.length > 0) {\n\t\t\t\t\tconst asyncResults = await Promise.all(\n\t\t\t\t\t\tunexpectedAsync.map(async ({ id, promise }) => ({\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tactive: await promise,\n\t\t\t\t\t\t})),\n\t\t\t\t\t);\n\n\t\t\t\t\tfor (const { id, active } of asyncResults) {\n\t\t\t\t\t\tprocessConstraintResult(id, active);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Evaluate async constraints in parallel\n\t\t\t\tif (asyncConstraints.length > 0) {\n\t\t\t\t\tconst asyncResults = await Promise.all(\n\t\t\t\t\t\tasyncConstraints.map(async (id) => ({\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tactive: await evaluateAsync(id),\n\t\t\t\t\t\t})),\n\t\t\t\t\t);\n\n\t\t\t\t\tfor (const { id, active } of asyncResults) {\n\t\t\t\t\t\tprocessConstraintResult(id, active);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn blockedConstraints;\n\t\t\t}\n\n\t\t\t// Evaluate constraints in passes until no blocked constraints become unblocked\n\t\t\tlet remainingToEvaluate = constraintsToEvaluate;\n\t\t\tlet maxPasses = constraintsToEvaluate.length + 1; // Prevent infinite loops\n\n\t\t\twhile (remainingToEvaluate.length > 0 && maxPasses > 0) {\n\t\t\t\tconst previousRemaining = remainingToEvaluate.length;\n\t\t\t\tremainingToEvaluate = await evaluateConstraintBatch(remainingToEvaluate);\n\n\t\t\t\t// If no progress was made (all still blocked), break\n\t\t\t\tif (remainingToEvaluate.length === previousRemaining) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tmaxPasses--;\n\t\t\t}\n\n\t\t\treturn requirements.all();\n\t\t},\n\n\t\tgetState(id: string): ConstraintState | undefined {\n\t\t\treturn states.get(id);\n\t\t},\n\n\t\tgetAllStates(): ConstraintState[] {\n\t\t\treturn [...states.values()];\n\t\t},\n\n\t\tdisable(id: string): void {\n\t\t\tdisabled.add(id);\n\t\t\t// Invalidate cache when constraints change\n\t\t\tsortedConstraintIds = null;\n\t\t\t// Mark as dirty so it gets removed from requirements on next evaluate\n\t\t\tlastRequirements.delete(id);\n\n\t\t\t// Clean up dependency maps for disabled constraint\n\t\t\tconst deps = constraintDeps.get(id);\n\t\t\tif (deps) {\n\t\t\t\tfor (const dep of deps) {\n\t\t\t\t\tconst constraints = factToConstraints.get(dep);\n\t\t\t\t\tif (constraints) {\n\t\t\t\t\t\tconstraints.delete(id);\n\t\t\t\t\t\tif (constraints.size === 0) {\n\t\t\t\t\t\t\tfactToConstraints.delete(dep);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconstraintDeps.delete(id);\n\t\t\t}\n\t\t\tlatestWhenDeps.delete(id);\n\t\t},\n\n\t\tenable(id: string): void {\n\t\t\tdisabled.delete(id);\n\t\t\t// Invalidate cache when constraints change\n\t\t\tsortedConstraintIds = null;\n\t\t\t// Mark as dirty so it gets evaluated on next cycle\n\t\t\tdirtyConstraints.add(id);\n\t\t},\n\n\t\tinvalidate(factKey: string): void {\n\t\t\t// Mark all constraints that depend on this fact as dirty\n\t\t\tconst dependentConstraints = factToConstraints.get(factKey);\n\t\t\tif (dependentConstraints) {\n\t\t\t\tfor (const id of dependentConstraints) {\n\t\t\t\t\tdirtyConstraints.add(id);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tmarkResolved(constraintId: string): void {\n\t\t\tresolvedConstraints.add(constraintId);\n\t\t\tconst state = states.get(constraintId);\n\t\t\tif (state) {\n\t\t\t\tstate.lastResolvedAt = Date.now();\n\t\t\t}\n\n\t\t\t// Mark all constraints that depend on this one (via `after`) as dirty\n\t\t\t// so they get re-evaluated on the next reconcile\n\t\t\t// Uses reverse dependency map for O(1) lookup instead of O(n*m) iteration\n\t\t\tconst dependents = dependsOnMe.get(constraintId);\n\t\t\tif (dependents) {\n\t\t\t\tfor (const id of dependents) {\n\t\t\t\t\tdirtyConstraints.add(id);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tisResolved(constraintId: string): boolean {\n\t\t\treturn resolvedConstraints.has(constraintId);\n\t\t},\n\n\t\tregisterDefinitions(newDefs: ConstraintsDef<Schema>): void {\n\t\t\tfor (const [key, def] of Object.entries(newDefs)) {\n\t\t\t\t(definitions as Record<string, unknown>)[key] = def;\n\t\t\t\tinitState(key);\n\t\t\t\tdirtyConstraints.add(key);\n\t\t\t}\n\t\t\t// Invalidate cached sort order\n\t\t\tsortedConstraintIds = null;\n\t\t\t// Rebuild topological order and reverse dependency map\n\t\t\t// so new `after` deps are validated for cycles and indexed\n\t\t\tdetectCyclesAndComputeTopoOrder();\n\t\t\tbuildReverseDependencyMap();\n\t\t},\n\t};\n\n\treturn manager;\n}\n","/**\n * Derivations - Auto-tracked computed values with composition\n *\n * Features:\n * - Automatic dependency tracking (no manual deps arrays)\n * - Memoization with smart invalidation\n * - Derivation composition (derivations can depend on other derivations)\n * - Circular dependency detection\n * - Lazy evaluation\n */\n\nimport { trackAccess, withTracking } from \"./tracking.js\";\nimport type {\n\tDerivationsDef,\n\tDerivationState,\n\tDerivedValues,\n\tFacts,\n\tFactsStore,\n\tSchema,\n} from \"./types.js\";\n\n// ============================================================================\n// Derivations Manager\n// ============================================================================\n\nexport interface DerivationsManager<S extends Schema, D extends DerivationsDef<S>> {\n\t/** Get a derived value (computes if stale) */\n\tget<K extends keyof D>(id: K): ReturnType<D[K]>;\n\t/** Check if a derivation is stale */\n\tisStale(id: keyof D): boolean;\n\t/** Invalidate derivations that depend on a fact key */\n\tinvalidate(factKey: string): void;\n\t/** Invalidate derivations for multiple fact keys, notifying listeners once at the end */\n\tinvalidateMany(factKeys: Iterable<string>): void;\n\t/** Invalidate all derivations */\n\tinvalidateAll(): void;\n\t/** Subscribe to derivation changes */\n\tsubscribe(ids: Array<keyof D>, listener: () => void): () => void;\n\t/** Get the proxy for composition */\n\tgetProxy(): DerivedValues<S, D>;\n\t/** Get dependencies for a derivation */\n\tgetDependencies(id: keyof D): Set<string>;\n\t/** Register new derivation definitions (for dynamic module registration) */\n\tregisterDefinitions(newDefs: DerivationsDef<S>): void;\n}\n\n/** Options for creating a derivations manager */\nexport interface CreateDerivationsOptions<S extends Schema, D extends DerivationsDef<S>> {\n\tdefinitions: D;\n\tfacts: Facts<S>;\n\tstore: FactsStore<S>;\n\t/** Callback when a derivation is computed */\n\tonCompute?: (id: string, value: unknown, deps: string[]) => void;\n\t/** Callback when a derivation is invalidated */\n\tonInvalidate?: (id: string) => void;\n\t/** Callback when a derivation errors */\n\tonError?: (id: string, error: unknown) => void;\n}\n\n/**\n * Create a manager for lazily-evaluated, auto-tracked derived values.\n *\n * Derivations are memoized computations that automatically track which facts\n * they read. When a tracked fact changes, the derivation is invalidated and\n * recomputed on next access. Derivations can depend on other derivations\n * (composition), and circular dependencies are detected at compute time.\n *\n * Notifications are deferred during invalidation so listeners always see\n * consistent state across multiple simultaneous fact changes.\n *\n * @param options - Derivation definitions, facts proxy, store, and optional lifecycle callbacks\n * @returns A `DerivationsManager` with get/invalidate/subscribe/getProxy methods\n */\nexport function createDerivationsManager<S extends Schema, D extends DerivationsDef<S>>(\n\toptions: CreateDerivationsOptions<S, D>,\n): DerivationsManager<S, D> {\n\tconst { definitions, facts, store: _store, onCompute, onInvalidate, onError } = options;\n\t// Note: _store is kept for API compatibility but invalidation is handled by the engine calling invalidate()\n\n\t// Internal state for each derivation\n\tconst states = new Map<string, DerivationState<unknown>>();\n\tconst listeners = new Map<string, Set<() => void>>();\n\n\t// Track which derivations depend on which fact keys\n\tconst factToDerivedDeps = new Map<string, Set<string>>();\n\t// Track which derivations depend on which other derivations\n\tconst derivedToDerivedDeps = new Map<string, Set<string>>();\n\n\t// Prototype pollution guard (same pattern as engine.ts, facts.ts, system.ts)\n\tconst BLOCKED_PROPS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n\t// Deferred notification: during invalidation, collect IDs to notify.\n\t// Listeners fire AFTER all invalidations complete so they see consistent state.\n\tlet invalidationDepth = 0;\n\tconst pendingNotifications = new Set<string>();\n\tlet isFlushing = false;\n\tconst MAX_FLUSH_ITERATIONS = 100;\n\n\t// The proxy for composition (derivations accessing other derivations)\n\tlet derivedProxy: DerivedValues<S, D>;\n\n\t/** Initialize state for a derivation */\n\tfunction initState(id: string): DerivationState<unknown> {\n\t\tconst def = definitions[id as keyof D];\n\t\tif (!def) {\n\t\t\tthrow new Error(`[Directive] Unknown derivation: ${id}`);\n\t\t}\n\n\t\tconst state: DerivationState<unknown> = {\n\t\t\tid,\n\t\t\tcompute: () => computeDerivation(id),\n\t\t\tcachedValue: undefined,\n\t\t\tdependencies: new Set(),\n\t\t\tisStale: true,\n\t\t\tisComputing: false,\n\t\t};\n\n\t\tstates.set(id, state);\n\t\treturn state;\n\t}\n\n\t/** Get or create state for a derivation */\n\tfunction getState(id: string): DerivationState<unknown> {\n\t\treturn states.get(id) ?? initState(id);\n\t}\n\n\t/** Compute a derivation and track its dependencies */\n\tfunction computeDerivation(id: string): unknown {\n\t\tconst state = getState(id);\n\t\tconst def = definitions[id as keyof D];\n\n\t\tif (!def) {\n\t\t\tthrow new Error(`[Directive] Unknown derivation: ${id}`);\n\t\t}\n\n\t\t// Circular dependency detection\n\t\tif (state.isComputing) {\n\t\t\tthrow new Error(`[Directive] Circular dependency detected in derivation: ${id}`);\n\t\t}\n\n\t\tstate.isComputing = true;\n\n\t\ttry {\n\t\t\t// Compute with tracking\n\t\t\tconst { value, deps } = withTracking(() => def(facts, derivedProxy));\n\n\t\t\t// Update state\n\t\t\tstate.cachedValue = value;\n\t\t\tstate.isStale = false;\n\n\t\t\t// Update dependency tracking\n\t\t\tupdateDependencies(id, deps);\n\n\t\t\t// Notify callback\n\t\t\tonCompute?.(id, value, [...deps]);\n\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tonError?.(id, error);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tstate.isComputing = false;\n\t\t}\n\t}\n\n\t/** Update dependency tracking for a derivation */\n\tfunction updateDependencies(id: string, newDeps: Set<string>): void {\n\t\tconst state = getState(id);\n\t\tconst oldDeps = state.dependencies;\n\n\t\t// Remove old fact dependencies\n\t\tfor (const dep of oldDeps) {\n\t\t\t// Check if it's a fact key or a derived key\n\t\t\tif (states.has(dep)) {\n\t\t\t\tconst depSet = derivedToDerivedDeps.get(dep);\n\t\t\t\tdepSet?.delete(id);\n\t\t\t\t// Clean up empty Sets to prevent memory leaks\n\t\t\t\tif (depSet && depSet.size === 0) {\n\t\t\t\t\tderivedToDerivedDeps.delete(dep);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst depSet = factToDerivedDeps.get(dep);\n\t\t\t\tdepSet?.delete(id);\n\t\t\t\t// Clean up empty Sets to prevent memory leaks\n\t\t\t\tif (depSet && depSet.size === 0) {\n\t\t\t\t\tfactToDerivedDeps.delete(dep);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Add new dependencies\n\t\tfor (const dep of newDeps) {\n\t\t\t// Check if it's a derivation or a fact\n\t\t\tif (definitions[dep as keyof D]) {\n\t\t\t\t// It's a derivation-to-derivation dependency\n\t\t\t\tif (!derivedToDerivedDeps.has(dep)) {\n\t\t\t\t\tderivedToDerivedDeps.set(dep, new Set());\n\t\t\t\t}\n\t\t\t\tderivedToDerivedDeps.get(dep)!.add(id);\n\t\t\t} else {\n\t\t\t\t// It's a fact dependency\n\t\t\t\tif (!factToDerivedDeps.has(dep)) {\n\t\t\t\t\tfactToDerivedDeps.set(dep, new Set());\n\t\t\t\t}\n\t\t\t\tfactToDerivedDeps.get(dep)!.add(id);\n\t\t\t}\n\t\t}\n\n\t\tstate.dependencies = newDeps;\n\t}\n\n\t/** Flush deferred notifications after all invalidations complete */\n\tfunction flushNotifications(): void {\n\t\tif (invalidationDepth > 0 || isFlushing) return;\n\n\t\tisFlushing = true;\n\t\ttry {\n\t\t\t// Loop until no more pending — listeners may trigger new invalidations\n\t\t\t// that add to pendingNotifications via re-entrant invalidate() calls.\n\t\t\tlet iterations = 0;\n\t\t\twhile (pendingNotifications.size > 0) {\n\t\t\t\tif (++iterations > MAX_FLUSH_ITERATIONS) {\n\t\t\t\t\tconst remaining = [...pendingNotifications];\n\t\t\t\t\tpendingNotifications.clear();\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Infinite derivation notification loop detected after ${MAX_FLUSH_ITERATIONS} iterations. ` +\n\t\t\t\t\t\t\t`Remaining: ${remaining.join(\", \")}. ` +\n\t\t\t\t\t\t\t`This usually means a derivation listener is mutating facts that re-trigger the same derivation.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst ids = [...pendingNotifications];\n\t\t\t\tpendingNotifications.clear();\n\n\t\t\t\tfor (const id of ids) {\n\t\t\t\t\tlisteners.get(id)?.forEach((listener) => listener());\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tisFlushing = false;\n\t\t}\n\t}\n\n\t/** Invalidate a derivation and its dependents */\n\tfunction invalidateDerivation(id: string, visited = new Set<string>()): void {\n\t\tif (visited.has(id)) return;\n\t\tvisited.add(id);\n\n\t\tconst state = states.get(id);\n\t\tif (!state || state.isStale) return;\n\n\t\tstate.isStale = true;\n\t\tonInvalidate?.(id);\n\n\t\t// Defer listener notification until all invalidations complete.\n\t\t// This prevents listeners from observing partially-stale state and\n\t\t// avoids infinite loops from Set mutation during iteration (listeners\n\t\t// recompute derivations → updateDependencies → modify dep Sets).\n\t\tpendingNotifications.add(id);\n\n\t\t// Invalidate derivations that depend on this one\n\t\tconst dependents = derivedToDerivedDeps.get(id);\n\t\tif (dependents) {\n\t\t\tfor (const dependent of dependents) {\n\t\t\t\tinvalidateDerivation(dependent, visited);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create the proxy for composition\n\tderivedProxy = new Proxy({} as DerivedValues<S, D>, {\n\t\tget(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\n\t\t\t// Track this derivation access so the consuming derivation\n\t\t\t// records a dependency on it (enables composition invalidation)\n\t\t\ttrackAccess(prop);\n\n\t\t\tconst state = getState(prop);\n\n\t\t\t// Recompute if stale\n\t\t\tif (state.isStale) {\n\t\t\t\tcomputeDerivation(prop);\n\t\t\t}\n\n\t\t\treturn state.cachedValue;\n\t\t},\n\t});\n\n\t// Note: Fact change invalidation is handled by the engine calling invalidate()\n\n\tconst manager: DerivationsManager<S, D> = {\n\t\tget<K extends keyof D>(id: K): ReturnType<D[K]> {\n\t\t\tconst state = getState(id as string);\n\n\t\t\tif (state.isStale) {\n\t\t\t\tcomputeDerivation(id as string);\n\t\t\t}\n\n\t\t\treturn state.cachedValue as ReturnType<D[K]>;\n\t\t},\n\n\t\tisStale(id: keyof D): boolean {\n\t\t\tconst state = states.get(id as string);\n\t\t\treturn state?.isStale ?? true;\n\t\t},\n\n\t\tinvalidate(factKey: string): void {\n\t\t\tconst dependents = factToDerivedDeps.get(factKey);\n\t\t\tif (!dependents) return;\n\n\t\t\tinvalidationDepth++;\n\t\t\ttry {\n\t\t\t\tfor (const id of dependents) {\n\t\t\t\t\tinvalidateDerivation(id);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tinvalidationDepth--;\n\t\t\t\tflushNotifications();\n\t\t\t}\n\t\t},\n\n\t\tinvalidateMany(factKeys: Iterable<string>): void {\n\t\t\tinvalidationDepth++;\n\t\t\ttry {\n\t\t\t\tfor (const factKey of factKeys) {\n\t\t\t\t\tconst dependents = factToDerivedDeps.get(factKey);\n\t\t\t\t\tif (!dependents) continue;\n\t\t\t\t\tfor (const id of dependents) {\n\t\t\t\t\t\tinvalidateDerivation(id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tinvalidationDepth--;\n\t\t\t\tflushNotifications();\n\t\t\t}\n\t\t},\n\n\t\tinvalidateAll(): void {\n\t\t\tinvalidationDepth++;\n\t\t\ttry {\n\t\t\t\tfor (const state of states.values()) {\n\t\t\t\t\tif (!state.isStale) {\n\t\t\t\t\t\tstate.isStale = true;\n\t\t\t\t\t\tpendingNotifications.add(state.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tinvalidationDepth--;\n\t\t\t\tflushNotifications();\n\t\t\t}\n\t\t},\n\n\t\tsubscribe(ids: Array<keyof D>, listener: () => void): () => void {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst idStr = id as string;\n\t\t\t\tif (!listeners.has(idStr)) {\n\t\t\t\t\tlisteners.set(idStr, new Set());\n\t\t\t\t}\n\t\t\t\tlisteners.get(idStr)!.add(listener);\n\t\t\t}\n\n\t\t\treturn () => {\n\t\t\t\tfor (const id of ids) {\n\t\t\t\t\tconst idStr = id as string;\n\t\t\t\t\tconst listenerSet = listeners.get(idStr);\n\t\t\t\t\tlistenerSet?.delete(listener);\n\t\t\t\t\t// Clean up empty Sets to prevent memory leaks\n\t\t\t\t\tif (listenerSet && listenerSet.size === 0) {\n\t\t\t\t\t\tlisteners.delete(idStr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\n\t\tgetProxy(): DerivedValues<S, D> {\n\t\t\treturn derivedProxy;\n\t\t},\n\n\t\tgetDependencies(id: keyof D): Set<string> {\n\t\t\treturn getState(id as string).dependencies;\n\t\t},\n\n\t\tregisterDefinitions(newDefs: DerivationsDef<S>): void {\n\t\t\tfor (const [key, fn] of Object.entries(newDefs)) {\n\t\t\t\t(definitions as Record<string, unknown>)[key] = fn;\n\t\t\t\tinitState(key);\n\t\t\t}\n\t\t},\n\t};\n\n\treturn manager;\n}\n","/**\n * Effects - Fire-and-forget side effects\n *\n * Features:\n * - Separate from requirement resolution\n * - Error isolation (never breaks reconciliation)\n * - Optional explicit dependencies for optimization\n * - Runs after facts stabilize\n *\n * IMPORTANT: Auto-tracking limitations\n * ------------------------------------\n * When using auto-tracking (no explicit `deps`), only SYNCHRONOUS fact accesses\n * are tracked. If your effect reads facts after an `await`, those reads are NOT\n * tracked and won't trigger the effect on future changes.\n *\n * For async effects, always use explicit `deps`:\n * @example\n * ```typescript\n * effects: {\n * // BAD: fetchData is async, facts.userId read after await won't be tracked\n * badEffect: {\n * run: async (facts) => {\n * await someAsyncOp();\n * console.log(facts.userId); // NOT tracked!\n * },\n * },\n * // GOOD: explicit deps for async effects\n * goodEffect: {\n * deps: [\"userId\"],\n * run: async (facts) => {\n * await someAsyncOp();\n * console.log(facts.userId); // Works because we declared the dep\n * },\n * },\n * }\n * ```\n */\n\nimport { withTracking } from \"./tracking.js\";\nimport type {\n\tEffectsDef,\n\tFacts,\n\tFactsSnapshot,\n\tFactsStore,\n\tSchema,\n} from \"./types.js\";\n\n// ============================================================================\n// Effects Manager\n// ============================================================================\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface EffectsManager<_S extends Schema = Schema> {\n\t/** Run all effects that should trigger based on changes */\n\trunEffects(changedKeys: Set<string>): Promise<void>;\n\t/** Run all effects unconditionally */\n\trunAll(): Promise<void>;\n\t/** Disable an effect */\n\tdisable(id: string): void;\n\t/** Enable an effect */\n\tenable(id: string): void;\n\t/** Check if an effect is enabled */\n\tisEnabled(id: string): boolean;\n\t/** Run all stored cleanup functions (called on system stop/destroy) */\n\tcleanupAll(): void;\n\t/** Register new effect definitions (for dynamic module registration) */\n\tregisterDefinitions(newDefs: EffectsDef<Schema>): void;\n}\n\n/** Internal effect state */\ninterface EffectState {\n\tid: string;\n\tenabled: boolean;\n\thasExplicitDeps: boolean; // true = user-provided deps (fixed), false = auto-tracked (re-track every run)\n\tdependencies: Set<string> | null; // null = not yet tracked\n\tlastSnapshot: FactsSnapshot<Schema> | null;\n\tcleanup: (() => void) | null; // cleanup function returned by last run()\n}\n\n/** Options for creating an effects manager */\nexport interface CreateEffectsOptions<S extends Schema> {\n\tdefinitions: EffectsDef<S>;\n\tfacts: Facts<S>;\n\tstore: FactsStore<S>;\n\t/** Callback when an effect runs */\n\tonRun?: (id: string) => void;\n\t/** Callback when an effect errors */\n\tonError?: (id: string, error: unknown) => void;\n}\n\n/**\n * Create a manager for fire-and-forget side effects that run after facts\n * stabilize.\n *\n * Effects support auto-tracked dependencies (re-tracked on every run to\n * capture conditional reads) or explicit `deps` arrays. Each effect can\n * return a cleanup function that runs before the next execution or on\n * system stop. Errors in effects are isolated and never break the\n * reconciliation loop.\n *\n * @param options - Effect definitions, facts proxy, store, and optional lifecycle callbacks\n * @returns An `EffectsManager` with runEffects/runAll/enable/disable/cleanupAll methods\n */\nexport function createEffectsManager<S extends Schema>(\n\toptions: CreateEffectsOptions<S>,\n): EffectsManager<S> {\n\tconst { definitions, facts, store, onRun, onError } = options;\n\n\t// Internal state for each effect\n\tconst states = new Map<string, EffectState>();\n\n\t// Previous facts snapshot for comparison\n\tlet previousSnapshot: FactsSnapshot<Schema> | null = null;\n\n\t// Track whether cleanupAll has been called (system stopped/destroyed).\n\t// If an async effect resolves after stop, its cleanup is invoked immediately.\n\tlet stopped = false;\n\n\t/** Initialize state for an effect */\n\tfunction initState(id: string): EffectState {\n\t\tconst def = definitions[id];\n\t\tif (!def) {\n\t\t\tthrow new Error(`[Directive] Unknown effect: ${id}`);\n\t\t}\n\n\t\tconst state: EffectState = {\n\t\t\tid,\n\t\t\tenabled: true,\n\t\t\thasExplicitDeps: !!def.deps,\n\t\t\tdependencies: def.deps ? new Set(def.deps as string[]) : null,\n\t\t\tlastSnapshot: null,\n\t\t\tcleanup: null,\n\t\t};\n\n\t\tstates.set(id, state);\n\t\treturn state;\n\t}\n\n\t/** Get or create state for an effect */\n\tfunction getState(id: string): EffectState {\n\t\treturn states.get(id) ?? initState(id);\n\t}\n\n\t/** Create a snapshot of current facts */\n\tfunction createSnapshot(): FactsSnapshot<Schema> {\n\t\treturn facts.$snapshot() as FactsSnapshot<Schema>;\n\t}\n\n\t/** Check if an effect should run based on changed keys */\n\tfunction shouldRun(id: string, changedKeys: Set<string>): boolean {\n\t\tconst state = getState(id);\n\t\tif (!state.enabled) return false;\n\n\t\t// If effect has tracked deps (explicit or auto-tracked), check if any changed\n\t\tif (state.dependencies) {\n\t\t\tfor (const dep of state.dependencies) {\n\t\t\t\tif (changedKeys.has(dep)) return true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\t// No deps yet (first run or auto-tracked with no reads) = run on any change\n\t\treturn true;\n\t}\n\n\t/** Run cleanup for a single effect (safe — catches errors) */\n\tfunction runCleanup(state: EffectState): void {\n\t\tif (state.cleanup) {\n\t\t\ttry {\n\t\t\t\tstate.cleanup();\n\t\t\t} catch (error) {\n\t\t\t\tonError?.(state.id, error);\n\t\t\t\tconsole.error(`[Directive] Effect \"${state.id}\" cleanup threw an error:`, error);\n\t\t\t}\n\t\t\tstate.cleanup = null;\n\t\t}\n\t}\n\n\t/** Store a cleanup function if the effect returned one */\n\tfunction storeCleanup(state: EffectState, result: unknown): void {\n\t\tif (typeof result === \"function\") {\n\t\t\tif (stopped) {\n\t\t\t\t// System already stopped — invoke cleanup immediately so it's not lost\n\t\t\t\ttry {\n\t\t\t\t\t(result as () => void)();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tonError?.(state.id, error);\n\t\t\t\t\tconsole.error(`[Directive] Effect \"${state.id}\" cleanup threw an error:`, error);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstate.cleanup = result as () => void;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Run a single effect */\n\tasync function runEffect(id: string): Promise<void> {\n\t\tconst state = getState(id);\n\t\tconst def = definitions[id];\n\n\t\tif (!state.enabled || !def) return;\n\n\t\t// Run previous cleanup before re-running\n\t\trunCleanup(state);\n\n\t\tonRun?.(id);\n\n\t\ttry {\n\t\t\tif (!state.hasExplicitDeps) {\n\t\t\t\t// Auto-tracked: re-track dependencies on EVERY run so conditional\n\t\t\t\t// reads are picked up (fixes frozen deps after first run)\n\t\t\t\tlet trackedDeps: Set<string> | null = null;\n\t\t\t\tlet effectPromise: unknown;\n\t\t\t\tconst trackingResult = withTracking(() => {\n\t\t\t\t\tstore.batch(() => {\n\t\t\t\t\t\teffectPromise = def.run(facts, previousSnapshot as FactsSnapshot<S> | null);\n\t\t\t\t\t});\n\t\t\t\t\treturn effectPromise;\n\t\t\t\t});\n\t\t\t\ttrackedDeps = trackingResult.deps;\n\n\t\t\t\t// If the effect is async, wait for it and capture cleanup\n\t\t\t\tlet result = trackingResult.value;\n\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\tresult = await result;\n\t\t\t\t}\n\t\t\t\tstoreCleanup(state, result);\n\n\t\t\t\t// Update tracked dependencies (always replace to catch new conditional reads)\n\t\t\t\tstate.dependencies = trackedDeps.size > 0 ? trackedDeps : null;\n\t\t\t} else {\n\t\t\t\t// Has explicit deps, batch synchronous mutations and run\n\t\t\t\tlet effectPromise: unknown;\n\t\t\t\tstore.batch(() => {\n\t\t\t\t\teffectPromise = def.run(facts, previousSnapshot as FactsSnapshot<S> | null);\n\t\t\t\t});\n\t\t\t\tif (effectPromise instanceof Promise) {\n\t\t\t\t\tconst result = await effectPromise;\n\t\t\t\t\tstoreCleanup(state, result);\n\t\t\t\t} else {\n\t\t\t\t\tstoreCleanup(state, effectPromise);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Effects are fire-and-forget - errors are reported but don't propagate\n\t\t\tonError?.(id, error);\n\t\t\tconsole.error(`[Directive] Effect \"${id}\" threw an error:`, error);\n\t\t}\n\t}\n\n\t// Initialize all effect states\n\tfor (const id of Object.keys(definitions)) {\n\t\tinitState(id);\n\t}\n\n\tconst manager: EffectsManager<S> = {\n\t\tasync runEffects(changedKeys: Set<string>): Promise<void> {\n\t\t\tconst effectsToRun: string[] = [];\n\n\t\t\tfor (const id of Object.keys(definitions)) {\n\t\t\t\tif (shouldRun(id, changedKeys)) {\n\t\t\t\t\teffectsToRun.push(id);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Run effects in parallel (they're independent)\n\t\t\tawait Promise.all(effectsToRun.map(runEffect));\n\n\t\t\t// Update previous snapshot\n\t\t\tpreviousSnapshot = createSnapshot();\n\t\t},\n\n\t\tasync runAll(): Promise<void> {\n\t\t\tconst effectIds = Object.keys(definitions);\n\t\t\tawait Promise.all(\n\t\t\t\teffectIds.map((id) => {\n\t\t\t\t\tconst state = getState(id);\n\t\t\t\t\tif (state.enabled) {\n\t\t\t\t\t\treturn runEffect(id);\n\t\t\t\t\t}\n\t\t\t\t\treturn Promise.resolve();\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\t// Update previous snapshot\n\t\t\tpreviousSnapshot = createSnapshot();\n\t\t},\n\n\t\tdisable(id: string): void {\n\t\t\tconst state = getState(id);\n\t\t\tstate.enabled = false;\n\t\t},\n\n\t\tenable(id: string): void {\n\t\t\tconst state = getState(id);\n\t\t\tstate.enabled = true;\n\t\t},\n\n\t\tisEnabled(id: string): boolean {\n\t\t\treturn getState(id).enabled;\n\t\t},\n\n\t\tcleanupAll(): void {\n\t\t\tstopped = true;\n\t\t\tfor (const state of states.values()) {\n\t\t\t\trunCleanup(state);\n\t\t\t}\n\t\t},\n\n\t\tregisterDefinitions(newDefs: EffectsDef<S>): void {\n\t\t\tfor (const [key, def] of Object.entries(newDefs)) {\n\t\t\t\t(definitions as Record<string, unknown>)[key] = def;\n\t\t\t\tinitState(key);\n\t\t\t}\n\t\t},\n\t};\n\n\treturn manager;\n}\n","/**\n * Error Boundaries - Configurable error handling and recovery\n *\n * Features:\n * - Catch errors in constraints/resolvers/effects/derivations\n * - Configurable recovery strategies (skip, retry, retry-later, disable, throw)\n * - Circuit breaker pattern for automatic failure protection\n * - Error reporting to plugins\n */\n\nimport {\n\tDirectiveError,\n\ttype ErrorBoundaryConfig,\n\ttype ErrorSource,\n\ttype RecoveryStrategy,\n\ttype RetryLaterConfig,\n} from \"./types.js\";\n\n// ============================================================================\n// Retry-Later Queue\n// ============================================================================\n\n/**\n * Pending retry entry.\n */\nexport interface PendingRetry {\n\tsource: ErrorSource;\n\tsourceId: string;\n\tcontext: unknown;\n\tattempt: number;\n\tnextRetryTime: number;\n\tcallback?: () => void;\n}\n\n/**\n * Create a manager for deferred retry scheduling with exponential backoff.\n *\n * Retries are stored in a Map keyed by source ID. Each retry tracks its\n * attempt number and next retry time. When `processDueRetries()` is called\n * (typically during reconciliation), entries whose time has elapsed are\n * returned and removed from the queue.\n *\n * @param config - Backoff configuration: `delayMs`, `maxRetries`, `backoffMultiplier`, `maxDelayMs`\n * @returns A manager with `scheduleRetry`, `getPendingRetries`, `processDueRetries`, `cancelRetry`, and `clearAll` methods\n */\nexport function createRetryLaterManager(config: RetryLaterConfig = {}): {\n\t/** Schedule a retry */\n\tscheduleRetry: (\n\t\tsource: ErrorSource,\n\t\tsourceId: string,\n\t\tcontext: unknown,\n\t\tattempt: number,\n\t\tcallback?: () => void,\n\t) => PendingRetry | null;\n\t/** Get pending retries */\n\tgetPendingRetries: () => PendingRetry[];\n\t/** Process due retries */\n\tprocessDueRetries: () => PendingRetry[];\n\t/** Cancel a retry */\n\tcancelRetry: (sourceId: string) => void;\n\t/** Clear all pending retries */\n\tclearAll: () => void;\n} {\n\tconst {\n\t\tdelayMs = 1000,\n\t\tmaxRetries = 3,\n\t\tbackoffMultiplier = 2,\n\t\tmaxDelayMs = 30000,\n\t} = config;\n\n\tconst pendingRetries: Map<string, PendingRetry> = new Map();\n\n\tfunction calculateDelay(attempt: number): number {\n\t\tconst delay = delayMs * Math.pow(backoffMultiplier, attempt - 1);\n\t\treturn Math.min(delay, maxDelayMs);\n\t}\n\n\treturn {\n\t\tscheduleRetry(\n\t\t\tsource: ErrorSource,\n\t\t\tsourceId: string,\n\t\t\tcontext: unknown,\n\t\t\tattempt: number,\n\t\t\tcallback?: () => void,\n\t\t): PendingRetry | null {\n\t\t\t// Check if max retries exceeded\n\t\t\tif (attempt > maxRetries) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst delay = calculateDelay(attempt);\n\t\t\tconst entry: PendingRetry = {\n\t\t\t\tsource,\n\t\t\t\tsourceId,\n\t\t\t\tcontext,\n\t\t\t\tattempt,\n\t\t\t\tnextRetryTime: Date.now() + delay,\n\t\t\t\tcallback,\n\t\t\t};\n\n\t\t\tpendingRetries.set(sourceId, entry);\n\t\t\treturn entry;\n\t\t},\n\n\t\tgetPendingRetries(): PendingRetry[] {\n\t\t\treturn Array.from(pendingRetries.values());\n\t\t},\n\n\t\tprocessDueRetries(): PendingRetry[] {\n\t\t\tconst now = Date.now();\n\t\t\tconst dueRetries: PendingRetry[] = [];\n\n\t\t\tfor (const [sourceId, entry] of pendingRetries) {\n\t\t\t\tif (entry.nextRetryTime <= now) {\n\t\t\t\t\tdueRetries.push(entry);\n\t\t\t\t\tpendingRetries.delete(sourceId);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn dueRetries;\n\t\t},\n\n\t\tcancelRetry(sourceId: string): void {\n\t\t\tpendingRetries.delete(sourceId);\n\t\t},\n\n\t\tclearAll(): void {\n\t\t\tpendingRetries.clear();\n\t\t},\n\t};\n}\n\n// ============================================================================\n// Error Boundary Manager\n// ============================================================================\n\nexport interface ErrorBoundaryManager {\n\t/** Handle an error from a specific source */\n\thandleError(source: ErrorSource, sourceId: string, error: unknown, context?: unknown): RecoveryStrategy;\n\t/** Get the last error */\n\tgetLastError(): DirectiveError | null;\n\t/** Get all errors */\n\tgetAllErrors(): DirectiveError[];\n\t/** Clear all errors */\n\tclearErrors(): void;\n\t/** Get retry-later manager */\n\tgetRetryLaterManager(): ReturnType<typeof createRetryLaterManager>;\n\t/** Process due retries (call periodically or on reconcile) */\n\tprocessDueRetries(): PendingRetry[];\n\t/** Clear retry attempts for a source ID (call on success) */\n\tclearRetryAttempts(sourceId: string): void;\n}\n\n/** Options for creating an error boundary manager */\nexport interface CreateErrorBoundaryOptions {\n\tconfig?: ErrorBoundaryConfig;\n\t/** Callback when an error occurs */\n\tonError?: (error: DirectiveError) => void;\n\t/** Callback when recovery is attempted */\n\tonRecovery?: (error: DirectiveError, strategy: RecoveryStrategy) => void;\n}\n\n/** Default recovery strategies by source */\nconst DEFAULT_STRATEGIES: Record<ErrorSource, RecoveryStrategy> = {\n\tconstraint: \"skip\",\n\tresolver: \"skip\",\n\teffect: \"skip\",\n\tderivation: \"skip\",\n\tsystem: \"throw\",\n};\n\n/**\n * Create a manager that handles errors from constraints, resolvers, effects,\n * and derivations with configurable per-source recovery strategies.\n *\n * Supported strategies: `\"skip\"` (ignore), `\"retry\"` (immediate),\n * `\"retry-later\"` (deferred with backoff), `\"disable\"` (turn off source),\n * and `\"throw\"` (re-throw). Recent errors are kept in a ring buffer\n * (last 100) for inspection. The retry-later strategy delegates to an\n * internal {@link createRetryLaterManager}.\n *\n * @param options - Error boundary configuration, plus `onError` and `onRecovery` callbacks for plugin integration\n * @returns An `ErrorBoundaryManager` with handleError/getLastError/getAllErrors/clearErrors/processDueRetries methods\n *\n * @example\n * ```ts\n * const boundary = createErrorBoundaryManager({\n * config: {\n * onResolverError: \"retry-later\",\n * onEffectError: \"skip\",\n * retryLater: { maxRetries: 5, delayMs: 500 },\n * },\n * onError: (err) => console.error(err.source, err.message),\n * });\n *\n * const strategy = boundary.handleError(\"resolver\", \"fetchUser\", new Error(\"timeout\"));\n * // strategy === \"retry-later\"\n * ```\n */\nexport function createErrorBoundaryManager(\n\toptions: CreateErrorBoundaryOptions = {},\n): ErrorBoundaryManager {\n\tconst { config = {}, onError, onRecovery } = options;\n\n\t// Store errors for inspection\n\tconst errors: DirectiveError[] = [];\n\tconst maxErrors = 100; // Keep last 100 errors\n\n\t// Retry-later manager\n\tconst retryLaterManager = createRetryLaterManager(config.retryLater);\n\n\t// Track retry attempts per source ID\n\tconst retryAttempts = new Map<string, number>();\n\n\t/** Convert unknown error to DirectiveError */\n\tfunction toDirectiveError(\n\t\tsource: ErrorSource,\n\t\tsourceId: string,\n\t\terror: unknown,\n\t\tcontext?: unknown,\n\t): DirectiveError {\n\t\tif (error instanceof DirectiveError) {\n\t\t\treturn error;\n\t\t}\n\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst recoverable = source !== \"system\";\n\n\t\treturn new DirectiveError(message, source, sourceId, context, recoverable);\n\t}\n\n\t/** Get recovery strategy for a source */\n\tfunction getStrategy(source: ErrorSource, sourceId: string, error: Error): RecoveryStrategy {\n\t\t// Get configured handler\n\t\tconst handler = (() => {\n\t\t\tswitch (source) {\n\t\t\t\tcase \"constraint\":\n\t\t\t\t\treturn config.onConstraintError;\n\t\t\t\tcase \"resolver\":\n\t\t\t\t\treturn config.onResolverError;\n\t\t\t\tcase \"effect\":\n\t\t\t\t\treturn config.onEffectError;\n\t\t\t\tcase \"derivation\":\n\t\t\t\t\treturn config.onDerivationError;\n\t\t\t\tdefault:\n\t\t\t\t\treturn undefined;\n\t\t\t}\n\t\t})();\n\n\t\t// If handler is a function, call it and return skip\n\t\tif (typeof handler === \"function\") {\n\t\t\ttry {\n\t\t\t\thandler(error, sourceId);\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(\"[Directive] Error in error handler callback:\", e);\n\t\t\t}\n\t\t\treturn \"skip\";\n\t\t}\n\n\t\t// If handler is a strategy string, return it\n\t\tif (typeof handler === \"string\") {\n\t\t\treturn handler;\n\t\t}\n\n\t\t// Return default strategy\n\t\treturn DEFAULT_STRATEGIES[source];\n\t}\n\n\tconst manager: ErrorBoundaryManager = {\n\t\thandleError(\n\t\t\tsource: ErrorSource,\n\t\t\tsourceId: string,\n\t\t\terror: unknown,\n\t\t\tcontext?: unknown,\n\t\t): RecoveryStrategy {\n\t\t\tconst directiveError = toDirectiveError(source, sourceId, error, context);\n\n\t\t\t// Store error\n\t\t\terrors.push(directiveError);\n\t\t\tif (errors.length > maxErrors) {\n\t\t\t\terrors.shift();\n\t\t\t}\n\n\t\t\t// Notify callbacks (wrapped to prevent bypassing recovery)\n\t\t\ttry { onError?.(directiveError); } catch (e) { console.error(\"[Directive] Error in onError callback:\", e); }\n\t\t\ttry { config.onError?.(directiveError); } catch (e) { console.error(\"[Directive] Error in config.onError callback:\", e); }\n\n\t\t\t// Get recovery strategy\n\t\t\tlet strategy = getStrategy(\n\t\t\t\tsource,\n\t\t\t\tsourceId,\n\t\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t\t);\n\n\t\t\t// Handle retry-later strategy\n\t\t\tif (strategy === \"retry-later\") {\n\t\t\t\tconst attempt = (retryAttempts.get(sourceId) ?? 0) + 1;\n\t\t\t\tretryAttempts.set(sourceId, attempt);\n\n\t\t\t\tconst scheduled = retryLaterManager.scheduleRetry(\n\t\t\t\t\tsource,\n\t\t\t\t\tsourceId,\n\t\t\t\t\tcontext,\n\t\t\t\t\tattempt,\n\t\t\t\t);\n\n\t\t\t\tif (!scheduled) {\n\t\t\t\t\t// Max retries exceeded, fall back to skip\n\t\t\t\t\tstrategy = \"skip\";\n\t\t\t\t\tretryAttempts.delete(sourceId);\n\n\t\t\t\t\tif (typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\") {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[Directive] ${source} \"${sourceId}\" exceeded max retry-later attempts. Skipping.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Notify recovery callback\n\t\t\ttry { onRecovery?.(directiveError, strategy); } catch (e) { console.error(\"[Directive] Error in onRecovery callback:\", e); }\n\n\t\t\t// If strategy is throw, re-throw the error\n\t\t\tif (strategy === \"throw\") {\n\t\t\t\tthrow directiveError;\n\t\t\t}\n\n\t\t\treturn strategy;\n\t\t},\n\n\t\tgetLastError(): DirectiveError | null {\n\t\t\treturn errors[errors.length - 1] ?? null;\n\t\t},\n\n\t\tgetAllErrors(): DirectiveError[] {\n\t\t\treturn [...errors];\n\t\t},\n\n\t\tclearErrors(): void {\n\t\t\terrors.length = 0;\n\t\t},\n\n\t\tgetRetryLaterManager() {\n\t\t\treturn retryLaterManager;\n\t\t},\n\n\t\tprocessDueRetries(): PendingRetry[] {\n\t\t\treturn retryLaterManager.processDueRetries();\n\t\t},\n\n\t\tclearRetryAttempts(sourceId: string): void {\n\t\t\tretryAttempts.delete(sourceId);\n\t\t\tretryLaterManager.cancelRetry(sourceId);\n\t\t},\n\t};\n\n\treturn manager;\n}\n","/**\n * Plugin Architecture - Extensible middleware for Directive\n *\n * Features:\n * - Lifecycle hooks for all engine events\n * - Multiple plugins can be composed\n * - Plugins execute in registration order\n */\n\nimport type {\n\tFactChange,\n\tFactsSnapshot,\n\tPlugin,\n\tReconcileResult,\n\tRecoveryStrategy,\n\tRequirementWithId,\n\tSchema,\n\tSnapshot,\n\tSystem,\n} from \"./types.js\";\nimport { DirectiveError } from \"./types.js\";\n\n// ============================================================================\n// Plugin Manager\n// ============================================================================\n\n// Note: PluginManager uses Schema (flat) internally because the engine works with flat schemas.\n// The public API uses ModuleSchema (consolidated), and the conversion happens in createSystem.\n// biome-ignore lint/suspicious/noExplicitAny: Internal type - plugins are schema-agnostic at runtime\nexport interface PluginManager<_S extends Schema = any> {\n\t/** Register a plugin */\n\t// biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n\tregister(plugin: Plugin<any>): void;\n\t/** Unregister a plugin by name */\n\tunregister(name: string): void;\n\t/** Get all registered plugins */\n\t// biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n\tgetPlugins(): Plugin<any>[];\n\n\t// Lifecycle hooks\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies between internal/public API\n\temitInit(system: System<any>): Promise<void>;\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies between internal/public API\n\temitStart(system: System<any>): void;\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies between internal/public API\n\temitStop(system: System<any>): void;\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies between internal/public API\n\temitDestroy(system: System<any>): void;\n\n\t// Fact hooks\n\temitFactSet(key: string, value: unknown, prev: unknown): void;\n\temitFactDelete(key: string, prev: unknown): void;\n\temitFactsBatch(changes: FactChange[]): void;\n\n\t// Derivation hooks\n\temitDerivationCompute(id: string, value: unknown, deps: string[]): void;\n\temitDerivationInvalidate(id: string): void;\n\n\t// Reconciliation hooks\n\t// biome-ignore lint/suspicious/noExplicitAny: Schema type varies\n\temitReconcileStart(snapshot: FactsSnapshot<any>): void;\n\temitReconcileEnd(result: ReconcileResult): void;\n\n\t// Constraint hooks\n\temitConstraintEvaluate(id: string, active: boolean): void;\n\temitConstraintError(id: string, error: unknown): void;\n\n\t// Requirement hooks\n\temitRequirementCreated(req: RequirementWithId): void;\n\temitRequirementMet(req: RequirementWithId, byResolver: string): void;\n\temitRequirementCanceled(req: RequirementWithId): void;\n\n\t// Resolver hooks\n\temitResolverStart(resolver: string, req: RequirementWithId): void;\n\temitResolverComplete(resolver: string, req: RequirementWithId, duration: number): void;\n\temitResolverError(resolver: string, req: RequirementWithId, error: unknown): void;\n\temitResolverRetry(resolver: string, req: RequirementWithId, attempt: number): void;\n\temitResolverCancel(resolver: string, req: RequirementWithId): void;\n\n\t// Effect hooks\n\temitEffectRun(id: string): void;\n\temitEffectError(id: string, error: unknown): void;\n\n\t// Time-travel hooks\n\temitSnapshot(snapshot: Snapshot): void;\n\temitTimeTravel(from: number, to: number): void;\n\n\t// Error boundary hooks\n\temitError(error: DirectiveError): void;\n\temitErrorRecovery(error: DirectiveError, strategy: RecoveryStrategy): void;\n}\n\n/**\n * Create a manager that broadcasts lifecycle events to registered plugins.\n *\n * Plugins are called in registration order. All hook invocations are\n * wrapped in try-catch so a misbehaving plugin never breaks the engine.\n * Duplicate plugin names are detected and the older registration is\n * replaced with a warning.\n *\n * @returns A `PluginManager` with register/unregister/getPlugins and emit* methods for every lifecycle event\n */\n// biome-ignore lint/suspicious/noExplicitAny: Internal - schema type varies\nexport function createPluginManager<S extends Schema = any>(): PluginManager<S> {\n\t// biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n\tconst plugins: Plugin<any>[] = [];\n\n\t/** Safe call - wraps plugin hook calls to prevent errors from breaking the system */\n\tfunction safeCall<T>(fn: (() => T) | undefined): T | undefined {\n\t\tif (!fn) return undefined;\n\t\ttry {\n\t\t\treturn fn();\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[Directive] Plugin error:\", error);\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/** Safe async call */\n\tasync function safeCallAsync<T>(fn: (() => Promise<T>) | undefined): Promise<T | undefined> {\n\t\tif (!fn) return undefined;\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[Directive] Plugin error:\", error);\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tconst manager: PluginManager<S> = {\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n\t\tregister(plugin: Plugin<any>): void {\n\t\t\t// Check for duplicate names\n\t\t\tif (plugins.some((p) => p.name === plugin.name)) {\n\t\t\t\tconsole.warn(`[Directive] Plugin \"${plugin.name}\" is already registered, replacing...`);\n\t\t\t\tthis.unregister(plugin.name);\n\t\t\t}\n\t\t\tplugins.push(plugin);\n\t\t},\n\n\t\tunregister(name: string): void {\n\t\t\tconst index = plugins.findIndex((p) => p.name === name);\n\t\t\tif (index !== -1) {\n\t\t\t\tplugins.splice(index, 1);\n\t\t\t}\n\t\t},\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n\t\tgetPlugins(): Plugin<any>[] {\n\t\t\treturn [...plugins];\n\t\t},\n\n\t\t// Lifecycle hooks\n\t\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\t\tasync emitInit(system: System<any>): Promise<void> {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tawait safeCallAsync(() => plugin.onInit?.(system) as Promise<void>);\n\t\t\t}\n\t\t},\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\t\temitStart(system: System<any>): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onStart?.(system));\n\t\t\t}\n\t\t},\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\t\temitStop(system: System<any>): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onStop?.(system));\n\t\t\t}\n\t\t},\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\t\temitDestroy(system: System<any>): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onDestroy?.(system));\n\t\t\t}\n\t\t},\n\n\t\t// Fact hooks\n\t\temitFactSet(key: string, value: unknown, prev: unknown): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onFactSet?.(key, value, prev));\n\t\t\t}\n\t\t},\n\n\t\temitFactDelete(key: string, prev: unknown): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onFactDelete?.(key, prev));\n\t\t\t}\n\t\t},\n\n\t\temitFactsBatch(changes: FactChange[]): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onFactsBatch?.(changes));\n\t\t\t}\n\t\t},\n\n\t\t// Derivation hooks\n\t\temitDerivationCompute(id: string, value: unknown, deps: string[]): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onDerivationCompute?.(id, value, deps));\n\t\t\t}\n\t\t},\n\n\t\temitDerivationInvalidate(id: string): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onDerivationInvalidate?.(id));\n\t\t\t}\n\t\t},\n\n\t\t// Reconciliation hooks\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Schema type varies\n\t\temitReconcileStart(snapshot: FactsSnapshot<any>): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onReconcileStart?.(snapshot));\n\t\t\t}\n\t\t},\n\n\t\temitReconcileEnd(result: ReconcileResult): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onReconcileEnd?.(result));\n\t\t\t}\n\t\t},\n\n\t\t// Constraint hooks\n\t\temitConstraintEvaluate(id: string, active: boolean): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onConstraintEvaluate?.(id, active));\n\t\t\t}\n\t\t},\n\n\t\temitConstraintError(id: string, error: unknown): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onConstraintError?.(id, error));\n\t\t\t}\n\t\t},\n\n\t\t// Requirement hooks\n\t\temitRequirementCreated(req: RequirementWithId): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onRequirementCreated?.(req));\n\t\t\t}\n\t\t},\n\n\t\temitRequirementMet(req: RequirementWithId, byResolver: string): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onRequirementMet?.(req, byResolver));\n\t\t\t}\n\t\t},\n\n\t\temitRequirementCanceled(req: RequirementWithId): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onRequirementCanceled?.(req));\n\t\t\t}\n\t\t},\n\n\t\t// Resolver hooks\n\t\temitResolverStart(resolver: string, req: RequirementWithId): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onResolverStart?.(resolver, req));\n\t\t\t}\n\t\t},\n\n\t\temitResolverComplete(resolver: string, req: RequirementWithId, duration: number): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onResolverComplete?.(resolver, req, duration));\n\t\t\t}\n\t\t},\n\n\t\temitResolverError(resolver: string, req: RequirementWithId, error: unknown): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onResolverError?.(resolver, req, error));\n\t\t\t}\n\t\t},\n\n\t\temitResolverRetry(resolver: string, req: RequirementWithId, attempt: number): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onResolverRetry?.(resolver, req, attempt));\n\t\t\t}\n\t\t},\n\n\t\temitResolverCancel(resolver: string, req: RequirementWithId): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onResolverCancel?.(resolver, req));\n\t\t\t}\n\t\t},\n\n\t\t// Effect hooks\n\t\temitEffectRun(id: string): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onEffectRun?.(id));\n\t\t\t}\n\t\t},\n\n\t\temitEffectError(id: string, error: unknown): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onEffectError?.(id, error));\n\t\t\t}\n\t\t},\n\n\t\t// Time-travel hooks\n\t\temitSnapshot(snapshot: Snapshot): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onSnapshot?.(snapshot));\n\t\t\t}\n\t\t},\n\n\t\temitTimeTravel(from: number, to: number): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onTimeTravel?.(from, to));\n\t\t\t}\n\t\t},\n\n\t\t// Error boundary hooks\n\t\temitError(error: DirectiveError): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onError?.(error));\n\t\t\t}\n\t\t},\n\n\t\temitErrorRecovery(error: DirectiveError, strategy: RecoveryStrategy): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onErrorRecovery?.(error, strategy));\n\t\t\t}\n\t\t},\n\t};\n\n\treturn manager;\n}\n","/**\n * Resolvers - Capability-based handlers for requirements\n *\n * Features:\n * - Capability matching (handles predicate)\n * - Custom dedupe keys\n * - Retry policies with exponential backoff\n * - Batched resolution for similar requirements\n * - Cancellation via AbortController\n */\n\nimport type {\n\tBatchConfig,\n\tBatchResolveResults,\n\tFacts,\n\tFactsSnapshot,\n\tFactsStore,\n\tRequirement,\n\tRequirementWithId,\n\tResolverContext,\n\tResolversDef,\n\tResolverStatus,\n\tRetryPolicy,\n\tSchema,\n} from \"./types.js\";\nimport { withTimeout } from \"../utils/utils.js\";\n\n// ============================================================================\n// Resolvers Manager\n// ============================================================================\n\n/** Inflight resolver info */\nexport interface InflightInfo {\n\tid: string;\n\tresolverId: string;\n\tstartedAt: number;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ResolversManager<_S extends Schema> {\n\t/** Start resolving a requirement */\n\tresolve(req: RequirementWithId): void;\n\t/** Cancel a resolver by requirement ID */\n\tcancel(requirementId: string): void;\n\t/** Cancel all inflight resolvers */\n\tcancelAll(): void;\n\t/** Get status of a resolver by requirement ID */\n\tgetStatus(requirementId: string): ResolverStatus;\n\t/** Get all inflight requirement IDs */\n\tgetInflight(): string[];\n\t/** Get full info for all inflight resolvers */\n\tgetInflightInfo(): InflightInfo[];\n\t/** Check if a requirement is being resolved */\n\tisResolving(requirementId: string): boolean;\n\t/** Process batched requirements (called periodically) */\n\tprocessBatches(): void;\n\t/** Register new resolver definitions (for dynamic module registration) */\n\tregisterDefinitions(newDefs: ResolversDef<Schema>): void;\n}\n\n/** Internal resolver state */\ninterface ResolverState {\n\trequirementId: string;\n\tresolverId: string;\n\tcontroller: AbortController;\n\tstartedAt: number;\n\tattempt: number;\n\tstatus: ResolverStatus;\n\t/** Original requirement for proper cancel callback */\n\toriginalRequirement: RequirementWithId;\n}\n\n/** Batch state for batched resolvers */\ninterface BatchState {\n\tresolverId: string;\n\trequirements: RequirementWithId[];\n\ttimer: ReturnType<typeof setTimeout> | null;\n}\n\n/** Options for creating a resolvers manager */\nexport interface CreateResolversOptions<S extends Schema> {\n\tdefinitions: ResolversDef<S>;\n\tfacts: Facts<S>;\n\tstore: FactsStore<S>;\n\t/** Callback when a resolver starts */\n\tonStart?: (resolver: string, req: RequirementWithId) => void;\n\t/** Callback when a resolver completes */\n\tonComplete?: (resolver: string, req: RequirementWithId, duration: number) => void;\n\t/** Callback when a resolver errors */\n\tonError?: (resolver: string, req: RequirementWithId, error: unknown) => void;\n\t/** Callback when a resolver retries */\n\tonRetry?: (resolver: string, req: RequirementWithId, attempt: number) => void;\n\t/** Callback when a resolver is canceled */\n\tonCancel?: (resolver: string, req: RequirementWithId) => void;\n\t/** Callback when resolution cycle completes (for reconciliation) */\n\tonResolutionComplete?: () => void;\n}\n\n/** Default retry policy */\nconst DEFAULT_RETRY: RetryPolicy = {\n\tattempts: 1,\n\tbackoff: \"none\",\n\tinitialDelay: 100,\n\tmaxDelay: 30000,\n};\n\n/** Default batch config */\nconst DEFAULT_BATCH: BatchConfig = {\n\tenabled: false,\n\twindowMs: 50,\n};\n\n/**\n * Calculate delay for a retry attempt.\n */\nfunction calculateDelay(policy: RetryPolicy, attempt: number): number {\n\tconst { backoff, initialDelay = 100, maxDelay = 30000 } = policy;\n\n\tlet delay: number;\n\n\tswitch (backoff) {\n\t\tcase \"none\":\n\t\t\tdelay = initialDelay;\n\t\t\tbreak;\n\t\tcase \"linear\":\n\t\t\tdelay = initialDelay * attempt;\n\t\t\tbreak;\n\t\tcase \"exponential\":\n\t\t\tdelay = initialDelay * Math.pow(2, attempt - 1);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tdelay = initialDelay;\n\t}\n\n\t// Ensure delay is at least 1ms to prevent busy loops\n\treturn Math.max(1, Math.min(delay, maxDelay));\n}\n\n/**\n * Create a manager that fulfills requirements by matching them to resolver\n * handlers.\n *\n * Resolvers are matched by requirement type (string or predicate). Each\n * resolution runs with an `AbortController` for cancellation, configurable\n * retry policies (none/linear/exponential backoff), and optional batching\n * for grouping similar requirements. Duplicate in-flight requirements are\n * automatically deduplicated.\n *\n * @param options - Resolver definitions, facts proxy, store, and lifecycle callbacks (onStart/onComplete/onError/onRetry/onCancel/onResolutionComplete)\n * @returns A `ResolversManager` with resolve/cancel/cancelAll/getStatus/processBatches methods\n */\nexport function createResolversManager<S extends Schema>(\n\toptions: CreateResolversOptions<S>,\n): ResolversManager<S> {\n\tconst {\n\t\tdefinitions,\n\t\tfacts,\n\t\tstore,\n\t\tonStart,\n\t\tonComplete,\n\t\tonError,\n\t\tonRetry,\n\t\tonCancel,\n\t\tonResolutionComplete,\n\t} = options;\n\n\t// Validate resolver definitions\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tfor (const [id, def] of Object.entries(definitions)) {\n\t\t\tif (!def.resolve && !def.resolveBatch) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Resolver \"${id}\" must define either resolve() or resolveBatch(). ` +\n\t\t\t\t\t\t`Add one of these methods to handle requirements.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (def.batch?.enabled && !def.resolveBatch) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Resolver \"${id}\" has batch.enabled=true but no resolveBatch() method. ` +\n\t\t\t\t\t\t`Add resolveBatch() to handle batched requirements.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Active resolver states by requirement ID\n\tconst inflight = new Map<string, ResolverState>();\n\n\t// Completed/failed statuses (kept for inspection) - LRU cleanup\n\tconst statuses = new Map<string, ResolverStatus>();\n\tconst MAX_STATUSES = 1000; // Limit to prevent memory leak\n\n\t// Batch states by resolver ID\n\tconst batches = new Map<string, BatchState>();\n\n\t// Resolver index by requirement type for O(1) lookup (populated lazily)\n\t// Capped to prevent unbounded growth with dynamic requirement types (e.g., FETCH_USER_${id})\n\tconst resolversByType = new Map<string, string[]>();\n\tconst MAX_RESOLVER_CACHE = 1000;\n\n\t/** Cleanup old statuses to prevent memory leak */\n\tfunction cleanupStatuses(): void {\n\t\tif (statuses.size > MAX_STATUSES) {\n\t\t\t// Remove oldest entries (first inserted = first in iteration)\n\t\t\tconst entriesToRemove = statuses.size - MAX_STATUSES;\n\t\t\tconst iterator = statuses.keys();\n\t\t\tfor (let i = 0; i < entriesToRemove; i++) {\n\t\t\t\tconst key = iterator.next().value;\n\t\t\t\tif (key) statuses.delete(key);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Type guard for resolver with string `requirement` property */\n\tfunction hasStringRequirement(\n\t\tdef: unknown,\n\t): def is { requirement: string } {\n\t\treturn (\n\t\t\ttypeof def === \"object\" &&\n\t\t\tdef !== null &&\n\t\t\t\"requirement\" in def &&\n\t\t\ttypeof (def as { requirement: unknown }).requirement === \"string\"\n\t\t);\n\t}\n\n\t/** Type guard for resolver with function `requirement` property */\n\tfunction hasFunctionRequirement(\n\t\tdef: unknown,\n\t): def is { requirement: (req: Requirement) => boolean } {\n\t\treturn (\n\t\t\ttypeof def === \"object\" &&\n\t\t\tdef !== null &&\n\t\t\t\"requirement\" in def &&\n\t\t\ttypeof (def as { requirement: unknown }).requirement === \"function\"\n\t\t);\n\t}\n\n\t/**\n\t * Check if a resolver handles a requirement.\n\t * Supports:\n\t * - `requirement: \"TYPE\"` - string matching\n\t * - `requirement: (req) => req is T` - function type guard\n\t */\n\tfunction resolverHandles(def: ResolversDef<S>[string], req: Requirement): boolean {\n\t\t// Check string-based `requirement`\n\t\tif (hasStringRequirement(def)) {\n\t\t\treturn req.type === def.requirement;\n\t\t}\n\n\t\t// Check function-based `requirement` (type guard)\n\t\tif (hasFunctionRequirement(def)) {\n\t\t\treturn def.requirement(req);\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/** Find a resolver that handles a requirement */\n\tfunction findResolver(req: Requirement): string | null {\n\t\t// Check cache first for this requirement type\n\t\tconst reqType = req.type;\n\t\tconst cached = resolversByType.get(reqType);\n\t\tif (cached) {\n\t\t\t// Try cached resolvers first\n\t\t\tfor (const id of cached) {\n\t\t\t\tconst def = definitions[id];\n\t\t\t\tif (def && resolverHandles(def, req)) {\n\t\t\t\t\treturn id;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Fallback to full search and cache the result\n\t\tfor (const [id, def] of Object.entries(definitions)) {\n\t\t\tif (resolverHandles(def, req)) {\n\t\t\t\t// Cache this resolver for this type (with size cap)\n\t\t\t\tif (!resolversByType.has(reqType)) {\n\t\t\t\t\t// Evict oldest entry if cache is full\n\t\t\t\t\tif (resolversByType.size >= MAX_RESOLVER_CACHE) {\n\t\t\t\t\t\tconst oldest = resolversByType.keys().next().value;\n\t\t\t\t\t\tif (oldest !== undefined) resolversByType.delete(oldest);\n\t\t\t\t\t}\n\t\t\t\t\tresolversByType.set(reqType, []);\n\t\t\t\t}\n\t\t\t\tconst typeResolvers = resolversByType.get(reqType)!;\n\t\t\t\tif (!typeResolvers.includes(id)) {\n\t\t\t\t\ttypeResolvers.push(id);\n\t\t\t\t}\n\t\t\t\treturn id;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** Create resolver context */\n\tfunction createContext(signal: AbortSignal): ResolverContext<S> {\n\t\treturn {\n\t\t\tfacts,\n\t\t\tsignal,\n\t\t\tsnapshot: () => facts.$snapshot() as FactsSnapshot<S>,\n\t\t};\n\t}\n\n\t/** Execute a single requirement resolution with retry */\n\tasync function executeResolve(\n\t\tresolverId: string,\n\t\treq: RequirementWithId,\n\t\tcontroller: AbortController,\n\t): Promise<void> {\n\t\tconst def = definitions[resolverId];\n\t\tif (!def) return;\n\t\tconst retryPolicy = { ...DEFAULT_RETRY, ...def.retry };\n\t\tlet lastError: Error | null = null;\n\n\t\tfor (let attempt = 1; attempt <= retryPolicy.attempts; attempt++) {\n\t\t\t// Check if canceled\n\t\t\tif (controller.signal.aborted) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tconst state = inflight.get(req.id);\n\t\t\tif (state) {\n\t\t\t\tstate.attempt = attempt;\n\t\t\t\tstate.status = {\n\t\t\t\t\tstate: \"running\",\n\t\t\t\t\trequirementId: req.id,\n\t\t\t\t\tstartedAt: state.startedAt,\n\t\t\t\t\tattempt,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst ctx = createContext(controller.signal);\n\n\t\t\t\tif (def.resolve) {\n\t\t\t\t\t// Batch the synchronous portion of resolve to coalesce fact mutations.\n\t\t\t\t\t// For sync-body async resolvers, all mutations are batched and flushed once.\n\t\t\t\t\t// For truly async resolvers, mutations before the first await are batched.\n\t\t\t\t\tlet resolvePromise!: Promise<void>;\n\t\t\t\t\tstore.batch(() => {\n\t\t\t\t\t\tresolvePromise = def.resolve!(req.requirement as Parameters<NonNullable<typeof def.resolve>>[0], ctx) as Promise<void>;\n\t\t\t\t\t});\n\n\t\t\t\t\tconst timeout = def.timeout;\n\t\t\t\t\tif (timeout && timeout > 0) {\n\t\t\t\t\t\tawait withTimeout(\n\t\t\t\t\t\t\tresolvePromise,\n\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\t`Resolver \"${resolverId}\" timed out after ${timeout}ms`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait resolvePromise;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Success\n\t\t\t\tconst duration = Date.now() - (state?.startedAt ?? Date.now());\n\t\t\t\tstatuses.set(req.id, {\n\t\t\t\t\tstate: \"success\",\n\t\t\t\t\trequirementId: req.id,\n\t\t\t\t\tcompletedAt: Date.now(),\n\t\t\t\t\tduration,\n\t\t\t\t});\n\t\t\t\tcleanupStatuses(); // Prevent memory leak\n\t\t\t\tonComplete?.(resolverId, req, duration);\n\t\t\t\treturn;\n\t\t\t} catch (error) {\n\t\t\t\tlastError = error instanceof Error ? error : new Error(String(error));\n\n\t\t\t\t// Check if it was an abort\n\t\t\t\tif (controller.signal.aborted) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Check shouldRetry predicate — if it returns false, stop immediately\n\t\t\t\tif (retryPolicy.shouldRetry && !retryPolicy.shouldRetry(lastError, attempt)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// If we have more attempts, wait and retry\n\t\t\t\tif (attempt < retryPolicy.attempts) {\n\t\t\t\t\t// Check abort before starting delay (avoids unnecessary waiting)\n\t\t\t\t\tif (controller.signal.aborted) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst delay = calculateDelay(retryPolicy, attempt);\n\t\t\t\t\tonRetry?.(resolverId, req, attempt + 1);\n\n\t\t\t\t\t// Use AbortSignal-aware sleep to respond to cancellation immediately\n\t\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\t\tconst timeoutId = setTimeout(resolve, delay);\n\t\t\t\t\t\t// Listen for abort during sleep\n\t\t\t\t\t\tconst abortHandler = () => {\n\t\t\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcontroller.signal.addEventListener(\"abort\", abortHandler, { once: true });\n\t\t\t\t\t});\n\n\t\t\t\t\t// Check abort after sleep\n\t\t\t\t\tif (controller.signal.aborted) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// All attempts failed (or shouldRetry returned false)\n\t\tstatuses.set(req.id, {\n\t\t\tstate: \"error\",\n\t\t\trequirementId: req.id,\n\t\t\terror: lastError!,\n\t\t\tfailedAt: Date.now(),\n\t\t\tattempts: retryPolicy.attempts,\n\t\t});\n\t\tcleanupStatuses();\n\t\tonError?.(resolverId, req, lastError);\n\t}\n\n\t/** Execute a batch of requirements with retry, timeout, and partial failure support */\n\tasync function executeBatch(\n\t\tresolverId: string,\n\t\trequirements: RequirementWithId[],\n\t): Promise<void> {\n\t\tconst def = definitions[resolverId];\n\t\tif (!def) return;\n\n\t\t// If no batch handler, fall back to individual resolution\n\t\tif (!def.resolveBatch && !def.resolveBatchWithResults) {\n\t\t\tawait Promise.all(\n\t\t\t\trequirements.map((req) => {\n\t\t\t\t\tconst controller = new AbortController();\n\t\t\t\t\treturn executeResolve(resolverId, req, controller);\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst retryPolicy = { ...DEFAULT_RETRY, ...def.retry };\n\t\tconst batchConfig = { ...DEFAULT_BATCH, ...def.batch };\n\t\tconst controller = new AbortController();\n\t\tconst startedAt = Date.now();\n\t\tlet lastError: Error | null = null;\n\n\t\t// Use batch timeout if configured, otherwise fall back to resolver timeout\n\t\tconst timeout = batchConfig.timeoutMs ?? def.timeout;\n\n\t\tfor (let attempt = 1; attempt <= retryPolicy.attempts; attempt++) {\n\t\t\t// Check if canceled\n\t\t\tif (controller.signal.aborted) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst ctx = createContext(controller.signal);\n\t\t\t\tconst reqPayloads = requirements.map((r) => r.requirement);\n\n\t\t\t\t// Check for resolveBatchWithResults (per-item results)\n\t\t\t\tif (def.resolveBatchWithResults) {\n\t\t\t\t\tlet results: BatchResolveResults;\n\n\t\t\t\t\t// Batch fact mutations for the synchronous portion of the resolver\n\t\t\t\t\tlet resolvePromise!: Promise<BatchResolveResults>;\n\t\t\t\t\tstore.batch(() => {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Requirement type varies\n\t\t\t\t\t\tresolvePromise = def.resolveBatchWithResults!(reqPayloads as any, ctx);\n\t\t\t\t\t});\n\n\t\t\t\t\tif (timeout && timeout > 0) {\n\t\t\t\t\t\tresults = await withTimeout(\n\t\t\t\t\t\t\tresolvePromise,\n\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\t`Batch resolver \"${resolverId}\" timed out after ${timeout}ms`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresults = await resolvePromise;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Validate results length\n\t\t\t\t\tif (results.length !== requirements.length) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`[Directive] Batch resolver \"${resolverId}\" returned ${results.length} results ` +\n\t\t\t\t\t\t\t\t`but expected ${requirements.length}. Results array must match input order.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Process per-item results\n\t\t\t\t\tconst duration = Date.now() - startedAt;\n\t\t\t\t\tlet hasFailures = false;\n\n\t\t\t\t\tfor (let i = 0; i < requirements.length; i++) {\n\t\t\t\t\t\tconst req = requirements[i]!;\n\t\t\t\t\t\tconst result = results[i]!;\n\n\t\t\t\t\t\tif (result.success) {\n\t\t\t\t\t\t\tstatuses.set(req.id, {\n\t\t\t\t\t\t\t\tstate: \"success\",\n\t\t\t\t\t\t\t\trequirementId: req.id,\n\t\t\t\t\t\t\t\tcompletedAt: Date.now(),\n\t\t\t\t\t\t\t\tduration,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tonComplete?.(resolverId, req, duration);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\thasFailures = true;\n\t\t\t\t\t\t\tconst error = result.error ?? new Error(\"Batch item failed\");\n\t\t\t\t\t\t\tstatuses.set(req.id, {\n\t\t\t\t\t\t\t\tstate: \"error\",\n\t\t\t\t\t\t\t\trequirementId: req.id,\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t\tfailedAt: Date.now(),\n\t\t\t\t\t\t\t\tattempts: attempt,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tonError?.(resolverId, req, error);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// No failures: all succeeded, done\n\t\t\t\t\tif (!hasFailures) return;\n\n\t\t\t\t\t// Partial success (some succeeded, some failed): don't retry the batch\n\t\t\t\t\tif (requirements.some((_, i) => results[i]?.success)) return;\n\n\t\t\t\t\t// ALL failed: fall through to retry logic below\n\t\t\t\t} else {\n\t\t\t\t\t// Use all-or-nothing resolveBatch\n\t\t\t\t\t// Batch fact mutations for the synchronous portion of the resolver\n\t\t\t\t\tlet resolvePromise!: Promise<void>;\n\t\t\t\t\tstore.batch(() => {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Requirement type varies\n\t\t\t\t\t\tresolvePromise = def.resolveBatch!(reqPayloads as any, ctx) as Promise<void>;\n\t\t\t\t\t});\n\n\t\t\t\t\tif (timeout && timeout > 0) {\n\t\t\t\t\t\tawait withTimeout(\n\t\t\t\t\t\t\tresolvePromise,\n\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\t`Batch resolver \"${resolverId}\" timed out after ${timeout}ms`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait resolvePromise;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Mark all as success\n\t\t\t\t\tconst duration = Date.now() - startedAt;\n\t\t\t\t\tfor (const req of requirements) {\n\t\t\t\t\t\tstatuses.set(req.id, {\n\t\t\t\t\t\t\tstate: \"success\",\n\t\t\t\t\t\t\trequirementId: req.id,\n\t\t\t\t\t\t\tcompletedAt: Date.now(),\n\t\t\t\t\t\t\tduration,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tonComplete?.(resolverId, req, duration);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tlastError = error instanceof Error ? error : new Error(String(error));\n\n\t\t\t\t// Check if it was an abort\n\t\t\t\tif (controller.signal.aborted) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Check shouldRetry predicate — if it returns false, stop immediately\n\t\t\t\tif (retryPolicy.shouldRetry && !retryPolicy.shouldRetry(lastError, attempt)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// If we have more attempts, wait and retry\n\t\t\t\tif (attempt < retryPolicy.attempts) {\n\t\t\t\t\tconst delay = calculateDelay(retryPolicy, attempt);\n\t\t\t\t\t// Notify retry for all requirements\n\t\t\t\t\tfor (const req of requirements) {\n\t\t\t\t\t\tonRetry?.(resolverId, req, attempt + 1);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Use AbortSignal-aware sleep\n\t\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\t\tconst timeoutId = setTimeout(resolve, delay);\n\t\t\t\t\t\tconst abortHandler = () => {\n\t\t\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcontroller.signal.addEventListener(\"abort\", abortHandler, { once: true });\n\t\t\t\t\t});\n\n\t\t\t\t\t// Check abort after sleep\n\t\t\t\t\tif (controller.signal.aborted) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// All attempts failed (or shouldRetry returned false) - mark all as error\n\t\tfor (const req of requirements) {\n\t\t\tstatuses.set(req.id, {\n\t\t\t\tstate: \"error\",\n\t\t\t\trequirementId: req.id,\n\t\t\t\terror: lastError!,\n\t\t\t\tfailedAt: Date.now(),\n\t\t\t\tattempts: retryPolicy.attempts,\n\t\t\t});\n\t\t\tonError?.(resolverId, req, lastError);\n\t\t}\n\t\tcleanupStatuses();\n\t}\n\n\t/** Add a requirement to a batch */\n\tfunction addToBatch(resolverId: string, req: RequirementWithId): void {\n\t\tconst def = definitions[resolverId];\n\t\tif (!def) return;\n\t\tconst batchConfig = { ...DEFAULT_BATCH, ...def.batch };\n\n\t\tif (!batches.has(resolverId)) {\n\t\t\tbatches.set(resolverId, {\n\t\t\t\tresolverId,\n\t\t\t\trequirements: [],\n\t\t\t\ttimer: null,\n\t\t\t});\n\t\t}\n\n\t\tconst batch = batches.get(resolverId)!;\n\t\tbatch.requirements.push(req);\n\n\t\t// Start or reset timer\n\t\tif (batch.timer) {\n\t\t\tclearTimeout(batch.timer);\n\t\t}\n\n\t\tbatch.timer = setTimeout(() => {\n\t\t\tprocessBatch(resolverId);\n\t\t}, batchConfig.windowMs);\n\t}\n\n\t/** Process a single batch */\n\tfunction processBatch(resolverId: string): void {\n\t\tconst batch = batches.get(resolverId);\n\t\tif (!batch || batch.requirements.length === 0) return;\n\n\t\tconst requirements = [...batch.requirements];\n\t\tbatch.requirements = [];\n\t\tbatch.timer = null;\n\n\t\t// Execute batch\n\t\texecuteBatch(resolverId, requirements).then(() => {\n\t\t\tonResolutionComplete?.();\n\t\t});\n\t}\n\n\tconst manager: ResolversManager<S> = {\n\t\tresolve(req: RequirementWithId): void {\n\t\t\t// Already resolving?\n\t\t\tif (inflight.has(req.id)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Find resolver\n\t\t\tconst resolverId = findResolver(req.requirement);\n\t\t\tif (!resolverId) {\n\t\t\t\tconsole.warn(`[Directive] No resolver found for requirement: ${req.id}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst def = definitions[resolverId];\n\t\t\tif (!def) return;\n\n\t\t\t// Check if this is a batched resolver\n\t\t\tif (def.batch?.enabled) {\n\t\t\t\taddToBatch(resolverId, req);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Start resolution\n\t\t\tconst controller = new AbortController();\n\t\t\tconst startedAt = Date.now();\n\n\t\t\tconst state: ResolverState = {\n\t\t\t\trequirementId: req.id,\n\t\t\t\tresolverId,\n\t\t\t\tcontroller,\n\t\t\t\tstartedAt,\n\t\t\t\tattempt: 1,\n\t\t\t\tstatus: {\n\t\t\t\t\tstate: \"pending\",\n\t\t\t\t\trequirementId: req.id,\n\t\t\t\t\tstartedAt,\n\t\t\t\t},\n\t\t\t\toriginalRequirement: req,\n\t\t\t};\n\n\t\t\tinflight.set(req.id, state);\n\t\t\tonStart?.(resolverId, req);\n\n\t\t\t// Execute asynchronously\n\t\t\texecuteResolve(resolverId, req, controller)\n\t\t\t\t.finally(() => {\n\t\t\t\t\t// Only fire onResolutionComplete if we're the first to clean up.\n\t\t\t\t\t// If cancel() already removed us from inflight, skip to avoid\n\t\t\t\t\t// spurious double-notifications.\n\t\t\t\t\tconst wasInflight = inflight.delete(req.id);\n\t\t\t\t\tif (wasInflight) {\n\t\t\t\t\t\tonResolutionComplete?.();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t},\n\n\t\tcancel(requirementId: string): void {\n\t\t\tconst state = inflight.get(requirementId);\n\t\t\tif (!state) return;\n\n\t\t\tstate.controller.abort();\n\t\t\tinflight.delete(requirementId);\n\n\t\t\tstatuses.set(requirementId, {\n\t\t\t\tstate: \"canceled\",\n\t\t\t\trequirementId,\n\t\t\t\tcanceledAt: Date.now(),\n\t\t\t});\n\t\t\tcleanupStatuses();\n\n\t\t\tonCancel?.(state.resolverId, state.originalRequirement);\n\t\t},\n\n\t\tcancelAll(): void {\n\t\t\tfor (const [id] of inflight) {\n\t\t\t\tthis.cancel(id);\n\t\t\t}\n\n\t\t\t// Clear batches\n\t\t\tfor (const batch of batches.values()) {\n\t\t\t\tif (batch.timer) {\n\t\t\t\t\tclearTimeout(batch.timer);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbatches.clear();\n\t\t},\n\n\t\tgetStatus(requirementId: string): ResolverStatus {\n\t\t\t// Check inflight first\n\t\t\tconst state = inflight.get(requirementId);\n\t\t\tif (state) {\n\t\t\t\treturn state.status;\n\t\t\t}\n\n\t\t\t// Check completed statuses\n\t\t\tconst status = statuses.get(requirementId);\n\t\t\tif (status) {\n\t\t\t\treturn status;\n\t\t\t}\n\n\t\t\treturn { state: \"idle\" };\n\t\t},\n\n\t\tgetInflight(): string[] {\n\t\t\treturn [...inflight.keys()];\n\t\t},\n\n\t\tgetInflightInfo(): InflightInfo[] {\n\t\t\treturn [...inflight.values()].map((state) => ({\n\t\t\t\tid: state.requirementId,\n\t\t\t\tresolverId: state.resolverId,\n\t\t\t\tstartedAt: state.startedAt,\n\t\t\t}));\n\t\t},\n\n\t\tisResolving(requirementId: string): boolean {\n\t\t\treturn inflight.has(requirementId);\n\t\t},\n\n\t\tprocessBatches(): void {\n\t\t\tfor (const resolverId of batches.keys()) {\n\t\t\t\tprocessBatch(resolverId);\n\t\t\t}\n\t\t},\n\n\t\tregisterDefinitions(newDefs: ResolversDef<Schema>): void {\n\t\t\tfor (const [key, def] of Object.entries(newDefs)) {\n\t\t\t\t(definitions as Record<string, unknown>)[key] = def;\n\t\t\t}\n\t\t\t// Clear the resolver-by-type cache so new resolvers are discovered\n\t\t\tresolversByType.clear();\n\t\t},\n\t};\n\n\treturn manager;\n}\n","/**\n * Time-Travel Debugging - Snapshot-based state history\n *\n * Features:\n * - Ring buffer of state snapshots\n * - Go back/forward through history\n * - Replay from any snapshot\n * - Export/import state history\n */\n\nimport type { DebugConfig, Facts, FactsStore, Schema, Snapshot, TimeTravelAPI } from \"../core/types.js\";\nimport { isPrototypeSafe } from \"./utils.js\";\n\n// ============================================================================\n// Time-Travel Manager\n// ============================================================================\n\n/** A changeset groups multiple snapshots into a single undo/redo unit. */\nexport interface Changeset {\n\tlabel: string;\n\tstartIndex: number;\n\tendIndex: number;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface TimeTravelManager<_S extends Schema> extends TimeTravelAPI {\n\t/** Take a snapshot of current state */\n\ttakeSnapshot(trigger: string): Snapshot;\n\t/** Restore facts from a snapshot */\n\trestore(snapshot: Snapshot): void;\n\t/** Check if time-travel is enabled */\n\treadonly isEnabled: boolean;\n\t/** True while restoring a snapshot (engine should skip reconciliation) */\n\treadonly isRestoring: boolean;\n\t/** Pause snapshot taking */\n\tpause(): void;\n\t/** Resume snapshot taking */\n\tresume(): void;\n}\n\n/** Options for creating a time-travel manager */\nexport interface CreateTimeTravelOptions<S extends Schema> {\n\tconfig: DebugConfig;\n\tfacts: Facts<S>;\n\tstore: FactsStore<S>;\n\t/** Callback when a snapshot is taken */\n\tonSnapshot?: (snapshot: Snapshot) => void;\n\t/** Callback when time-travel occurs */\n\tonTimeTravel?: (from: number, to: number) => void;\n}\n\n/**\n * Create a snapshot-based time-travel debugger with a ring buffer of state\n * history.\n *\n * Snapshots are taken automatically after fact changes (during\n * reconciliation) and can be navigated with `goBack`/`goForward`/`goTo`.\n * Changesets group multiple snapshots into a single undo/redo unit.\n * The entire history can be exported to JSON and re-imported for\n * cross-session debugging.\n *\n * @param options - Debug config (maxSnapshots, timeTravel flag), facts proxy, store, and snapshot/time-travel callbacks\n * @returns A `TimeTravelManager` with takeSnapshot/restore/goBack/goForward/goTo/replay/export/import and changeset methods\n */\nexport function createTimeTravelManager<S extends Schema>(\n\toptions: CreateTimeTravelOptions<S>,\n): TimeTravelManager<S> {\n\tconst { config, facts, store, onSnapshot, onTimeTravel } = options;\n\n\tconst isEnabled = config.timeTravel ?? false;\n\tconst maxSnapshots = config.maxSnapshots ?? 100;\n\n\t// Ring buffer of snapshots\n\tconst snapshots: Snapshot[] = [];\n\tlet currentIndex = -1;\n\tlet nextId = 1;\n\tlet paused = false;\n\tlet restoring = false;\n\n\t// Changeset tracking\n\tconst changesets: Changeset[] = [];\n\tlet pendingChangesetLabel: string | null = null;\n\tlet pendingChangesetStart = -1;\n\n\t/** Get current facts as a plain object */\n\tfunction getCurrentFacts(): Record<string, unknown> {\n\t\treturn store.toObject();\n\t}\n\n\t/** Serialize facts to a snapshot-friendly format */\n\tfunction serializeFacts(): Record<string, unknown> {\n\t\tconst factsObj = getCurrentFacts();\n\n\t\t// Deep clone to prevent mutation\n\t\treturn structuredClone(factsObj);\n\t}\n\n\t/** Deserialize and restore facts from a snapshot */\n\tfunction deserializeFacts(serialized: Record<string, unknown>): void {\n\t\t// Validate entire object tree for prototype pollution\n\t\tif (!isPrototypeSafe(serialized)) {\n\t\t\tconsole.error(\"[Directive] Potential prototype pollution detected in snapshot data, skipping restore\");\n\t\t\treturn;\n\t\t}\n\n\t\tstore.batch(() => {\n\t\t\tfor (const [key, value] of Object.entries(serialized)) {\n\t\t\t\t// Prototype pollution protection (redundant but defensive)\n\t\t\t\tif (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") {\n\t\t\t\t\tconsole.warn(`[Directive] Skipping dangerous key \"${key}\" during fact restoration`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// @ts-expect-error - dynamic key access\n\t\t\t\tfacts[key] = value;\n\t\t\t}\n\t\t});\n\t}\n\n\tconst manager: TimeTravelManager<S> = {\n\t\tget isEnabled() {\n\t\t\treturn isEnabled;\n\t\t},\n\n\t\tget isRestoring() {\n\t\t\treturn restoring;\n\t\t},\n\n\t\tget isPaused() {\n\t\t\treturn paused;\n\t\t},\n\n\t\tget snapshots() {\n\t\t\treturn [...snapshots];\n\t\t},\n\n\t\tget currentIndex() {\n\t\t\treturn currentIndex;\n\t\t},\n\n\t\ttakeSnapshot(trigger: string): Snapshot {\n\t\t\tif (!isEnabled || paused) {\n\t\t\t\treturn { id: -1, timestamp: Date.now(), facts: {}, trigger };\n\t\t\t}\n\n\t\t\tconst snapshot: Snapshot = {\n\t\t\t\tid: nextId++,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tfacts: serializeFacts(),\n\t\t\t\ttrigger,\n\t\t\t};\n\n\t\t\t// If we're not at the end, truncate future snapshots\n\t\t\tif (currentIndex < snapshots.length - 1) {\n\t\t\t\tsnapshots.splice(currentIndex + 1);\n\t\t\t}\n\n\t\t\t// Add new snapshot\n\t\t\tsnapshots.push(snapshot);\n\t\t\tcurrentIndex = snapshots.length - 1;\n\n\t\t\t// Enforce max size (ring buffer)\n\t\t\twhile (snapshots.length > maxSnapshots) {\n\t\t\t\tsnapshots.shift();\n\t\t\t\tcurrentIndex--;\n\t\t\t}\n\n\t\t\tonSnapshot?.(snapshot);\n\t\t\treturn snapshot;\n\t\t},\n\n\t\trestore(snapshot: Snapshot): void {\n\t\t\tif (!isEnabled) return;\n\n\t\t\t// Set restoring flag so the engine skips reconciliation scheduling.\n\t\t\t// The restored state is already \"reconciled\" — it was captured after\n\t\t\t// a complete reconcile cycle. Re-reconciling would create spurious\n\t\t\t// snapshots that break undo/redo navigation.\n\t\t\tpaused = true;\n\t\t\trestoring = true;\n\n\t\t\ttry {\n\t\t\t\tdeserializeFacts(snapshot.facts);\n\t\t\t} finally {\n\t\t\t\tpaused = false;\n\t\t\t\trestoring = false;\n\t\t\t}\n\t\t},\n\n\t\tgoBack(steps = 1): void {\n\t\t\tif (!isEnabled || snapshots.length === 0) return;\n\n\t\t\tconst fromIndex = currentIndex;\n\n\t\t\t// Check if we're inside a changeset — jump to its start\n\t\t\tlet toIndex = currentIndex;\n\t\t\tconst cs = changesets.find((c) => currentIndex > c.startIndex && currentIndex <= c.endIndex);\n\t\t\tif (cs) {\n\t\t\t\ttoIndex = cs.startIndex;\n\t\t\t} else {\n\t\t\t\t// Check if we're at the end of a changeset — jump past its start\n\t\t\t\tconst prevCs = changesets.find((c) => currentIndex === c.startIndex);\n\t\t\t\tif (prevCs) {\n\t\t\t\t\t// We're at the boundary. Look for the changeset before this one.\n\t\t\t\t\tconst earlierCs = changesets.find((c) => c.endIndex < currentIndex && currentIndex - c.endIndex <= steps);\n\t\t\t\t\ttoIndex = earlierCs ? earlierCs.startIndex : Math.max(0, currentIndex - steps);\n\t\t\t\t} else {\n\t\t\t\t\ttoIndex = Math.max(0, currentIndex - steps);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (fromIndex === toIndex) return;\n\n\t\t\tcurrentIndex = toIndex;\n\t\t\tconst snapshot = snapshots[currentIndex];\n\t\t\tif (snapshot) {\n\t\t\t\tthis.restore(snapshot);\n\t\t\t\tonTimeTravel?.(fromIndex, toIndex);\n\t\t\t}\n\t\t},\n\n\t\tgoForward(steps = 1): void {\n\t\t\tif (!isEnabled || snapshots.length === 0) return;\n\n\t\t\tconst fromIndex = currentIndex;\n\n\t\t\t// Check if we're inside or at the start of a changeset — jump to its end\n\t\t\tlet toIndex = currentIndex;\n\t\t\tconst cs = changesets.find((c) => currentIndex >= c.startIndex && currentIndex < c.endIndex);\n\t\t\tif (cs) {\n\t\t\t\ttoIndex = cs.endIndex;\n\t\t\t} else {\n\t\t\t\ttoIndex = Math.min(snapshots.length - 1, currentIndex + steps);\n\t\t\t}\n\n\t\t\tif (fromIndex === toIndex) return;\n\n\t\t\tcurrentIndex = toIndex;\n\t\t\tconst snapshot = snapshots[currentIndex];\n\t\t\tif (snapshot) {\n\t\t\t\tthis.restore(snapshot);\n\t\t\t\tonTimeTravel?.(fromIndex, toIndex);\n\t\t\t}\n\t\t},\n\n\t\tgoTo(snapshotId: number): void {\n\t\t\tif (!isEnabled) return;\n\n\t\t\tconst index = snapshots.findIndex((s) => s.id === snapshotId);\n\t\t\tif (index === -1) {\n\t\t\t\tconsole.warn(`[Directive] Snapshot ${snapshotId} not found`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst fromIndex = currentIndex;\n\t\t\tcurrentIndex = index;\n\t\t\tconst snapshot = snapshots[currentIndex];\n\t\t\tif (snapshot) {\n\t\t\t\tthis.restore(snapshot);\n\t\t\t\tonTimeTravel?.(fromIndex, index);\n\t\t\t}\n\t\t},\n\n\t\treplay(): void {\n\t\t\tif (!isEnabled || snapshots.length === 0) return;\n\n\t\t\t// Start from the beginning\n\t\t\tcurrentIndex = 0;\n\t\t\tconst snapshot = snapshots[0];\n\t\t\tif (snapshot) {\n\t\t\t\tthis.restore(snapshot);\n\t\t\t}\n\t\t},\n\n\t\texport(): string {\n\t\t\treturn JSON.stringify({\n\t\t\t\tversion: 1,\n\t\t\t\tsnapshots,\n\t\t\t\tcurrentIndex,\n\t\t\t});\n\t\t},\n\n\t\timport(json: string): void {\n\t\t\tif (!isEnabled) return;\n\n\t\t\ttry {\n\t\t\t\tconst data = JSON.parse(json);\n\n\t\t\t\t// Validate import data structure to prevent prototype pollution\n\t\t\t\tif (typeof data !== \"object\" || data === null) {\n\t\t\t\t\tthrow new Error(\"Invalid time-travel data: expected object\");\n\t\t\t\t}\n\t\t\t\tif (data.version !== 1) {\n\t\t\t\t\tthrow new Error(`Unsupported time-travel export version: ${data.version}`);\n\t\t\t\t}\n\t\t\t\tif (!Array.isArray(data.snapshots)) {\n\t\t\t\t\tthrow new Error(\"Invalid time-travel data: snapshots must be an array\");\n\t\t\t\t}\n\t\t\t\tif (typeof data.currentIndex !== \"number\") {\n\t\t\t\t\tthrow new Error(\"Invalid time-travel data: currentIndex must be a number\");\n\t\t\t\t}\n\n\t\t\t\t// Validate each snapshot has required properties\n\t\t\t\tfor (const snap of data.snapshots) {\n\t\t\t\t\tif (typeof snap !== \"object\" || snap === null) {\n\t\t\t\t\t\tthrow new Error(\"Invalid snapshot: expected object\");\n\t\t\t\t\t}\n\t\t\t\t\tif (typeof snap.id !== \"number\" || typeof snap.timestamp !== \"number\" ||\n\t\t\t\t\t\ttypeof snap.trigger !== \"string\" || typeof snap.facts !== \"object\") {\n\t\t\t\t\t\tthrow new Error(\"Invalid snapshot structure\");\n\t\t\t\t\t}\n\t\t\t\t\t// Deep check for prototype pollution attacks (including nested objects)\n\t\t\t\t\tif (!isPrototypeSafe(snap.facts)) {\n\t\t\t\t\t\tthrow new Error(\"Invalid fact data: potential prototype pollution detected in nested objects\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsnapshots.length = 0;\n\t\t\t\tsnapshots.push(...data.snapshots);\n\t\t\t\tcurrentIndex = data.currentIndex;\n\n\t\t\t\t// Restore current state\n\t\t\t\tconst snapshot = snapshots[currentIndex];\n\t\t\t\tif (snapshot) {\n\t\t\t\t\tthis.restore(snapshot);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"[Directive] Failed to import time-travel data:\", error);\n\t\t\t}\n\t\t},\n\n\t\tbeginChangeset(label: string): void {\n\t\t\tif (!isEnabled) return;\n\t\t\tpendingChangesetLabel = label;\n\t\t\tpendingChangesetStart = currentIndex;\n\t\t},\n\n\t\tendChangeset(): void {\n\t\t\tif (!isEnabled || pendingChangesetLabel === null) return;\n\t\t\tif (currentIndex > pendingChangesetStart) {\n\t\t\t\tchangesets.push({\n\t\t\t\t\tlabel: pendingChangesetLabel,\n\t\t\t\t\tstartIndex: pendingChangesetStart,\n\t\t\t\t\tendIndex: currentIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t\tpendingChangesetLabel = null;\n\t\t\tpendingChangesetStart = -1;\n\t\t},\n\n\t\tpause(): void {\n\t\t\tpaused = true;\n\t\t},\n\n\t\tresume(): void {\n\t\t\tpaused = false;\n\t\t},\n\t};\n\n\treturn manager;\n}\n\n/**\n * Create a no-op time-travel manager used when `debug.timeTravel` is\n * disabled. All methods are safe to call but perform no work.\n *\n * @returns A `TimeTravelManager` where every method is a no-op and `isEnabled` is `false`\n */\nexport function createDisabledTimeTravel<S extends Schema>(): TimeTravelManager<S> {\n\tconst noopSnapshot: Snapshot = { id: -1, timestamp: 0, facts: {}, trigger: \"\" };\n\n\treturn {\n\t\tisEnabled: false,\n\t\tisRestoring: false,\n\t\tisPaused: false,\n\t\tsnapshots: [],\n\t\tcurrentIndex: -1,\n\t\ttakeSnapshot: () => noopSnapshot,\n\t\trestore: () => {},\n\t\tgoBack: () => {},\n\t\tgoForward: () => {},\n\t\tgoTo: () => {},\n\t\treplay: () => {},\n\t\texport: () => \"{}\",\n\t\timport: () => {},\n\t\tbeginChangeset: () => {},\n\t\tendChangeset: () => {},\n\t\tpause: () => {},\n\t\tresume: () => {},\n\t};\n}\n","/**\n * Engine - The core reconciliation loop\n *\n * The engine orchestrates:\n * 1. Fact changes trigger reconciliation\n * 2. Constraints produce requirements\n * 3. Resolvers fulfill requirements\n * 4. Effects run after stabilization\n * 5. Derivations are invalidated and recomputed\n */\n\nimport { createConstraintsManager, type ConstraintsManager } from \"./constraints.js\";\nimport { createDerivationsManager, type DerivationsManager } from \"./derivations.js\";\nimport { createEffectsManager, type EffectsManager } from \"./effects.js\";\nimport { createErrorBoundaryManager, type ErrorBoundaryManager } from \"./errors.js\";\nimport { createFacts } from \"./facts.js\";\nimport { createPluginManager, type PluginManager } from \"./plugins.js\";\nimport { RequirementSet } from \"./requirements.js\";\nimport { createResolversManager, type ResolversManager } from \"./resolvers.js\";\nimport { createDisabledTimeTravel, createTimeTravelManager, type TimeTravelManager } from \"../utils/time-travel.js\";\nimport { isPrototypeSafe, hashObject } from \"../utils/utils.js\";\n\n// Blocked properties for prototype pollution protection\nconst BLOCKED_PROPS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\nimport type {\n\tConstraintsDef,\n\tDerivationsDef,\n\tEffectsDef,\n\tEventsDef,\n\tFactsSnapshot,\n\tInferSchema,\n\tReconcileResult,\n\tResolversDef,\n\tSchema,\n\tSystem,\n\tSystemConfig,\n\tSystemEvent,\n\tSystemInspection,\n} from \"./types.js\";\n\n// ============================================================================\n// Engine Implementation\n// ============================================================================\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ninterface EngineState<_S extends Schema> {\n\tisRunning: boolean;\n\tisReconciling: boolean;\n\treconcileScheduled: boolean;\n\tisInitializing: boolean;\n\tisInitialized: boolean;\n\tisReady: boolean;\n\tisDestroyed: boolean;\n\tchangedKeys: Set<string>;\n\tpreviousRequirements: RequirementSet;\n\treadyPromise: Promise<void> | null;\n\treadyResolve: (() => void) | null;\n}\n\n/**\n * Create the core Directive reconciliation engine that wires facts, derivations,\n * effects, constraints, resolvers, plugins, error boundaries, and time-travel\n * into a single reactive system.\n *\n * This is the internal factory used by `createSystem`. Most users should call\n * `createSystem` instead, which provides a friendlier API and handles module\n * composition.\n *\n * @param config - Full system configuration: modules, plugins, error boundary settings, and debug options\n * @returns A `System` instance with facts, derive, events, dispatch, subscribe, watch, settle, and lifecycle methods\n *\n * @example\n * ```ts\n * // Prefer createSystem for most use cases:\n * import { createSystem, createModule, t } from \"@directive-run/core\";\n *\n * const counter = createModule(\"counter\", {\n * schema: { count: t.number() },\n * init: (facts) => { facts.count = 0; },\n * });\n *\n * const system = createSystem({ module: counter });\n * system.start();\n * system.facts.count = 42;\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: Engine uses flat schema internally, public API uses ModuleSchema\nexport function createEngine<S extends Schema>(\n\tconfig: SystemConfig<any>,\n): System<any> {\n\t// Merge all module definitions with collision detection\n\t// Use Object.create(null) to prevent prototype chain traversal (e.g., \"toString\" in mergedEvents)\n\tconst mergedSchema = Object.create(null) as S;\n\tconst mergedEvents: EventsDef<S> = Object.create(null);\n\tconst mergedDerive: DerivationsDef<S> = Object.create(null);\n\tconst mergedEffects: EffectsDef<S> = Object.create(null);\n\tconst mergedConstraints: ConstraintsDef<S> = Object.create(null);\n\tconst mergedResolvers: ResolversDef<S> = Object.create(null);\n\n\t// Track which module defined each key for collision detection\n\tconst schemaOwners = new Map<string, string>();\n\n\tfor (const module of config.modules) {\n\t\t// Security: Validate module definitions for dangerous keys\n\t\t// Always run in all environments — this is a security boundary, not a dev convenience\n\t\tconst validateKeys = (obj: object | undefined, section: string) => {\n\t\t\tif (!obj) return;\n\t\t\tfor (const key of Object.keys(obj)) {\n\t\t\t\tif (BLOCKED_PROPS.has(key)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Security: Module \"${module.id}\" has dangerous key \"${key}\" in ${section}. ` +\n\t\t\t\t\t\t\t`This could indicate a prototype pollution attempt.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tvalidateKeys(module.schema, \"schema\");\n\t\tvalidateKeys(module.events, \"events\");\n\t\tvalidateKeys(module.derive, \"derive\");\n\t\tvalidateKeys(module.effects, \"effects\");\n\t\tvalidateKeys(module.constraints, \"constraints\");\n\t\tvalidateKeys(module.resolvers, \"resolvers\");\n\n\t\t// Check for schema collisions\n\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\tfor (const key of Object.keys(module.schema)) {\n\t\t\t\tconst existingOwner = schemaOwners.get(key);\n\t\t\t\tif (existingOwner) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Schema collision: Fact \"${key}\" is defined in both module \"${existingOwner}\" and \"${module.id}\". ` +\n\t\t\t\t\t\t\t`Use namespacing (e.g., \"${module.id}::${key}\") or merge into one module.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tschemaOwners.set(key, module.id);\n\t\t\t}\n\t\t}\n\n\t\tObject.assign(mergedSchema, module.schema);\n\t\tif (module.events) Object.assign(mergedEvents, module.events);\n\t\tif (module.derive) Object.assign(mergedDerive, module.derive);\n\t\tif (module.effects) Object.assign(mergedEffects, module.effects);\n\t\tif (module.constraints) Object.assign(mergedConstraints, module.constraints);\n\t\tif (module.resolvers) Object.assign(mergedResolvers, module.resolvers);\n\t}\n\n\t// Dev-mode: Warn if a fact and derivation share the same name\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tconst derivationNames = new Set(Object.keys(mergedDerive));\n\t\tfor (const key of Object.keys(mergedSchema)) {\n\t\t\tif (derivationNames.has(key)) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] \"${key}\" exists as both a fact and a derivation. ` +\n\t\t\t\t\t`This may cause unexpected dependency tracking behavior.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create plugin manager\n\tconst pluginManager: PluginManager<S> = createPluginManager();\n\tfor (const plugin of config.plugins ?? []) {\n\t\tpluginManager.register(plugin);\n\t}\n\n\t// Create error boundary\n\tconst errorBoundary: ErrorBoundaryManager = createErrorBoundaryManager({\n\t\tconfig: config.errorBoundary,\n\t\tonError: (error) => pluginManager.emitError(error),\n\t\tonRecovery: (error, strategy) => pluginManager.emitErrorRecovery(error, strategy),\n\t});\n\n\t// Create facts store and proxy\n\t// Note: We need to create a local invalidate function that will be set after derivationsManager is created\n\tlet invalidateDerivation: (key: string) => void = () => {};\n\tlet invalidateManyDerivations: (keys: string[]) => void = () => {};\n\n\t// Forward-declared so onChange/onBatch closures can check isRestoring.\n\t// Assigned after createTimeTravelManager() below.\n\tlet timeTravelRef: TimeTravelManager<S> | null = null;\n\n\tconst { store, facts } = createFacts<S>({\n\t\tschema: mergedSchema,\n\t\tonChange: (key, value, prev) => {\n\t\t\tpluginManager.emitFactSet(key, value, prev);\n\t\t\t// Invalidate derivations so they recompute on read\n\t\t\tinvalidateDerivation(key);\n\t\t\t// During time-travel restore, skip change tracking and reconciliation.\n\t\t\t// The restored state is already reconciled; re-reconciling would create\n\t\t\t// spurious snapshots that break undo/redo.\n\t\t\tif (timeTravelRef?.isRestoring) return;\n\t\t\tstate.changedKeys.add(key);\n\t\t\tscheduleReconcile();\n\t\t},\n\t\tonBatch: (changes) => {\n\t\t\tpluginManager.emitFactsBatch(changes);\n\t\t\tconst keys: string[] = [];\n\t\t\tfor (const change of changes) {\n\t\t\t\tkeys.push(change.key);\n\t\t\t}\n\t\t\t// Invalidate all affected derivations at once — listeners fire only\n\t\t\t// after ALL keys are invalidated, so they see consistent state.\n\t\t\tinvalidateManyDerivations(keys);\n\t\t\t// During time-travel restore, skip change tracking and reconciliation.\n\t\t\tif (timeTravelRef?.isRestoring) return;\n\t\t\tfor (const change of changes) {\n\t\t\t\tstate.changedKeys.add(change.key);\n\t\t\t}\n\t\t\tscheduleReconcile();\n\t\t},\n\t});\n\n\t// Create derivations manager\n\tconst derivationsManager: DerivationsManager<S, DerivationsDef<S>> = createDerivationsManager({\n\t\tdefinitions: mergedDerive,\n\t\tfacts,\n\t\tstore,\n\t\tonCompute: (id, value, deps) => pluginManager.emitDerivationCompute(id, value, deps),\n\t\tonInvalidate: (id) => pluginManager.emitDerivationInvalidate(id),\n\t\tonError: (id, error) => {\n\t\t\terrorBoundary.handleError(\"derivation\", id, error);\n\t\t},\n\t});\n\n\t// Now wire up derivation invalidation\n\tinvalidateDerivation = (key: string) => derivationsManager.invalidate(key);\n\tinvalidateManyDerivations = (keys: string[]) => derivationsManager.invalidateMany(keys);\n\n\t// Create effects manager\n\tconst effectsManager: EffectsManager<S> = createEffectsManager({\n\t\tdefinitions: mergedEffects,\n\t\tfacts,\n\t\tstore,\n\t\tonRun: (id) => pluginManager.emitEffectRun(id),\n\t\tonError: (id, error) => {\n\t\t\terrorBoundary.handleError(\"effect\", id, error);\n\t\t\tpluginManager.emitEffectError(id, error);\n\t\t},\n\t});\n\n\t// Create constraints manager\n\tconst constraintsManager: ConstraintsManager<S> = createConstraintsManager({\n\t\tdefinitions: mergedConstraints,\n\t\tfacts,\n\t\tonEvaluate: (id, active) => pluginManager.emitConstraintEvaluate(id, active),\n\t\tonError: (id, error) => {\n\t\t\terrorBoundary.handleError(\"constraint\", id, error);\n\t\t\tpluginManager.emitConstraintError(id, error);\n\t\t},\n\t});\n\n\t// Create resolvers manager\n\tconst resolversManager: ResolversManager<S> = createResolversManager({\n\t\tdefinitions: mergedResolvers,\n\t\tfacts,\n\t\tstore,\n\t\tonStart: (resolver, req) => pluginManager.emitResolverStart(resolver, req),\n\t\tonComplete: (resolver, req, duration) => {\n\t\t\tpluginManager.emitResolverComplete(resolver, req, duration);\n\t\t\tpluginManager.emitRequirementMet(req, resolver);\n\t\t\t// Mark the constraint as resolved for `after` ordering\n\t\t\tconstraintsManager.markResolved(req.fromConstraint);\n\t\t},\n\t\tonError: (resolver, req, error) => {\n\t\t\terrorBoundary.handleError(\"resolver\", resolver, error, req);\n\t\t\tpluginManager.emitResolverError(resolver, req, error);\n\t\t},\n\t\tonRetry: (resolver, req, attempt) => pluginManager.emitResolverRetry(resolver, req, attempt),\n\t\tonCancel: (resolver, req) => {\n\t\t\tpluginManager.emitResolverCancel(resolver, req);\n\t\t\tpluginManager.emitRequirementCanceled(req);\n\t\t},\n\t\tonResolutionComplete: () => {\n\t\t\t// After a resolver completes, schedule another reconcile\n\t\t\tnotifySettlementChange();\n\t\t\tscheduleReconcile();\n\t\t},\n\t});\n\n\t// Time-travel listeners — notified when snapshot state changes\n\tconst timeTravelListeners = new Set<() => void>();\n\n\tfunction notifyTimeTravelChange(): void {\n\t\tfor (const listener of timeTravelListeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n\n\t// Create time-travel manager\n\tconst timeTravelManager: TimeTravelManager<S> = config.debug?.timeTravel\n\t\t? createTimeTravelManager({\n\t\t\t\tconfig: config.debug,\n\t\t\t\tfacts,\n\t\t\t\tstore,\n\t\t\t\tonSnapshot: (snapshot) => {\n\t\t\t\t\tpluginManager.emitSnapshot(snapshot);\n\t\t\t\t\tnotifyTimeTravelChange();\n\t\t\t\t},\n\t\t\t\tonTimeTravel: (from, to) => {\n\t\t\t\t\tpluginManager.emitTimeTravel(from, to);\n\t\t\t\t\tnotifyTimeTravelChange();\n\t\t\t\t},\n\t\t\t})\n\t\t: createDisabledTimeTravel();\n\ttimeTravelRef = timeTravelManager;\n\n\t// Settlement listeners — notified when isSettled may have changed\n\tconst settlementListeners = new Set<() => void>();\n\n\tfunction notifySettlementChange(): void {\n\t\tfor (const listener of settlementListeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n\n\t// Reconcile depth guard — prevents runaway reconcile → scheduleReconcile chains\n\tconst MAX_RECONCILE_DEPTH = 50;\n\tlet reconcileDepth = 0;\n\n\t// Engine state\n\tconst state: EngineState<S> = {\n\t\tisRunning: false,\n\t\tisReconciling: false,\n\t\treconcileScheduled: false,\n\t\tisInitializing: false,\n\t\tisInitialized: false,\n\t\tisReady: false,\n\t\tisDestroyed: false,\n\t\tchangedKeys: new Set(),\n\t\tpreviousRequirements: new RequirementSet(),\n\t\treadyPromise: null,\n\t\treadyResolve: null,\n\t};\n\n\t/** Schedule a reconciliation on the next microtask */\n\tfunction scheduleReconcile(): void {\n\t\t// Suppress reconciliation during initialization phase\n\t\tif (!state.isRunning || state.reconcileScheduled || state.isInitializing) return;\n\n\t\tstate.reconcileScheduled = true;\n\t\tnotifySettlementChange();\n\t\tqueueMicrotask(() => {\n\t\t\tstate.reconcileScheduled = false;\n\t\t\tif (state.isRunning && !state.isInitializing) {\n\t\t\t\t// Await reconcile to prevent race conditions\n\t\t\t\t// Error is caught inside reconcile, so no need to handle here\n\t\t\t\treconcile().catch((error) => {\n\t\t\t\t\t// Only log unexpected errors (reconcile handles its own errors)\n\t\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\t\tconsole.error(\"[Directive] Unexpected error in reconcile:\", error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\n\t/** The main reconciliation loop */\n\tasync function reconcile(): Promise<void> {\n\t\tif (state.isReconciling) return;\n\n\t\treconcileDepth++;\n\t\tif (reconcileDepth > MAX_RECONCILE_DEPTH) {\n\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] Reconcile loop exceeded ${MAX_RECONCILE_DEPTH} iterations. ` +\n\t\t\t\t\t`This usually means resolvers are creating circular requirement chains. ` +\n\t\t\t\t\t`Check that resolvers aren't mutating facts that re-trigger their own constraints.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treconcileDepth = 0;\n\t\t\treturn;\n\t\t}\n\n\t\tstate.isReconciling = true;\n\t\tnotifySettlementChange();\n\n\t\ttry {\n\t\t\t// Take snapshot before reconciliation\n\t\t\tif (state.changedKeys.size > 0) {\n\t\t\t\ttimeTravelManager.takeSnapshot(`facts-changed:${[...state.changedKeys].join(\",\")}`);\n\t\t\t}\n\n\t\t\t// Get snapshot for plugins\n\t\t\tconst snapshot = facts.$snapshot() as FactsSnapshot<S>;\n\t\t\tpluginManager.emitReconcileStart(snapshot);\n\n\t\t\t// Note: Derivations are already invalidated immediately when facts change\n\t\t\t// (in the onChange/onBatch callbacks), so we don't need to do it here\n\n\t\t\t// Run effects for changed keys\n\t\t\tawait effectsManager.runEffects(state.changedKeys);\n\n\t\t\t// Copy changed keys for constraint evaluation before clearing\n\t\t\tconst keysForConstraints = new Set(state.changedKeys);\n\n\t\t\t// Clear changed keys\n\t\t\tstate.changedKeys.clear();\n\n\t\t\t// Evaluate constraints (pass changed keys for incremental evaluation)\n\t\t\tconst currentRequirements = await constraintsManager.evaluate(keysForConstraints);\n\t\t\tconst currentSet = new RequirementSet();\n\t\t\tfor (const req of currentRequirements) {\n\t\t\t\tcurrentSet.add(req);\n\t\t\t\tpluginManager.emitRequirementCreated(req);\n\t\t\t}\n\n\t\t\t// Diff with previous requirements\n\t\t\tconst { added, removed } = currentSet.diff(state.previousRequirements);\n\n\t\t\t// Cancel resolvers for removed requirements\n\t\t\tfor (const req of removed) {\n\t\t\t\tresolversManager.cancel(req.id);\n\t\t\t}\n\n\t\t\t// Start resolvers for new requirements\n\t\t\tfor (const req of added) {\n\t\t\t\tresolversManager.resolve(req);\n\t\t\t}\n\n\t\t\t// Update previous requirements\n\t\t\tstate.previousRequirements = currentSet;\n\n\t\t\t// Build reconcile result\n\t\t\tconst inflightInfo = resolversManager.getInflightInfo();\n\t\t\tconst result: ReconcileResult = {\n\t\t\t\tunmet: currentRequirements.filter((r) => !resolversManager.isResolving(r.id)),\n\t\t\t\tinflight: inflightInfo,\n\t\t\t\tcompleted: [], // Completed resolvers are tracked separately via onComplete callback\n\t\t\t\tcanceled: removed.map((r) => ({\n\t\t\t\t\tid: r.id,\n\t\t\t\t\tresolverId: inflightInfo.find((i) => i.id === r.id)?.resolverId ?? \"unknown\",\n\t\t\t\t})),\n\t\t\t};\n\n\t\t\tpluginManager.emitReconcileEnd(result);\n\n\t\t\t// Mark system as ready after first successful reconcile\n\t\t\tif (!state.isReady) {\n\t\t\t\tstate.isReady = true;\n\t\t\t\tif (state.readyResolve) {\n\t\t\t\t\tstate.readyResolve();\n\t\t\t\t\tstate.readyResolve = null;\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tstate.isReconciling = false;\n\n\t\t\t// Schedule next reconcile BEFORE notifying settlement change,\n\t\t\t// so listeners never see a brief isSettled=true flash when\n\t\t\t// more changes are pending.\n\t\t\tif (state.changedKeys.size > 0) {\n\t\t\t\tscheduleReconcile();\n\t\t\t} else if (!state.reconcileScheduled) {\n\t\t\t\t// System has settled — reset depth counter\n\t\t\t\treconcileDepth = 0;\n\t\t\t}\n\n\t\t\tnotifySettlementChange();\n\t\t}\n\t}\n\n\t// Create typed derive accessor using a Proxy\n\tconst deriveAccessor = new Proxy({} as Record<string, unknown>, {\n\t\tget(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\t\t\treturn derivationsManager.get(prop as keyof DerivationsDef<S>);\n\t\t},\n\t\thas(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\t\t\treturn prop in mergedDerive;\n\t\t},\n\t\townKeys() {\n\t\t\treturn Object.keys(mergedDerive);\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\t\t\tif (prop in mergedDerive) {\n\t\t\t\treturn { configurable: true, enumerable: true };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n\n\t// Create typed events accessor using a Proxy\n\t// This provides system.events.eventName(payload) syntax\n\tconst eventsAccessor = new Proxy({} as Record<string, (payload?: Record<string, unknown>) => void>, {\n\t\tget(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\t\t\t// Return a function that dispatches the event\n\t\t\treturn (payload?: Record<string, unknown>) => {\n\t\t\t\tconst handler = mergedEvents[prop];\n\t\t\t\tif (handler) {\n\t\t\t\t\tstore.batch(() => {\n\t\t\t\t\t\thandler(facts, { type: prop, ...payload });\n\t\t\t\t\t});\n\t\t\t\t} else if (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] Unknown event type \"${prop}\". ` +\n\t\t\t\t\t\t\t`No handler is registered for this event. ` +\n\t\t\t\t\t\t\t`Available events: ${Object.keys(mergedEvents).join(\", \") || \"(none)\"}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\thas(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\t\t\treturn prop in mergedEvents;\n\t\t},\n\t\townKeys() {\n\t\t\treturn Object.keys(mergedEvents);\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\t\t\tif (prop in mergedEvents) {\n\t\t\t\treturn { configurable: true, enumerable: true };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n\n\t// Create the system interface\n\t// biome-ignore lint/suspicious/noExplicitAny: Engine uses flat schema internally, public API uses ModuleSchema\n\tconst system: System<any> = {\n\t\tfacts,\n\t\tdebug: timeTravelManager.isEnabled ? timeTravelManager : null,\n\t\tderive: deriveAccessor,\n\t\tevents: eventsAccessor,\n\t\tconstraints: {\n\t\t\tdisable: (id: string) => constraintsManager.disable(id),\n\t\t\tenable: (id: string) => constraintsManager.enable(id),\n\t\t},\n\t\teffects: {\n\t\t\tdisable: (id: string) => effectsManager.disable(id),\n\t\t\tenable: (id: string) => effectsManager.enable(id),\n\t\t\tisEnabled: (id: string) => effectsManager.isEnabled(id),\n\t\t},\n\n\t\tstart(): void {\n\t\t\tif (state.isRunning) return;\n\t\t\tstate.isRunning = true;\n\n\t\t\t// Mark as initializing to suppress reconciliation during module init\n\t\t\tstate.isInitializing = true;\n\n\t\t\t// Initialize modules (reconciliation is suppressed during this phase)\n\t\t\tfor (const module of config.modules) {\n\t\t\t\tif (module.init) {\n\t\t\t\t\tstore.batch(() => {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Engine internal type coercion\n\t\t\t\t\t\tmodule.init!(facts as any);\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Call module hooks\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Engine internal type coercion\n\t\t\t\tmodule.hooks?.onStart?.(system as any);\n\t\t\t}\n\n\t\t\t// Apply initialFacts/hydrate via callback (still in init phase)\n\t\t\t// This ensures initialFacts are applied AFTER module init but BEFORE reconcile\n\t\t\tif (config.onAfterModuleInit) {\n\t\t\t\tstore.batch(() => {\n\t\t\t\t\tconfig.onAfterModuleInit!();\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Mark initialization complete\n\t\t\tstate.isInitializing = false;\n\t\t\tstate.isInitialized = true;\n\n\t\t\t// Emit start event\n\t\t\tpluginManager.emitStart(system);\n\n\t\t\t// Initial reconcile (now that all modules are initialized)\n\t\t\tscheduleReconcile();\n\t\t},\n\n\t\tstop(): void {\n\t\t\tif (!state.isRunning) return;\n\t\t\tstate.isRunning = false;\n\n\t\t\t// Cancel all resolvers\n\t\t\tresolversManager.cancelAll();\n\n\t\t\t// Run all effect cleanups\n\t\t\teffectsManager.cleanupAll();\n\n\t\t\t// Call module hooks\n\t\t\tfor (const module of config.modules) {\n\t\t\t\tmodule.hooks?.onStop?.(system);\n\t\t\t}\n\n\t\t\t// Emit stop event\n\t\t\tpluginManager.emitStop(system);\n\t\t},\n\n\t\tdestroy(): void {\n\t\t\tthis.stop();\n\t\t\tstate.isDestroyed = true;\n\t\t\tsettlementListeners.clear();\n\t\t\ttimeTravelListeners.clear();\n\t\t\tpluginManager.emitDestroy(system);\n\t\t},\n\n\t\tdispatch(event: SystemEvent): void {\n\t\t\tif (BLOCKED_PROPS.has(event.type)) return;\n\t\t\tconst handler = mergedEvents[event.type];\n\t\t\tif (handler) {\n\t\t\t\tstore.batch(() => {\n\t\t\t\t\thandler(facts, event);\n\t\t\t\t});\n\t\t\t} else if (process.env.NODE_ENV !== \"production\") {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] Unknown event type \"${event.type}\". ` +\n\t\t\t\t\t\t`No handler is registered for this event. ` +\n\t\t\t\t\t\t`Available events: ${Object.keys(mergedEvents).join(\", \") || \"(none)\"}`,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\n\t\tread<T = unknown>(derivationId: string): T {\n\t\t\treturn derivationsManager.get(derivationId as keyof DerivationsDef<S>) as T;\n\t\t},\n\n\t\tsubscribe(ids: string[], listener: () => void): () => void {\n\t\t\tconst derivationIds: string[] = [];\n\t\t\tconst factKeys: string[] = [];\n\n\t\t\tfor (const id of ids) {\n\t\t\t\tif (id in mergedDerive) {\n\t\t\t\t\tderivationIds.push(id);\n\t\t\t\t} else if (id in mergedSchema) {\n\t\t\t\t\tfactKeys.push(id);\n\t\t\t\t} else if (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(`[Directive] subscribe: unknown key \"${id}\"`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst unsubs: Array<() => void> = [];\n\t\t\tif (derivationIds.length > 0) {\n\t\t\t\tunsubs.push(\n\t\t\t\t\tderivationsManager.subscribe(\n\t\t\t\t\t\tderivationIds as Array<keyof DerivationsDef<S>>,\n\t\t\t\t\t\tlistener,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (factKeys.length > 0) {\n\t\t\t\tunsubs.push(store.subscribe(factKeys as Array<keyof InferSchema<S>>, listener));\n\t\t\t}\n\n\t\t\treturn () => {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t};\n\t\t},\n\n\t\twatch<T = unknown>(\n\t\t\tid: string,\n\t\t\tcallback: (newValue: T, previousValue: T | undefined) => void,\n\t\t\toptions?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n\t\t): () => void {\n\t\t\tconst isEqual = options?.equalityFn\n\t\t\t\t? (a: T, b: T | undefined) => options.equalityFn!(a, b)\n\t\t\t\t: (a: T, b: T | undefined) => Object.is(a, b);\n\n\t\t\tif (id in mergedDerive) {\n\t\t\t\t// Derivation path\n\t\t\t\tlet previousValue: T | undefined = derivationsManager.get(\n\t\t\t\t\tid as keyof DerivationsDef<S>,\n\t\t\t\t) as T | undefined;\n\n\t\t\t\treturn derivationsManager.subscribe(\n\t\t\t\t\t[id as keyof DerivationsDef<S>],\n\t\t\t\t\t() => {\n\t\t\t\t\t\tconst newValue = derivationsManager.get(id as keyof DerivationsDef<S>) as T;\n\t\t\t\t\t\tif (!isEqual(newValue, previousValue)) {\n\t\t\t\t\t\t\tconst oldValue = previousValue;\n\t\t\t\t\t\t\tpreviousValue = newValue;\n\t\t\t\t\t\t\tcallback(newValue, oldValue);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Fact path\n\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\tif (!(id in mergedSchema)) {\n\t\t\t\t\tconsole.warn(`[Directive] watch: unknown key \"${id}\"`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet prev = store.get(id as keyof InferSchema<S>) as T | undefined;\n\t\t\treturn store.subscribe([id as keyof InferSchema<S>], () => {\n\t\t\t\tconst next = store.get(id as keyof InferSchema<S>) as T;\n\t\t\t\tif (!isEqual(next, prev)) {\n\t\t\t\t\tconst old = prev;\n\t\t\t\t\tprev = next;\n\t\t\t\t\tcallback(next, old);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\twhen(\n\t\t\tpredicate: (facts: Record<string, unknown>) => boolean,\n\t\t\toptions?: { timeout?: number },\n\t\t): Promise<void> {\n\t\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\t\t// Check immediately\n\t\t\t\tconst factsObj = store.toObject();\n\t\t\t\tif (predicate(factsObj)) {\n\t\t\t\t\tresolve();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet unsub: (() => void) | undefined;\n\t\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\n\t\t\t\tconst cleanup = () => {\n\t\t\t\t\tunsub?.();\n\t\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\t};\n\n\t\t\t\t// Subscribe to all fact changes\n\t\t\t\tunsub = store.subscribeAll(() => {\n\t\t\t\t\tconst current = store.toObject();\n\t\t\t\t\tif (predicate(current)) {\n\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Timeout\n\t\t\t\tif (options?.timeout !== undefined && options.timeout > 0) {\n\t\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\treject(new Error(`[Directive] when: timed out after ${options.timeout}ms`));\n\t\t\t\t\t}, options.timeout);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\tinspect(): SystemInspection {\n\t\t\treturn {\n\t\t\t\tunmet: state.previousRequirements.all(),\n\t\t\t\tinflight: resolversManager.getInflightInfo(),\n\t\t\t\tconstraints: constraintsManager.getAllStates().map((s) => ({\n\t\t\t\t\tid: s.id,\n\t\t\t\t\tactive: s.lastResult ?? false,\n\t\t\t\t\tpriority: s.priority,\n\t\t\t\t})),\n\t\t\t\tresolvers: Object.fromEntries(\n\t\t\t\t\tresolversManager.getInflight().map((id) => [id, resolversManager.getStatus(id)]),\n\t\t\t\t),\n\t\t\t};\n\t\t},\n\n\t\texplain(requirementId: string): string | null {\n\t\t\t// Find the requirement in current unmet requirements\n\t\t\tconst requirements = state.previousRequirements.all();\n\t\t\tconst req = requirements.find((r) => r.id === requirementId);\n\n\t\t\tif (!req) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst constraintState = constraintsManager.getState(req.fromConstraint);\n\t\t\tconst resolverStatus = resolversManager.getStatus(requirementId);\n\n\t\t\t// Get relevant facts by looking at the constraint's last known state\n\t\t\tconst relevantFacts: Record<string, unknown> = {};\n\t\t\tconst factsSnapshot = store.toObject();\n\n\t\t\t// Include all facts for now (could be optimized with dependency tracking)\n\t\t\tfor (const [key, value] of Object.entries(factsSnapshot)) {\n\t\t\t\trelevantFacts[key] = value;\n\t\t\t}\n\n\t\t\tconst lines: string[] = [\n\t\t\t\t`Requirement \"${req.requirement.type}\" (id: ${req.id})`,\n\t\t\t\t`├─ Produced by constraint: ${req.fromConstraint}`,\n\t\t\t\t`├─ Constraint priority: ${constraintState?.priority ?? 0}`,\n\t\t\t\t`├─ Constraint active: ${constraintState?.lastResult ?? \"unknown\"}`,\n\t\t\t\t`├─ Resolver status: ${resolverStatus.state}`,\n\t\t\t];\n\n\t\t\t// Add requirement details\n\t\t\tconst reqDetails = Object.entries(req.requirement)\n\t\t\t\t.filter(([k]) => k !== \"type\")\n\t\t\t\t.map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n\t\t\t\t.join(\", \");\n\t\t\tif (reqDetails) {\n\t\t\t\tlines.push(`├─ Requirement payload: { ${reqDetails} }`);\n\t\t\t}\n\n\t\t\t// Add relevant facts (limit to prevent huge output)\n\t\t\tconst factEntries = Object.entries(relevantFacts).slice(0, 10);\n\t\t\tif (factEntries.length > 0) {\n\t\t\t\tlines.push(`└─ Relevant facts:`);\n\t\t\t\tfactEntries.forEach(([k, v], i) => {\n\t\t\t\t\tconst prefix = i === factEntries.length - 1 ? \" └─\" : \" ├─\";\n\t\t\t\t\tconst valueStr = typeof v === \"object\" ? JSON.stringify(v) : String(v);\n\t\t\t\t\tlines.push(`${prefix} ${k} = ${valueStr.slice(0, 50)}${valueStr.length > 50 ? \"...\" : \"\"}`);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn lines.join(\"\\n\");\n\t\t},\n\n\t\tasync settle(maxWait = 5000): Promise<void> {\n\t\t\tconst startTime = Date.now();\n\n\t\t\t// Use while loop instead of recursion to prevent stack overflow\n\t\t\twhile (true) {\n\t\t\t\t// Wait for any pending microtasks\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 0));\n\n\t\t\t\t// Check if we have inflight resolvers or unmet requirements with resolvers\n\t\t\t\tconst inspection = this.inspect();\n\t\t\t\tconst settled =\n\t\t\t\t\tinspection.inflight.length === 0 &&\n\t\t\t\t\t!state.isReconciling &&\n\t\t\t\t\t!state.reconcileScheduled;\n\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Check timeout\n\t\t\t\tif (Date.now() - startTime > maxWait) {\n\t\t\t\t\tconst details: string[] = [];\n\t\t\t\t\tif (inspection.inflight.length > 0) {\n\t\t\t\t\t\tdetails.push(\n\t\t\t\t\t\t\t`${inspection.inflight.length} resolvers inflight: ${inspection.inflight.map((r) => r.resolverId).join(\", \")}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (state.isReconciling) {\n\t\t\t\t\t\tdetails.push(\"reconciliation in progress\");\n\t\t\t\t\t}\n\t\t\t\t\tif (state.reconcileScheduled) {\n\t\t\t\t\t\tdetails.push(\"reconcile scheduled\");\n\t\t\t\t\t}\n\t\t\t\t\t// Include pending requirements for better debugging\n\t\t\t\t\tconst unmet = state.previousRequirements.all();\n\t\t\t\t\tif (unmet.length > 0) {\n\t\t\t\t\t\tdetails.push(\n\t\t\t\t\t\t\t`${unmet.length} unmet requirements: ${unmet.map((r) => r.requirement.type).join(\", \")}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] settle() timed out after ${maxWait}ms. ${details.join(\"; \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Wait a bit and check again\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 10));\n\t\t\t}\n\t\t},\n\n\t\tgetSnapshot() {\n\t\t\treturn {\n\t\t\t\tfacts: store.toObject(),\n\t\t\t\tversion: 1,\n\t\t\t};\n\t\t},\n\n\t\tgetDistributableSnapshot<T = Record<string, unknown>>(\n\t\t\toptions: {\n\t\t\t\tincludeDerivations?: string[];\n\t\t\t\texcludeDerivations?: string[];\n\t\t\t\tincludeFacts?: string[];\n\t\t\t\tttlSeconds?: number;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t\tincludeVersion?: boolean;\n\t\t\t} = {},\n\t\t): {\n\t\t\tdata: T;\n\t\t\tcreatedAt: number;\n\t\t\texpiresAt?: number;\n\t\t\tversion?: string;\n\t\t\tmetadata?: Record<string, unknown>;\n\t\t} {\n\t\t\tconst {\n\t\t\t\tincludeDerivations,\n\t\t\t\texcludeDerivations,\n\t\t\t\tincludeFacts,\n\t\t\t\tttlSeconds,\n\t\t\t\tmetadata,\n\t\t\t\tincludeVersion,\n\t\t\t} = options;\n\n\t\t\tconst data: Record<string, unknown> = {};\n\n\t\t\t// Collect derivation keys to include\n\t\t\tconst allDerivationKeys = Object.keys(mergedDerive);\n\t\t\tlet derivationKeys: string[];\n\n\t\t\tif (includeDerivations) {\n\t\t\t\t// Only include specified derivations\n\t\t\t\tderivationKeys = includeDerivations.filter((k) => allDerivationKeys.includes(k));\n\n\t\t\t\t// Warn about unknown derivation keys in dev mode\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconst unknown = includeDerivations.filter((k) => !allDerivationKeys.includes(k));\n\t\t\t\t\tif (unknown.length > 0) {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[Directive] getDistributableSnapshot: Unknown derivation keys ignored: ${unknown.join(\", \")}. ` +\n\t\t\t\t\t\t\t\t`Available: ${allDerivationKeys.join(\", \") || \"(none)\"}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Include all derivations by default\n\t\t\t\tderivationKeys = allDerivationKeys;\n\t\t\t}\n\n\t\t\t// Apply exclusions\n\t\t\tif (excludeDerivations) {\n\t\t\t\tconst excludeSet = new Set(excludeDerivations);\n\t\t\t\tderivationKeys = derivationKeys.filter((k) => !excludeSet.has(k));\n\t\t\t}\n\n\t\t\t// Read derivation values\n\t\t\tfor (const key of derivationKeys) {\n\t\t\t\ttry {\n\t\t\t\t\tdata[key] = derivationsManager.get(key as keyof DerivationsDef<S>);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Skip derivations that error during computation\n\t\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\t\tconsole.warn(`[Directive] getDistributableSnapshot: Skipping derivation \"${key}\" due to error:`, error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Include specified facts\n\t\t\tif (includeFacts && includeFacts.length > 0) {\n\t\t\t\tconst factsSnapshot = store.toObject();\n\t\t\t\tconst allFactKeys = Object.keys(factsSnapshot);\n\n\t\t\t\t// Warn about unknown fact keys in dev mode\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconst unknown = includeFacts.filter((k) => !(k in factsSnapshot));\n\t\t\t\t\tif (unknown.length > 0) {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[Directive] getDistributableSnapshot: Unknown fact keys ignored: ${unknown.join(\", \")}. ` +\n\t\t\t\t\t\t\t\t`Available: ${allFactKeys.join(\", \") || \"(none)\"}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (const key of includeFacts) {\n\t\t\t\t\tif (key in factsSnapshot) {\n\t\t\t\t\t\tdata[key] = factsSnapshot[key];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Build the snapshot\n\t\t\tconst createdAt = Date.now();\n\t\t\tconst snapshot: {\n\t\t\t\tdata: T;\n\t\t\t\tcreatedAt: number;\n\t\t\t\texpiresAt?: number;\n\t\t\t\tversion?: string;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t} = {\n\t\t\t\tdata: data as T,\n\t\t\t\tcreatedAt,\n\t\t\t};\n\n\t\t\t// Add TTL\n\t\t\tif (ttlSeconds !== undefined && ttlSeconds > 0) {\n\t\t\t\tsnapshot.expiresAt = createdAt + ttlSeconds * 1000;\n\t\t\t}\n\n\t\t\t// Add version hash\n\t\t\tif (includeVersion) {\n\t\t\t\t// Simple version hash based on data content\n\t\t\t\tsnapshot.version = hashObject(data);\n\t\t\t}\n\n\t\t\t// Add metadata\n\t\t\tif (metadata) {\n\t\t\t\tsnapshot.metadata = metadata;\n\t\t\t}\n\n\t\t\treturn snapshot;\n\t\t},\n\n\t\twatchDistributableSnapshot<T = Record<string, unknown>>(\n\t\t\toptions: {\n\t\t\t\tincludeDerivations?: string[];\n\t\t\t\texcludeDerivations?: string[];\n\t\t\t\tincludeFacts?: string[];\n\t\t\t\tttlSeconds?: number;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t\tincludeVersion?: boolean;\n\t\t\t},\n\t\t\tcallback: (snapshot: {\n\t\t\t\tdata: T;\n\t\t\t\tcreatedAt: number;\n\t\t\t\texpiresAt?: number;\n\t\t\t\tversion?: string;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t}) => void,\n\t\t): () => void {\n\t\t\tconst { includeDerivations, excludeDerivations } = options;\n\n\t\t\t// Determine which derivations to watch\n\t\t\tconst allDerivationKeys = Object.keys(mergedDerive);\n\t\t\tlet derivationKeys: string[];\n\n\t\t\tif (includeDerivations) {\n\t\t\t\tderivationKeys = includeDerivations.filter((k) => allDerivationKeys.includes(k));\n\t\t\t} else {\n\t\t\t\tderivationKeys = allDerivationKeys;\n\t\t\t}\n\n\t\t\tif (excludeDerivations) {\n\t\t\t\tconst excludeSet = new Set(excludeDerivations);\n\t\t\t\tderivationKeys = derivationKeys.filter((k) => !excludeSet.has(k));\n\t\t\t}\n\n\t\t\tif (derivationKeys.length === 0) {\n\t\t\t\t// Nothing to watch, return no-op unsubscribe\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\"[Directive] watchDistributableSnapshot: No derivations to watch. \" +\n\t\t\t\t\t\t\t\"Callback will never be called.\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn () => {};\n\t\t\t}\n\n\t\t\t// Get initial snapshot to seed version and ensure derivations are computed\n\t\t\t// (derivations must be computed before subscribing so listeners are called on invalidation)\n\t\t\tconst initialSnapshot = this.getDistributableSnapshot<T>({\n\t\t\t\t...options,\n\t\t\t\tincludeVersion: true,\n\t\t\t});\n\t\t\tlet previousVersion = initialSnapshot.version;\n\n\t\t\t// Subscribe to all watched derivations\n\t\t\treturn derivationsManager.subscribe(\n\t\t\t\tderivationKeys as Array<keyof DerivationsDef<S>>,\n\t\t\t\t() => {\n\t\t\t\t\t// Generate a new snapshot\n\t\t\t\t\tconst snapshot = this.getDistributableSnapshot<T>({\n\t\t\t\t\t\t...options,\n\t\t\t\t\t\t// Always include version for change detection\n\t\t\t\t\t\tincludeVersion: true,\n\t\t\t\t\t});\n\n\t\t\t\t\t// Only call callback if snapshot actually changed\n\t\t\t\t\tif (snapshot.version !== previousVersion) {\n\t\t\t\t\t\tpreviousVersion = snapshot.version;\n\t\t\t\t\t\tcallback(snapshot);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\n\t\trestore(snapshot) {\n\t\t\tif (!snapshot || typeof snapshot !== \"object\") {\n\t\t\t\tthrow new Error(\"[Directive] restore() requires a valid snapshot object\");\n\t\t\t}\n\t\t\tif (!snapshot.facts || typeof snapshot.facts !== \"object\") {\n\t\t\t\tthrow new Error(\"[Directive] restore() snapshot must have a facts object\");\n\t\t\t}\n\n\t\t\t// Security: Validate snapshot for prototype pollution\n\t\t\tif (!isPrototypeSafe(snapshot)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"[Directive] restore() rejected: snapshot contains potentially dangerous keys \" +\n\t\t\t\t\t\t\"(__proto__, constructor, or prototype). This may indicate a prototype pollution attack.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tstore.batch(() => {\n\t\t\t\tfor (const [key, value] of Object.entries(snapshot.facts)) {\n\t\t\t\t\t// Skip dangerous keys (defense in depth)\n\t\t\t\t\tif (BLOCKED_PROPS.has(key)) continue;\n\t\t\t\t\tstore.set(key as keyof InferSchema<S>, value as InferSchema<S>[keyof InferSchema<S>]);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\tonSettledChange(listener: () => void): () => void {\n\t\t\tsettlementListeners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tsettlementListeners.delete(listener);\n\t\t\t};\n\t\t},\n\n\t\tonTimeTravelChange(listener: () => void): () => void {\n\t\t\ttimeTravelListeners.add(listener);\n\t\t\treturn () => {\n\t\t\t\ttimeTravelListeners.delete(listener);\n\t\t\t};\n\t\t},\n\n\t\tbatch(fn: () => void): void {\n\t\t\tstore.batch(fn);\n\t\t},\n\n\t\tget isSettled(): boolean {\n\t\t\tconst inspection = this.inspect();\n\t\t\treturn (\n\t\t\t\tinspection.inflight.length === 0 &&\n\t\t\t\t!state.isReconciling &&\n\t\t\t\t!state.reconcileScheduled\n\t\t\t);\n\t\t},\n\n\t\tget isRunning(): boolean {\n\t\t\treturn state.isRunning;\n\t\t},\n\n\t\tget isInitialized(): boolean {\n\t\t\treturn state.isInitialized;\n\t\t},\n\n\t\tget isReady(): boolean {\n\t\t\treturn state.isReady;\n\t\t},\n\n\t\twhenReady(): Promise<void> {\n\t\t\t// If already ready, resolve immediately\n\t\t\tif (state.isReady) {\n\t\t\t\treturn Promise.resolve();\n\t\t\t}\n\n\t\t\t// If not running, the promise would never resolve\n\t\t\tif (!state.isRunning) {\n\t\t\t\treturn Promise.reject(\n\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\"[Directive] whenReady() called before start(). \" +\n\t\t\t\t\t\t\"Call system.start() first, then await system.whenReady().\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Create promise if not exists\n\t\t\tif (!state.readyPromise) {\n\t\t\t\tstate.readyPromise = new Promise<void>((resolve) => {\n\t\t\t\t\tstate.readyResolve = resolve;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn state.readyPromise;\n\t\t},\n\t};\n\n\t/**\n\t * Register a new module into a running (or stopped) engine.\n\t * Merges the module's schema, events, derive, effects, constraints, and resolvers\n\t * into the existing engine state, runs init, and triggers reconciliation.\n\t */\n\tfunction registerModule(module: {\n\t\tid: string;\n\t\tschema: Record<string, unknown>;\n\t\trequirements?: Record<string, unknown>;\n\t\tinit?: (facts: unknown) => void;\n\t\tderive?: Record<string, (facts: unknown, derive: unknown) => unknown>;\n\t\tevents?: Record<string, (facts: unknown, event: unknown) => void>;\n\t\teffects?: Record<string, unknown>;\n\t\tconstraints?: Record<string, unknown>;\n\t\tresolvers?: Record<string, unknown>;\n\t\thooks?: { onInit?: (s: unknown) => void; onStart?: (s: unknown) => void; onStop?: (s: unknown) => void; onError?: (e: unknown, ctx: unknown) => void };\n\t}): void {\n\t\t// Guard: cannot register during reconciliation (would corrupt iteration state)\n\t\tif (state.isReconciling) {\n\t\t\tthrow new Error(\n\t\t\t\t`[Directive] Cannot register module \"${module.id}\" during reconciliation. ` +\n\t\t\t\t`Wait for the current reconciliation cycle to complete.`,\n\t\t\t);\n\t\t}\n\n\t\t// Guard: cannot register on a destroyed system\n\t\tif (state.isDestroyed) {\n\t\t\tthrow new Error(\n\t\t\t\t`[Directive] Cannot register module \"${module.id}\" on a destroyed system.`,\n\t\t\t);\n\t\t}\n\n\t\t// Security: validate keys\n\t\tconst validateKeys = (obj: object | undefined, section: string) => {\n\t\t\tif (!obj) return;\n\t\t\tfor (const key of Object.keys(obj)) {\n\t\t\t\tif (BLOCKED_PROPS.has(key)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Security: Module \"${module.id}\" has dangerous key \"${key}\" in ${section}.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tvalidateKeys(module.schema, \"schema\");\n\t\tvalidateKeys(module.events, \"events\");\n\t\tvalidateKeys(module.derive, \"derive\");\n\t\tvalidateKeys(module.effects, \"effects\");\n\t\tvalidateKeys(module.constraints, \"constraints\");\n\t\tvalidateKeys(module.resolvers, \"resolvers\");\n\n\t\t// Schema collision detection (unconditional — production collision would cause data corruption)\n\t\tfor (const key of Object.keys(module.schema)) {\n\t\t\tif (key in mergedSchema) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Schema collision: Fact \"${key}\" already exists. Cannot register module \"${module.id}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\t// Fact/derivation name collision check (dev-only warning)\n\t\tif (process.env.NODE_ENV !== \"production\" && module.derive) {\n\t\t\tconst existingFactKeys = new Set(Object.keys(mergedSchema));\n\t\t\tfor (const key of Object.keys(module.derive)) {\n\t\t\t\tif (existingFactKeys.has(key)) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] \"${key}\" exists as both a fact and a derivation after registering module \"${module.id}\".`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Merge into existing engine state\n\t\tObject.assign(mergedSchema, module.schema);\n\t\tif (module.events) Object.assign(mergedEvents, module.events);\n\t\tif (module.derive) {\n\t\t\tObject.assign(mergedDerive, module.derive);\n\t\t\t// Register new derivations with the derivations manager\n\t\t\tderivationsManager.registerDefinitions(module.derive as DerivationsDef<S>);\n\t\t}\n\t\tif (module.effects) {\n\t\t\tObject.assign(mergedEffects, module.effects);\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic module registration\n\t\t\teffectsManager.registerDefinitions(module.effects as any);\n\t\t}\n\t\tif (module.constraints) {\n\t\t\tObject.assign(mergedConstraints, module.constraints);\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic module registration\n\t\t\tconstraintsManager.registerDefinitions(module.constraints as any);\n\t\t}\n\t\tif (module.resolvers) {\n\t\t\tObject.assign(mergedResolvers, module.resolvers);\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic module registration\n\t\t\tresolversManager.registerDefinitions(module.resolvers as any);\n\t\t}\n\n\t\t// Register new schema keys with the facts store\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal dynamic method\n\t\t(store as any).registerKeys(module.schema as Record<string, unknown>);\n\n\t\t// Track the new module in config.modules for hooks\n\t\tconfig.modules.push(module as typeof config.modules[number]);\n\n\t\t// Run init within a batch\n\t\tif (module.init) {\n\t\t\tstore.batch(() => {\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic module init\n\t\t\t\tmodule.init!(facts as any);\n\t\t\t});\n\t\t}\n\n\t\t// Call lifecycle hooks\n\t\tmodule.hooks?.onInit?.(system);\n\t\tif (state.isRunning) {\n\t\t\tmodule.hooks?.onStart?.(system);\n\t\t\t// Trigger reconciliation to evaluate new constraints\n\t\t\tscheduleReconcile();\n\t\t}\n\t}\n\n\t// Attach registerModule to system\n\t(system as unknown as Record<string, unknown>).registerModule = registerModule;\n\n\t// Initialize plugins\n\tpluginManager.emitInit(system);\n\n\t// Call module init hooks\n\tfor (const module of config.modules) {\n\t\tmodule.hooks?.onInit?.(system);\n\t}\n\n\treturn system;\n}\n","/**\n * System - The top-level API for creating a Directive runtime\n *\n * A system combines modules with plugins and configuration.\n * Modules are passed as an object with namespaced access:\n *\n * @example\n * ```typescript\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n *\n * system.facts.auth.token // Namespaced facts\n * system.derive.data.userCount // Namespaced derivations\n * system.events.auth.login() // Namespaced events\n * ```\n */\n\nimport { createEngine } from \"./engine.js\";\nimport { isPrototypeSafe } from \"../utils/utils.js\";\nimport type {\n\tModuleDef,\n\tModuleSchema,\n\tModulesMap,\n\tNamespacedSystem,\n\tCreateSystemOptionsNamed,\n\tCreateSystemOptionsSingle,\n\tSingleModuleSystem,\n} from \"./types.js\";\n\n// ============================================================================\n// Blocked Properties (Security)\n// ============================================================================\n\nconst BLOCKED_PROPS = Object.freeze(\n\tnew Set([\"__proto__\", \"constructor\", \"prototype\"]),\n);\n\n/** Namespace separator for internal key prefixing (e.g., \"auth::token\") */\nconst SEPARATOR = \"::\";\n\n// ============================================================================\n// Topological Sort for Module Dependencies\n// ============================================================================\n\n/**\n * Perform topological sort on modules based on crossModuleDeps.\n * Returns module namespaces in dependency order (dependencies first).\n *\n * @throws Error if circular dependency detected\n */\nfunction topologicalSort<Modules extends ModulesMap>(\n\tmodulesMap: Modules,\n): Array<keyof Modules & string> {\n\tconst namespaces = Object.keys(modulesMap) as Array<keyof Modules & string>;\n\tconst visited = new Set<string>();\n\tconst visiting = new Set<string>(); // For cycle detection\n\tconst result: Array<keyof Modules & string> = [];\n\tconst path: string[] = []; // Reuse array to avoid O(n²) memory\n\n\tfunction visit(namespace: string): void {\n\t\tif (visited.has(namespace)) return;\n\n\t\t// Cycle detection\n\t\tif (visiting.has(namespace)) {\n\t\t\tconst cycleStart = path.indexOf(namespace);\n\t\t\tconst cycle = [...path.slice(cycleStart), namespace].join(\" → \");\n\t\t\tthrow new Error(\n\t\t\t\t`[Directive] Circular dependency detected: ${cycle}. ` +\n\t\t\t\t`Modules cannot have circular crossModuleDeps. ` +\n\t\t\t\t`Break the cycle by removing one of the cross-module references.`,\n\t\t\t);\n\t\t}\n\n\t\tvisiting.add(namespace);\n\t\tpath.push(namespace);\n\n\t\t// Visit dependencies first\n\t\tconst mod = modulesMap[namespace];\n\t\tif (mod?.crossModuleDeps) {\n\t\t\tfor (const depNamespace of Object.keys(mod.crossModuleDeps)) {\n\t\t\t\tif (namespaces.includes(depNamespace as keyof Modules & string)) {\n\t\t\t\t\tvisit(depNamespace);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpath.pop();\n\t\tvisiting.delete(namespace);\n\t\tvisited.add(namespace);\n\t\tresult.push(namespace as keyof Modules & string);\n\t}\n\n\tfor (const namespace of namespaces) {\n\t\tvisit(namespace);\n\t}\n\n\treturn result;\n}\n\n// ============================================================================\n// Proxy Cache (Performance)\n// ============================================================================\n\n/**\n * WeakMap to cache module facts proxies. Keyed by the facts store object.\n * Inner map is keyed by namespace string.\n */\nconst moduleFactsProxyCache = new WeakMap<\n\tRecord<string, unknown>,\n\tMap<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache namespaced facts proxies.\n */\nconst namespacedFactsProxyCache = new WeakMap<\n\tRecord<string, unknown>,\n\tRecord<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache namespaced derive proxies.\n */\nconst namespacedDeriveProxyCache = new WeakMap<\n\tRecord<string, unknown>,\n\tRecord<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache module derive proxies.\n */\nconst moduleDeriveProxyCache = new WeakMap<\n\tRecord<string, unknown>,\n\tMap<string, Record<string, unknown>>\n>();\n\n// ============================================================================\n// createSystem\n// ============================================================================\n\n/**\n * Create a Directive system.\n *\n * Supports two modes:\n * - **Single module**: Use `module` prop for direct access without namespace\n * - **Multiple modules**: Use `modules` prop for namespaced access\n *\n * @example Single module (direct access)\n * ```ts\n * const system = createSystem({ module: counterModule });\n * system.facts.count // Direct access\n * system.events.increment() // Direct events\n * ```\n *\n * @example Multiple modules (namespaced access)\n * ```ts\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n * system.facts.auth.token // Namespaced access\n * system.events.auth.login() // Namespaced events\n * ```\n */\nexport function createSystem<S extends ModuleSchema>(\n\toptions: CreateSystemOptionsSingle<S>,\n): SingleModuleSystem<S>;\nexport function createSystem<const Modules extends ModulesMap>(\n\toptions: CreateSystemOptionsNamed<Modules>,\n): NamespacedSystem<Modules>;\nexport function createSystem<S extends ModuleSchema, Modules extends ModulesMap>(\n\toptions: CreateSystemOptionsSingle<S> | CreateSystemOptionsNamed<Modules>,\n): SingleModuleSystem<S> | NamespacedSystem<Modules> {\n\t// Single module mode (module prop)\n\tif (\"module\" in options) {\n\t\tif (!options.module) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[Directive] createSystem requires a module. Got: \" + typeof options.module,\n\t\t\t);\n\t\t}\n\t\treturn createSingleModuleSystem(options as CreateSystemOptionsSingle<S>) as SingleModuleSystem<S>;\n\t}\n\n\t// Namespaced mode (modules prop)\n\tconst namedOptions = options as CreateSystemOptionsNamed<Modules>;\n\n\t// Validate not an array\n\tif (Array.isArray(namedOptions.modules)) {\n\t\tthrow new Error(\n\t\t\t`[Directive] createSystem expects modules as an object, not an array.\\n\\n` +\n\t\t\t`Instead of:\\n` +\n\t\t\t` createSystem({ modules: [authModule, dataModule] })\\n\\n` +\n\t\t\t`Use:\\n` +\n\t\t\t` createSystem({ modules: { auth: authModule, data: dataModule } })\\n\\n` +\n\t\t\t`Or for a single module:\\n` +\n\t\t\t` createSystem({ module: counterModule })`,\n\t\t);\n\t}\n\n\treturn createNamespacedSystem(namedOptions) as NamespacedSystem<Modules>;\n}\n\n// ============================================================================\n// Internal Implementation\n// ============================================================================\n\nfunction createNamespacedSystem<Modules extends ModulesMap>(\n\toptions: CreateSystemOptionsNamed<Modules>,\n): NamespacedSystem<Modules> {\n\tconst modulesMap = options.modules;\n\tconst moduleNamespaces = new Set(Object.keys(modulesMap));\n\n\t// Validate tickMs if provided\n\tif (options.tickMs !== undefined && options.tickMs <= 0) {\n\t\tthrow new Error(\"[Directive] tickMs must be a positive number\");\n\t}\n\n\t// Dev-mode: Validate crossModuleDeps reference existing modules\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tfor (const [namespace, mod] of Object.entries(modulesMap)) {\n\t\t\tif (mod.crossModuleDeps) {\n\t\t\t\tfor (const depNamespace of Object.keys(mod.crossModuleDeps)) {\n\t\t\t\t\tif (depNamespace === namespace) {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[Directive] Module \"${namespace}\" references itself in crossModuleDeps. ` +\n\t\t\t\t\t\t\t`Use \"facts.self\" to access own module's facts instead.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (!moduleNamespaces.has(depNamespace)) {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[Directive] Module \"${namespace}\" declares crossModuleDeps.${depNamespace}, ` +\n\t\t\t\t\t\t\t`but no module with namespace \"${depNamespace}\" exists in the system. ` +\n\t\t\t\t\t\t\t`Available modules: ${[...moduleNamespaces].join(\", \")}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Determine module initialization order\n\tlet orderedNamespaces: Array<keyof Modules & string>;\n\tconst initOrder = options.initOrder ?? \"auto\";\n\n\tif (Array.isArray(initOrder)) {\n\t\t// Explicit order provided - validate it includes all modules\n\t\tconst explicitOrder = initOrder as Array<keyof Modules & string>;\n\t\tconst missingModules = Object.keys(modulesMap).filter(\n\t\t\t(ns) => !explicitOrder.includes(ns as keyof Modules & string),\n\t\t);\n\t\tif (missingModules.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`[Directive] initOrder is missing modules: ${missingModules.join(\", \")}. ` +\n\t\t\t\t`All modules must be included in the explicit order.`,\n\t\t\t);\n\t\t}\n\t\torderedNamespaces = explicitOrder;\n\t} else if (initOrder === \"declaration\") {\n\t\t// Use object key order (current behavior)\n\t\torderedNamespaces = Object.keys(modulesMap) as Array<keyof Modules & string>;\n\t} else {\n\t\t// \"auto\" - use topological sort based on crossModuleDeps\n\t\torderedNamespaces = topologicalSort(modulesMap);\n\t}\n\n\t// Apply zero-config defaults if enabled\n\tlet debug = options.debug;\n\tlet errorBoundary = options.errorBoundary;\n\n\tif (options.zeroConfig) {\n\t\tconst isDev = process.env.NODE_ENV !== \"production\";\n\n\t\tdebug = {\n\t\t\ttimeTravel: isDev,\n\t\t\tmaxSnapshots: 100,\n\t\t\t...options.debug,\n\t\t};\n\n\t\terrorBoundary = {\n\t\t\tonConstraintError: \"skip\",\n\t\t\tonResolverError: \"skip\",\n\t\t\tonEffectError: \"skip\",\n\t\t\tonDerivationError: \"skip\",\n\t\t\t...options.errorBoundary,\n\t\t};\n\t}\n\n\t// Validate module names and schema keys don't contain the separator\n\tfor (const namespace of Object.keys(modulesMap)) {\n\t\tif (namespace.includes(SEPARATOR)) {\n\t\t\tthrow new Error(\n\t\t\t\t`[Directive] Module name \"${namespace}\" contains the reserved separator \"${SEPARATOR}\". ` +\n\t\t\t\t`Module names cannot contain \"${SEPARATOR}\".`,\n\t\t\t);\n\t\t}\n\t\tconst mod = modulesMap[namespace];\n\t\tif (mod) {\n\t\t\tfor (const key of Object.keys(mod.schema.facts)) {\n\t\t\t\tif (key.includes(SEPARATOR)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Schema key \"${key}\" in module \"${namespace}\" contains the reserved separator \"${SEPARATOR}\". ` +\n\t\t\t\t\t\t`Schema keys cannot contain \"${SEPARATOR}\".`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Transform modules to flat format with prefixed keys\n\t// auth.token → auth::token internally\n\t// Process in dependency order (determined above)\n\tconst flatModules: Array<ModuleDef<ModuleSchema>> = [];\n\n\tfor (const namespace of orderedNamespaces) {\n\t\tconst mod = modulesMap[namespace];\n\t\tif (!mod) continue; // TypeScript guard - should never happen\n\t\t// Compute cross-module deps info once per module (used by derive, constraints, effects)\n\t\tconst hasCrossModuleDeps = mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0;\n\t\tconst depNamespaces = hasCrossModuleDeps ? Object.keys(mod.crossModuleDeps!) : [];\n\n\t\t// Prefix all fact keys with namespace\n\t\tconst prefixedFacts: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(mod.schema.facts)) {\n\t\t\tprefixedFacts[`${namespace}${SEPARATOR}${key}`] = value;\n\t\t}\n\n\t\t// Prefix all derivation keys with namespace\n\t\tconst prefixedDerivations: Record<string, unknown> = {};\n\t\tif (mod.schema.derivations) {\n\t\t\tfor (const [key, value] of Object.entries(mod.schema.derivations)) {\n\t\t\t\tprefixedDerivations[`${namespace}${SEPARATOR}${key}`] = value;\n\t\t\t}\n\t\t}\n\n\t\t// Prefix all event keys with namespace\n\t\tconst prefixedEvents: Record<string, unknown> = {};\n\t\tif (mod.schema.events) {\n\t\t\tfor (const [key, value] of Object.entries(mod.schema.events)) {\n\t\t\t\tprefixedEvents[`${namespace}${SEPARATOR}${key}`] = value;\n\t\t\t}\n\t\t}\n\n\t\t// Transform init to use prefixed keys\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Facts proxy type coercion\n\t\tconst prefixedInit = mod.init\n\t\t\t? (facts: any) => {\n\t\t\t\t\t// Create a proxy that translates unprefixed keys to prefixed\n\t\t\t\t\tconst moduleFactsProxy = createModuleFactsProxy(facts, namespace);\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Module init type coercion\n\t\t\t\t\t(mod.init as any)(moduleFactsProxy);\n\t\t\t\t}\n\t\t\t: undefined;\n\n\t\t// Transform derive functions to use prefixed keys\n\t\tconst prefixedDerive: Record<string, (facts: unknown, derive: unknown) => unknown> = {};\n\t\tif (mod.derive) {\n\t\t\tfor (const [key, fn] of Object.entries(mod.derive)) {\n\t\t\t\tprefixedDerive[`${namespace}${SEPARATOR}${key}`] = (facts: unknown, derive: unknown) => {\n\t\t\t\t\t// Use cross-module proxy (facts.self + facts.{dep}) if crossModuleDeps is defined\n\t\t\t\t\t// Otherwise use flat access to own module only\n\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t// Derive proxy stays scoped to own module\n\t\t\t\t\tconst deriveProxy = createModuleDeriveProxy(derive as Record<string, unknown>, namespace);\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Derive function type coercion\n\t\t\t\t\treturn (fn as any)(factsProxy, deriveProxy);\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Transform event handlers to use prefixed keys\n\t\tconst prefixedEventHandlers: Record<string, (facts: unknown, event: unknown) => void> = {};\n\t\tif (mod.events) {\n\t\t\tfor (const [key, handler] of Object.entries(mod.events)) {\n\t\t\t\tprefixedEventHandlers[`${namespace}${SEPARATOR}${key}`] = (facts: unknown, event: unknown) => {\n\t\t\t\t\tconst moduleFactsProxy = createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Event handler type coercion\n\t\t\t\t\t(handler as any)(moduleFactsProxy, event);\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Transform constraints to use namespaced facts proxy\n\t\tconst prefixedConstraints: Record<string, unknown> = {};\n\t\tif (mod.constraints) {\n\t\t\tfor (const [key, constraint] of Object.entries(mod.constraints)) {\n\t\t\t\tconst constraintDef = constraint as {\n\t\t\t\t\twhen: (facts: unknown) => boolean | Promise<boolean>;\n\t\t\t\t\trequire: unknown | ((facts: unknown) => unknown);\n\t\t\t\t\tpriority?: number;\n\t\t\t\t\tasync?: boolean;\n\t\t\t\t\ttimeout?: number;\n\t\t\t\t\tdeps?: string[];\n\t\t\t\t};\n\n\t\t\t\tprefixedConstraints[`${namespace}${SEPARATOR}${key}`] = {\n\t\t\t\t\t...constraintDef,\n\t\t\t\t\t// Transform deps to use prefixed keys\n\t\t\t\t\tdeps: constraintDef.deps?.map((dep) => `${namespace}${SEPARATOR}${dep}`),\n\t\t\t\t\twhen: (facts: unknown) => {\n\t\t\t\t\t\t// Use cross-module proxy (facts.self + facts.{dep}) if crossModuleDeps is defined\n\t\t\t\t\t\t// Otherwise use module-scoped proxy for direct access (facts.key → namespace::key)\n\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\treturn constraintDef.when(factsProxy);\n\t\t\t\t\t},\n\t\t\t\t\trequire: typeof constraintDef.require === \"function\"\n\t\t\t\t\t\t? (facts: unknown) => {\n\t\t\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\t\t\treturn (constraintDef.require as (facts: unknown) => unknown)(factsProxy);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: constraintDef.require,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Transform resolvers to use namespaced facts proxy\n\t\tconst prefixedResolvers: Record<string, unknown> = {};\n\t\tif (mod.resolvers) {\n\t\t\tfor (const [key, resolver] of Object.entries(mod.resolvers)) {\n\t\t\t\tconst resolverDef = resolver as {\n\t\t\t\t\trequirement: string;\n\t\t\t\t\tresolve: (req: unknown, ctx: { facts: unknown; signal: AbortSignal }) => Promise<void>;\n\t\t\t\t\tkey?: (req: unknown) => string;\n\t\t\t\t\tretry?: unknown;\n\t\t\t\t\ttimeout?: number;\n\t\t\t\t};\n\n\t\t\t\tprefixedResolvers[`${namespace}${SEPARATOR}${key}`] = {\n\t\t\t\t\t...resolverDef,\n\t\t\t\t\tresolve: async (req: unknown, ctx: { facts: unknown; signal: AbortSignal }) => {\n\t\t\t\t\t\tconst namespacedFacts = createNamespacedFactsProxy(ctx.facts as Record<string, unknown>, modulesMap, () => Object.keys(modulesMap));\n\t\t\t\t\t\tawait resolverDef.resolve(req, {\n\t\t\t\t\t\t\tfacts: namespacedFacts[namespace],\n\t\t\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Transform effects to use namespaced facts proxy\n\t\tconst prefixedEffects: Record<string, unknown> = {};\n\t\tif (mod.effects) {\n\t\t\tfor (const [key, effect] of Object.entries(mod.effects)) {\n\t\t\t\tconst effectDef = effect as {\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Effect run function type\n\t\t\t\t\trun: (facts: any, prev: any) => void | Promise<void>;\n\t\t\t\t\tdeps?: string[];\n\t\t\t\t};\n\n\t\t\t\tprefixedEffects[`${namespace}${SEPARATOR}${key}`] = {\n\t\t\t\t\t...effectDef,\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Effect run function wrapper\n\t\t\t\t\trun: (facts: any, prev: any) => {\n\t\t\t\t\t\t// Use cross-module proxy (facts.self + facts.{dep}) if crossModuleDeps is defined\n\t\t\t\t\t\t// Otherwise use module-scoped proxy for direct access (facts.key → namespace::key)\n\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\tconst prevProxy = prev\n\t\t\t\t\t\t\t? (hasCrossModuleDeps\n\t\t\t\t\t\t\t\t\t? createCrossModuleFactsProxy(prev as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t\t\t: createModuleFactsProxy(prev as Record<string, unknown>, namespace))\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\treturn effectDef.run(factsProxy, prevProxy);\n\t\t\t\t\t},\n\t\t\t\t\t// Transform deps to use prefixed keys\n\t\t\t\t\tdeps: effectDef.deps?.map((dep) => `${namespace}${SEPARATOR}${dep}`),\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tflatModules.push({\n\t\t\tid: mod.id,\n\t\t\tschema: {\n\t\t\t\tfacts: prefixedFacts,\n\t\t\t\tderivations: prefixedDerivations,\n\t\t\t\tevents: prefixedEvents,\n\t\t\t\trequirements: mod.schema.requirements ?? {},\n\t\t\t},\n\t\t\tinit: prefixedInit,\n\t\t\tderive: prefixedDerive,\n\t\t\tevents: prefixedEventHandlers,\n\t\t\teffects: prefixedEffects,\n\t\t\tconstraints: prefixedConstraints,\n\t\t\tresolvers: prefixedResolvers,\n\t\t\thooks: mod.hooks,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Module transformation\n\t\t} as any);\n\t}\n\n\t// Dev-mode warning: tickMs set without tick event handler\n\tif (process.env.NODE_ENV !== \"production\" && options.tickMs && options.tickMs > 0) {\n\t\tconst hasTickHandler = flatModules.some(\n\t\t\t(m) => m.events && Object.keys(m.events).some((k) => k.endsWith(`${SEPARATOR}tick`)),\n\t\t);\n\t\tif (!hasTickHandler) {\n\t\t\tconsole.warn(\n\t\t\t\t`[Directive] tickMs is set to ${options.tickMs}ms but no module defines a \"tick\" event handler.`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Store for hydrated facts (set by hydrate(), applied during init)\n\tlet hydratedFacts: Record<string, Record<string, unknown>> | null = null;\n\n\t// Engine reference (set after creation, used by applyNamespacedFacts)\n\t// biome-ignore lint/suspicious/noExplicitAny: Engine type\n\tlet engine: any = null;\n\n\t/**\n\t * Apply namespaced facts to the engine's flat store.\n\t * Converts { auth: { token: \"x\" } } to { \"auth::token\": \"x\" }\n\t * Includes prototype pollution protection.\n\t */\n\tfunction applyNamespacedFacts(\n\t\tnamespacedFacts: Record<string, Record<string, unknown>>,\n\t): void {\n\t\tfor (const [namespace, facts] of Object.entries(namespacedFacts)) {\n\t\t\t// Skip blocked property names\n\t\t\tif (BLOCKED_PROPS.has(namespace)) {\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] initialFacts/hydrate contains blocked namespace \"${namespace}\". Skipping.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!moduleNamespaces.has(namespace)) {\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] initialFacts/hydrate contains unknown namespace \"${namespace}\". ` +\n\t\t\t\t\t\t`Available modules: ${[...moduleNamespaces].join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Validate facts object for prototype pollution\n\t\t\tif (facts && typeof facts === \"object\" && !isPrototypeSafe(facts)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] initialFacts/hydrate for namespace \"${namespace}\" contains potentially ` +\n\t\t\t\t\t`dangerous keys (__proto__, constructor, or prototype). This may indicate a ` +\n\t\t\t\t\t`prototype pollution attack.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tfor (const [key, value] of Object.entries(facts)) {\n\t\t\t\t// Skip blocked keys\n\t\t\t\tif (BLOCKED_PROPS.has(key)) continue;\n\t\t\t\t(engine.facts as Record<string, unknown>)[`${namespace}${SEPARATOR}${key}`] = value;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create engine with flat modules\n\tengine = createEngine({\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Module format conversion\n\t\tmodules: flatModules.map((mod) => ({\n\t\t\tid: mod.id,\n\t\t\tschema: mod.schema.facts,\n\t\t\trequirements: mod.schema.requirements,\n\t\t\tinit: mod.init,\n\t\t\tderive: mod.derive,\n\t\t\tevents: mod.events,\n\t\t\teffects: mod.effects,\n\t\t\tconstraints: mod.constraints,\n\t\t\tresolvers: mod.resolvers,\n\t\t\thooks: mod.hooks,\n\t\t})) as any,\n\t\tplugins: options.plugins,\n\t\tdebug,\n\t\terrorBoundary,\n\t\ttickMs: options.tickMs,\n\t\t// Callback to apply initialFacts/hydrate during init phase (after module inits, before reconcile)\n\t\tonAfterModuleInit: () => {\n\t\t\t// Apply initialFacts first\n\t\t\tif (options.initialFacts) {\n\t\t\t\tapplyNamespacedFacts(options.initialFacts as Record<string, Record<string, unknown>>);\n\t\t\t}\n\t\t\t// Apply hydrated facts second (takes precedence)\n\t\t\tif (hydratedFacts) {\n\t\t\t\tapplyNamespacedFacts(hydratedFacts);\n\t\t\t\thydratedFacts = null;\n\t\t\t}\n\t\t},\n\t});\n\n\t// Build namespace → internal keys map (for subscribeModule / wildcard support)\n\tconst namespaceKeysMap = new Map<string, string[]>();\n\tfor (const namespace of Object.keys(modulesMap)) {\n\t\tconst mod = modulesMap[namespace];\n\t\tif (!mod) continue;\n\t\tconst keys: string[] = [];\n\t\tfor (const key of Object.keys(mod.schema.facts)) {\n\t\t\tkeys.push(`${namespace}${SEPARATOR}${key}`);\n\t\t}\n\t\tif (mod.schema.derivations) {\n\t\t\tfor (const key of Object.keys(mod.schema.derivations)) {\n\t\t\t\tkeys.push(`${namespace}${SEPARATOR}${key}`);\n\t\t\t}\n\t\t}\n\t\tnamespaceKeysMap.set(namespace, keys);\n\t}\n\n\t// Cached module names array, shared by all namespaced proxies.\n\t// Set to null on registerModule to lazily recompute.\n\tconst moduleNamesCache: { names: string[] | null } = { names: null };\n\tfunction getModuleNames(): string[] {\n\t\tif (moduleNamesCache.names === null) {\n\t\t\tmoduleNamesCache.names = Object.keys(modulesMap);\n\t\t}\n\t\treturn moduleNamesCache.names;\n\t}\n\n\t// Create namespaced proxies for external access\n\tconst namespacedFactsProxy = createNamespacedFactsProxy(engine.facts as unknown as Record<string, unknown>, modulesMap, getModuleNames);\n\tconst namespacedDeriveProxy = createNamespacedDeriveProxy(engine.derive as unknown as Record<string, unknown>, modulesMap, getModuleNames);\n\tconst namespacedEventsProxy = createNamespacedEventsProxy(engine, modulesMap, getModuleNames);\n\n\t// Build the namespaced system\n\tlet tickInterval: ReturnType<typeof setInterval> | null = null;\n\tconst tickMs = options.tickMs;\n\n\tconst system: NamespacedSystem<Modules> = {\n\t\t_mode: \"namespaced\",\n\t\tfacts: namespacedFactsProxy,\n\t\tdebug: engine.debug,\n\t\tderive: namespacedDeriveProxy,\n\t\tevents: namespacedEventsProxy,\n\t\tconstraints: engine.constraints,\n\t\teffects: engine.effects,\n\n\t\tget isRunning() {\n\t\t\treturn engine.isRunning;\n\t\t},\n\n\t\tget isSettled() {\n\t\t\treturn engine.isSettled;\n\t\t},\n\n\t\tget isInitialized() {\n\t\t\treturn engine.isInitialized;\n\t\t},\n\n\t\tget isReady() {\n\t\t\treturn engine.isReady;\n\t\t},\n\n\t\twhenReady: engine.whenReady.bind(engine),\n\n\t\tasync hydrate(\n\t\t\tloader: () =>\n\t\t\t\t| Promise<Record<string, Record<string, unknown>>>\n\t\t\t\t| Record<string, Record<string, unknown>>,\n\t\t) {\n\t\t\tif (engine.isRunning) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"[Directive] hydrate() must be called before start(). \" +\n\t\t\t\t\t\"The system is already running.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst result = await loader();\n\t\t\tif (result && typeof result === \"object\") {\n\t\t\t\thydratedFacts = result;\n\t\t\t}\n\t\t},\n\n\t\tstart(): void {\n\t\t\t// Engine.start() runs module inits, then applies initialFacts/hydrate via callback\n\t\t\tengine.start();\n\n\t\t\tif (tickMs && tickMs > 0) {\n\t\t\t\t// Find the first module with a tick event and dispatch to it\n\t\t\t\tconst tickEventKey = Object.keys(flatModules[0]?.events ?? {}).find((k) => k.endsWith(`${SEPARATOR}tick`));\n\t\t\t\tif (tickEventKey) {\n\t\t\t\t\ttickInterval = setInterval(() => {\n\t\t\t\t\t\tengine.dispatch({ type: tickEventKey });\n\t\t\t\t\t}, tickMs);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tstop(): void {\n\t\t\tif (tickInterval) {\n\t\t\t\tclearInterval(tickInterval);\n\t\t\t\ttickInterval = null;\n\t\t\t}\n\t\t\tengine.stop();\n\t\t},\n\n\t\tdestroy(): void {\n\t\t\tthis.stop();\n\t\t\tengine.destroy();\n\t\t},\n\n\t\tdispatch(event: { type: string; [key: string]: unknown }) {\n\t\t\t// Events are dispatched with namespace prefix\n\t\t\t// e.g., { type: \"login\", token: \"abc\" } from auth module\n\t\t\t// becomes { type: \"auth::login\", token: \"abc\" }\n\t\t\t// But we keep them simple - the event type should match the schema\n\t\t\tengine.dispatch(event);\n\t\t},\n\n\t\tbatch: engine.batch.bind(engine),\n\n\t\t/**\n\t\t * Read a derivation value using namespaced syntax.\n\t\t * Accepts \"namespace.key\" format.\n\t\t *\n\t\t * @example\n\t\t * system.read(\"auth.status\") // → \"authenticated\"\n\t\t * system.read(\"data.count\") // → 5\n\t\t */\n\t\tread<T = unknown>(derivationId: string): T {\n\t\t\treturn engine.read(toInternalKey(derivationId));\n\t\t},\n\n\t\t/**\n\t\t * Subscribe to derivation changes using namespaced syntax.\n\t\t * Accepts \"namespace.key\" format.\n\t\t * Supports wildcard \"namespace.*\" to subscribe to all keys in a module.\n\t\t *\n\t\t * @example\n\t\t * system.subscribe([\"auth.status\", \"data.count\"], () => {\n\t\t * console.log(\"Auth or data changed\");\n\t\t * });\n\t\t *\n\t\t * @example Wildcard\n\t\t * system.subscribe([\"game.*\", \"chat.*\"], () => render());\n\t\t */\n\t\tsubscribe(ids: string[], listener: () => void): () => void {\n\t\t\tconst internalIds: string[] = [];\n\t\t\tfor (const id of ids) {\n\t\t\t\tif (id.endsWith(\".*\")) {\n\t\t\t\t\tconst ns = id.slice(0, -2);\n\t\t\t\t\tconst keys = namespaceKeysMap.get(ns);\n\t\t\t\t\tif (keys) {\n\t\t\t\t\t\tinternalIds.push(...keys);\n\t\t\t\t\t} else if (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\t\tconsole.warn(`[Directive] subscribe wildcard \"${id}\" — namespace \"${ns}\" not found.`);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tinternalIds.push(toInternalKey(id));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn engine.subscribe(internalIds, listener);\n\t\t},\n\n\t\t/**\n\t\t * Subscribe to ALL fact and derivation changes in a module namespace.\n\t\t * Shorthand for subscribing to every key in a module.\n\t\t *\n\t\t * @example\n\t\t * const unsub = system.subscribeModule(\"game\", () => render());\n\t\t */\n\t\tsubscribeModule(namespace: string, listener: () => void): () => void {\n\t\t\tconst keys = namespaceKeysMap.get(namespace);\n\t\t\tif (!keys || keys.length === 0) {\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] subscribeModule(\"${namespace}\") — namespace not found. ` +\n\t\t\t\t\t\t`Available: ${[...namespaceKeysMap.keys()].join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn () => {};\n\t\t\t}\n\t\t\treturn engine.subscribe(keys, listener);\n\t\t},\n\n\t\t/**\n\t\t * Watch a fact or derivation for changes using namespaced syntax.\n\t\t * The key is auto-detected -- works with both fact keys and derivation keys.\n\t\t * Accepts \"namespace.key\" format.\n\t\t *\n\t\t * @example\n\t\t * system.watch(\"auth.token\", (newVal, oldVal) => { ... }) // fact\n\t\t * system.watch(\"auth.status\", (newVal, oldVal) => { ... }) // derivation\n\t\t */\n\t\twatch<T = unknown>(\n\t\t\tid: string,\n\t\t\tcallback: (newValue: T, previousValue: T | undefined) => void,\n\t\t\toptions?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n\t\t): () => void {\n\t\t\treturn engine.watch(toInternalKey(id), callback, options);\n\t\t},\n\n\t\t/**\n\t\t * Returns a promise that resolves when the predicate becomes true.\n\t\t * The predicate receives namespaced facts (e.g., facts.auth.token).\n\t\t */\n\t\twhen(\n\t\t\tpredicate: (facts: Record<string, unknown>) => boolean,\n\t\t\toptions?: { timeout?: number },\n\t\t): Promise<void> {\n\t\t\t// Wrap predicate to provide namespaced facts view\n\t\t\treturn engine.when(\n\t\t\t\t() => predicate(namespacedFactsProxy as unknown as Record<string, unknown>),\n\t\t\t\toptions,\n\t\t\t);\n\t\t},\n\n\t\tonSettledChange: engine.onSettledChange.bind(engine),\n\t\tonTimeTravelChange: engine.onTimeTravelChange.bind(engine),\n\t\tinspect: engine.inspect.bind(engine),\n\t\tsettle: engine.settle.bind(engine),\n\t\texplain: engine.explain.bind(engine),\n\t\tgetSnapshot: engine.getSnapshot.bind(engine),\n\t\trestore: engine.restore.bind(engine),\n\n\t\t/**\n\t\t * Get a distributable snapshot with namespaced key translation.\n\t\t * Accepts \"namespace.key\" format in options (e.g., \"auth.effectivePlan\").\n\t\t * Returns data with namespaced keys (e.g., { auth: { effectivePlan: ... } }).\n\t\t */\n\t\tgetDistributableSnapshot<T = Record<string, unknown>>(\n\t\t\toptions?: {\n\t\t\t\tincludeDerivations?: string[];\n\t\t\t\texcludeDerivations?: string[];\n\t\t\t\tincludeFacts?: string[];\n\t\t\t\tttlSeconds?: number;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t\tincludeVersion?: boolean;\n\t\t\t},\n\t\t): {\n\t\t\tdata: T;\n\t\t\tcreatedAt: number;\n\t\t\texpiresAt?: number;\n\t\t\tversion?: string;\n\t\t\tmetadata?: Record<string, unknown>;\n\t\t} {\n\t\t\t// Translate namespaced keys to internal format\n\t\t\tconst internalOptions = {\n\t\t\t\t...options,\n\t\t\t\tincludeDerivations: options?.includeDerivations?.map(toInternalKey),\n\t\t\t\texcludeDerivations: options?.excludeDerivations?.map(toInternalKey),\n\t\t\t\tincludeFacts: options?.includeFacts?.map(toInternalKey),\n\t\t\t};\n\n\t\t\tconst snapshot = engine.getDistributableSnapshot(internalOptions);\n\n\t\t\t// Transform data keys from internal format (auth::status) to namespaced format (auth: { status })\n\t\t\tconst namespacedData: Record<string, Record<string, unknown>> = {};\n\n\t\t\tfor (const [key, value] of Object.entries(snapshot.data as Record<string, unknown>)) {\n\t\t\t\t// Find the namespace prefix (first separator)\n\t\t\t\tconst sepIndex = key.indexOf(SEPARATOR);\n\t\t\t\tif (sepIndex > 0) {\n\t\t\t\t\tconst namespace = key.slice(0, sepIndex);\n\t\t\t\t\tconst localKey = key.slice(sepIndex + SEPARATOR.length);\n\t\t\t\t\tif (!namespacedData[namespace]) {\n\t\t\t\t\t\tnamespacedData[namespace] = {};\n\t\t\t\t\t}\n\t\t\t\t\tnamespacedData[namespace][localKey] = value;\n\t\t\t\t} else {\n\t\t\t\t\t// No namespace found, keep as-is\n\t\t\t\t\tif (!namespacedData[\"_root\"]) {\n\t\t\t\t\t\tnamespacedData[\"_root\"] = {};\n\t\t\t\t\t}\n\t\t\t\t\tnamespacedData[\"_root\"][key] = value;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\t...snapshot,\n\t\t\t\tdata: namespacedData as T,\n\t\t\t};\n\t\t},\n\n\t\t/**\n\t\t * Watch for changes to distributable snapshot derivations.\n\t\t * Accepts \"namespace.key\" format in options.\n\t\t * Callback receives data with namespaced keys.\n\t\t */\n\t\twatchDistributableSnapshot<T = Record<string, unknown>>(\n\t\t\toptions: {\n\t\t\t\tincludeDerivations?: string[];\n\t\t\t\texcludeDerivations?: string[];\n\t\t\t\tincludeFacts?: string[];\n\t\t\t\tttlSeconds?: number;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t\tincludeVersion?: boolean;\n\t\t\t},\n\t\t\tcallback: (snapshot: {\n\t\t\t\tdata: T;\n\t\t\t\tcreatedAt: number;\n\t\t\t\texpiresAt?: number;\n\t\t\t\tversion?: string;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t}) => void,\n\t\t): () => void {\n\t\t\t// Translate namespaced keys to internal format\n\t\t\tconst internalOptions = {\n\t\t\t\t...options,\n\t\t\t\tincludeDerivations: options?.includeDerivations?.map(toInternalKey),\n\t\t\t\texcludeDerivations: options?.excludeDerivations?.map(toInternalKey),\n\t\t\t\tincludeFacts: options?.includeFacts?.map(toInternalKey),\n\t\t\t};\n\n\t\t\treturn engine.watchDistributableSnapshot(\n\t\t\t\tinternalOptions,\n\t\t\t\t(snapshot: { data: Record<string, unknown>; createdAt: number; expiresAt?: number; version?: string; metadata?: Record<string, unknown> }) => {\n\t\t\t\t\t// Transform data keys from internal format to namespaced format\n\t\t\t\t\tconst namespacedData: Record<string, Record<string, unknown>> = {};\n\n\t\t\t\t\tfor (const [key, value] of Object.entries(snapshot.data)) {\n\t\t\t\t\t\tconst sepIndex = key.indexOf(SEPARATOR);\n\t\t\t\t\t\tif (sepIndex > 0) {\n\t\t\t\t\t\t\tconst namespace = key.slice(0, sepIndex);\n\t\t\t\t\t\t\tconst localKey = key.slice(sepIndex + SEPARATOR.length);\n\t\t\t\t\t\t\tif (!namespacedData[namespace]) {\n\t\t\t\t\t\t\t\tnamespacedData[namespace] = {};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnamespacedData[namespace][localKey] = value;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (!namespacedData[\"_root\"]) {\n\t\t\t\t\t\t\t\tnamespacedData[\"_root\"] = {};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnamespacedData[\"_root\"][key] = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcallback({\n\t\t\t\t\t\t...snapshot,\n\t\t\t\t\t\tdata: namespacedData as T,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\tregisterModule(namespace: string, moduleDef: ModuleDef<ModuleSchema>): void {\n\t\t\t// Validate namespace\n\t\t\tif (moduleNamespaces.has(namespace)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Module namespace \"${namespace}\" already exists. ` +\n\t\t\t\t\t`Cannot register a duplicate namespace.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (namespace.includes(SEPARATOR)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Module name \"${namespace}\" contains the reserved separator \"${SEPARATOR}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (BLOCKED_PROPS.has(namespace)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Module name \"${namespace}\" is a blocked property.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Validate schema keys\n\t\t\tfor (const key of Object.keys(moduleDef.schema.facts)) {\n\t\t\t\tif (key.includes(SEPARATOR)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Schema key \"${key}\" in module \"${namespace}\" contains the reserved separator \"${SEPARATOR}\".`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst mod = moduleDef;\n\t\t\tconst hasCrossModuleDeps = mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0;\n\t\t\tconst depNamespaces = hasCrossModuleDeps ? Object.keys(mod.crossModuleDeps!) : [];\n\n\t\t\t// Build prefixed schema, derive, events, effects, constraints, resolvers\n\t\t\t// (same logic as initial createNamespacedSystem)\n\t\t\tconst prefixedFacts: Record<string, unknown> = {};\n\t\t\tfor (const [key, value] of Object.entries(mod.schema.facts)) {\n\t\t\t\tprefixedFacts[`${namespace}${SEPARATOR}${key}`] = value;\n\t\t\t}\n\n\t\t\tconst prefixedInit = mod.init\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Module init type coercion\n\t\t\t\t? (facts: any) => {\n\t\t\t\t\t\tconst moduleFactsProxy = createModuleFactsProxy(facts, namespace);\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Module init type coercion\n\t\t\t\t\t\t(mod.init as any)(moduleFactsProxy);\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\n\t\t\tconst prefixedDerive: Record<string, (facts: unknown, derive: unknown) => unknown> = {};\n\t\t\tif (mod.derive) {\n\t\t\t\tfor (const [key, fn] of Object.entries(mod.derive)) {\n\t\t\t\t\tprefixedDerive[`${namespace}${SEPARATOR}${key}`] = (facts: unknown, derive: unknown) => {\n\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\tconst deriveProxy = createModuleDeriveProxy(derive as Record<string, unknown>, namespace);\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Derive function type coercion\n\t\t\t\t\t\treturn (fn as any)(factsProxy, deriveProxy);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst prefixedEventHandlers: Record<string, (facts: unknown, event: unknown) => void> = {};\n\t\t\tif (mod.events) {\n\t\t\t\tfor (const [key, handler] of Object.entries(mod.events)) {\n\t\t\t\t\tprefixedEventHandlers[`${namespace}${SEPARATOR}${key}`] = (facts: unknown, event: unknown) => {\n\t\t\t\t\t\tconst moduleFactsProxy = createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Event handler type coercion\n\t\t\t\t\t\t(handler as any)(moduleFactsProxy, event);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst prefixedConstraints: Record<string, unknown> = {};\n\t\t\tif (mod.constraints) {\n\t\t\t\tfor (const [key, constraint] of Object.entries(mod.constraints)) {\n\t\t\t\t\tconst constraintDef = constraint as {\n\t\t\t\t\t\twhen: (facts: unknown) => boolean | Promise<boolean>;\n\t\t\t\t\t\trequire: unknown | ((facts: unknown) => unknown);\n\t\t\t\t\t\tpriority?: number;\n\t\t\t\t\t\tasync?: boolean;\n\t\t\t\t\t\ttimeout?: number;\n\t\t\t\t\t\tdeps?: string[];\n\t\t\t\t\t};\n\t\t\t\t\tprefixedConstraints[`${namespace}${SEPARATOR}${key}`] = {\n\t\t\t\t\t\t...constraintDef,\n\t\t\t\t\t\tdeps: constraintDef.deps?.map((dep) => `${namespace}${SEPARATOR}${dep}`),\n\t\t\t\t\t\twhen: (facts: unknown) => {\n\t\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\t\treturn constraintDef.when(factsProxy);\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequire: typeof constraintDef.require === \"function\"\n\t\t\t\t\t\t\t? (facts: unknown) => {\n\t\t\t\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\t\t\t\treturn (constraintDef.require as (facts: unknown) => unknown)(factsProxy);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: constraintDef.require,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst prefixedResolvers: Record<string, unknown> = {};\n\t\t\tif (mod.resolvers) {\n\t\t\t\tfor (const [key, resolver] of Object.entries(mod.resolvers)) {\n\t\t\t\t\tconst resolverDef = resolver as {\n\t\t\t\t\t\trequirement: string;\n\t\t\t\t\t\tresolve: (req: unknown, ctx: { facts: unknown; signal: AbortSignal }) => Promise<void>;\n\t\t\t\t\t\tkey?: (req: unknown) => string;\n\t\t\t\t\t\tretry?: unknown;\n\t\t\t\t\t\ttimeout?: number;\n\t\t\t\t\t};\n\t\t\t\t\tprefixedResolvers[`${namespace}${SEPARATOR}${key}`] = {\n\t\t\t\t\t\t...resolverDef,\n\t\t\t\t\t\tresolve: async (req: unknown, ctx: { facts: unknown; signal: AbortSignal }) => {\n\t\t\t\t\t\t\t// Use live modulesMap reference (already mutated by registerModule before this runs)\n\t\t\t\t\t\t\tconst namespacedFacts = createNamespacedFactsProxy(ctx.facts as Record<string, unknown>, modulesMap, getModuleNames);\n\t\t\t\t\t\t\tawait resolverDef.resolve(req, {\n\t\t\t\t\t\t\t\tfacts: namespacedFacts[namespace],\n\t\t\t\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst prefixedEffects: Record<string, unknown> = {};\n\t\t\tif (mod.effects) {\n\t\t\t\tfor (const [key, effect] of Object.entries(mod.effects)) {\n\t\t\t\t\tconst effectDef = effect as {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Effect run function type\n\t\t\t\t\t\trun: (facts: any, prev: any) => void | Promise<void>;\n\t\t\t\t\t\tdeps?: string[];\n\t\t\t\t\t};\n\t\t\t\t\tprefixedEffects[`${namespace}${SEPARATOR}${key}`] = {\n\t\t\t\t\t\t...effectDef,\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Effect run function wrapper\n\t\t\t\t\t\trun: (facts: any, prev: any) => {\n\t\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\t\tconst prevProxy = prev\n\t\t\t\t\t\t\t\t? (hasCrossModuleDeps\n\t\t\t\t\t\t\t\t\t\t? createCrossModuleFactsProxy(prev as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t\t\t\t: createModuleFactsProxy(prev as Record<string, unknown>, namespace))\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\t\treturn effectDef.run(factsProxy, prevProxy);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdeps: effectDef.deps?.map((dep) => `${namespace}${SEPARATOR}${dep}`),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Register namespace\n\t\t\tmoduleNamespaces.add(namespace);\n\t\t\t(modulesMap as Record<string, ModuleDef<ModuleSchema>>)[namespace] = mod;\n\t\t\t// Invalidate cached module names so proxies see the new namespace\n\t\t\tmoduleNamesCache.names = null;\n\n\t\t\t// Update namespace keys map\n\t\t\tconst keys: string[] = [];\n\t\t\tfor (const key of Object.keys(mod.schema.facts)) {\n\t\t\t\tkeys.push(`${namespace}${SEPARATOR}${key}`);\n\t\t\t}\n\t\t\tif (mod.schema.derivations) {\n\t\t\t\tfor (const key of Object.keys(mod.schema.derivations)) {\n\t\t\t\t\tkeys.push(`${namespace}${SEPARATOR}${key}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tnamespaceKeysMap.set(namespace, keys);\n\n\t\t\t// Delegate to engine's registerModule\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Engine registerModule type\n\t\t\t(engine as any).registerModule({\n\t\t\t\tid: mod.id,\n\t\t\t\tschema: prefixedFacts,\n\t\t\t\trequirements: mod.schema.requirements ?? {},\n\t\t\t\tinit: prefixedInit,\n\t\t\t\tderive: Object.keys(prefixedDerive).length > 0 ? prefixedDerive : undefined,\n\t\t\t\tevents: Object.keys(prefixedEventHandlers).length > 0 ? prefixedEventHandlers : undefined,\n\t\t\t\teffects: Object.keys(prefixedEffects).length > 0 ? prefixedEffects : undefined,\n\t\t\t\tconstraints: Object.keys(prefixedConstraints).length > 0 ? prefixedConstraints : undefined,\n\t\t\t\tresolvers: Object.keys(prefixedResolvers).length > 0 ? prefixedResolvers : undefined,\n\t\t\t\thooks: mod.hooks,\n\t\t\t});\n\t\t},\n\n\t// biome-ignore lint/suspicious/noExplicitAny: Type narrowing for NamespacedSystem\n\t} as any;\n\n\treturn system;\n}\n\n// ============================================================================\n// Key Conversion Helpers\n// ============================================================================\n\n/**\n * Convert a namespaced key (e.g., \"auth.status\") to internal prefixed format (\"auth::status\").\n * If the key is already in prefixed format, returns it unchanged.\n *\n * @example\n * toInternalKey(\"auth.status\") // → \"auth::status\"\n * toInternalKey(\"auth::status\") // → \"auth::status\" (unchanged)\n * toInternalKey(\"status\") // → \"status\" (unchanged)\n */\nfunction toInternalKey(key: string): string {\n\t// If key contains a dot, convert to separator format\n\tif (key.includes(\".\")) {\n\t\tconst [namespace, ...rest] = key.split(\".\");\n\t\treturn `${namespace}${SEPARATOR}${rest.join(SEPARATOR)}`;\n\t}\n\t// Already in internal format or simple key\n\treturn key;\n}\n\n// ============================================================================\n// Proxy Helpers\n// ============================================================================\n\n/**\n * Create a proxy for a single module's facts (used in init, event handlers).\n * Translates unprefixed keys to prefixed: `token` → `auth::token`\n *\n * Proxies are cached per facts store and namespace for performance.\n */\nfunction createModuleFactsProxy(\n\tfacts: Record<string, unknown>,\n\tnamespace: string,\n): Record<string, unknown> {\n\t// Check cache first\n\tlet namespaceCache = moduleFactsProxyCache.get(facts);\n\tif (namespaceCache) {\n\t\tconst cached = namespaceCache.get(namespace);\n\t\tif (cached) return cached;\n\t} else {\n\t\tnamespaceCache = new Map();\n\t\tmoduleFactsProxyCache.set(facts, namespaceCache);\n\t}\n\n\tconst proxy = new Proxy({} as Record<string, unknown>, {\n\t\tget(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\t\t\t// Special properties pass through\n\t\t\tif (prop === \"$store\" || prop === \"$snapshot\") {\n\t\t\t\treturn (facts as Record<string, unknown>)[prop];\n\t\t\t}\n\t\t\treturn (facts as Record<string, unknown>)[`${namespace}${SEPARATOR}${prop}`];\n\t\t},\n\t\tset(_, prop: string | symbol, value: unknown) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\t\t\t(facts as Record<string, unknown>)[`${namespace}${SEPARATOR}${prop}`] = value;\n\t\t\treturn true;\n\t\t},\n\t\thas(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\t\t\treturn `${namespace}${SEPARATOR}${prop}` in facts;\n\t\t},\n\t\tdeleteProperty(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\t\t\tdelete (facts as Record<string, unknown>)[`${namespace}${SEPARATOR}${prop}`];\n\t\t\treturn true;\n\t\t},\n\t});\n\n\tnamespaceCache.set(namespace, proxy);\n\treturn proxy;\n}\n\n/**\n * Create a nested proxy for namespaced facts access.\n * `facts.auth.token` → reads `auth::token` from flat store\n *\n * Uses Set for O(1) namespace lookups and caches the outer proxy.\n */\nfunction createNamespacedFactsProxy(\n\tfacts: Record<string, unknown>,\n\tmodulesMap: ModulesMap,\n\tgetModuleNames: () => string[],\n): Record<string, Record<string, unknown>> {\n\t// Check cache first\n\tconst cached = namespacedFactsProxyCache.get(facts);\n\tif (cached) return cached;\n\n\tconst proxy = new Proxy({} as Record<string, Record<string, unknown>>, {\n\t\tget(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(namespace)) return undefined;\n\t\t\tif (!Object.hasOwn(modulesMap, namespace)) return undefined;\n\n\t\t\t// Return a cached proxy for this module's facts\n\t\t\treturn createModuleFactsProxy(facts, namespace);\n\t\t},\n\t\thas(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(namespace)) return false;\n\t\t\treturn Object.hasOwn(modulesMap, namespace);\n\t\t},\n\t\townKeys() {\n\t\t\treturn getModuleNames();\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return undefined;\n\t\t\tif (Object.hasOwn(modulesMap, namespace)) {\n\t\t\t\treturn { configurable: true, enumerable: true };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n\n\tnamespacedFactsProxyCache.set(facts, proxy);\n\treturn proxy;\n}\n\n/**\n * WeakMap to cache cross-module facts proxies.\n * Keyed by facts store, then by \"selfNamespace:depKeys\" string.\n */\nconst crossModuleFactsProxyCache = new WeakMap<\n\tRecord<string, unknown>,\n\tMap<string, Record<string, Record<string, unknown>>>\n>();\n\n/**\n * Create a proxy for cross-module facts access with \"self\" for own module.\n * `facts.self.users` → reads own module's facts\n * `facts.auth.token` → reads dependency module's facts\n *\n * Used when a module has crossModuleDeps defined.\n */\nfunction createCrossModuleFactsProxy(\n\tfacts: Record<string, unknown>,\n\tselfNamespace: string,\n\tdepNamespaces: string[],\n): Record<string, Record<string, unknown>> {\n\t// Create cache key using JSON.stringify for robustness with special characters\n\tconst cacheKey = `${selfNamespace}:${JSON.stringify([...depNamespaces].sort())}`;\n\n\t// Check cache first\n\tlet namespaceCache = crossModuleFactsProxyCache.get(facts);\n\tif (namespaceCache) {\n\t\tconst cached = namespaceCache.get(cacheKey);\n\t\tif (cached) return cached;\n\t} else {\n\t\tnamespaceCache = new Map();\n\t\tcrossModuleFactsProxyCache.set(facts, namespaceCache);\n\t}\n\n\tconst depNamesSet = new Set(depNamespaces);\n\tconst allKeys = [\"self\", ...depNamespaces];\n\n\tconst proxy = new Proxy({} as Record<string, Record<string, unknown>>, {\n\t\tget(_, key: string | symbol) {\n\t\t\tif (typeof key === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(key)) return undefined;\n\n\t\t\t// \"self\" maps to own module's namespace\n\t\t\tif (key === \"self\") {\n\t\t\t\treturn createModuleFactsProxy(facts, selfNamespace);\n\t\t\t}\n\n\t\t\t// Check if it's a declared dependency\n\t\t\tif (depNamesSet.has(key)) {\n\t\t\t\treturn createModuleFactsProxy(facts, key);\n\t\t\t}\n\n\t\t\t// Dev-mode warning for undeclared cross-module access\n\t\t\tif (process.env.NODE_ENV !== \"production\" && typeof key === \"string\") {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] Module \"${selfNamespace}\" accessed undeclared cross-module property \"${key}\". ` +\n\t\t\t\t\t`Add it to crossModuleDeps or use \"facts.self.${key}\" for own module facts.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn undefined;\n\t\t},\n\t\thas(_, key: string | symbol) {\n\t\t\tif (typeof key === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(key)) return false;\n\t\t\treturn key === \"self\" || depNamesSet.has(key);\n\t\t},\n\t\townKeys() {\n\t\t\treturn allKeys;\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, key: string | symbol) {\n\t\t\tif (typeof key === \"symbol\") return undefined;\n\t\t\tif (key === \"self\" || depNamesSet.has(key)) {\n\t\t\t\treturn { configurable: true, enumerable: true };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n\n\tnamespaceCache.set(cacheKey, proxy);\n\treturn proxy;\n}\n\n/**\n * Create a proxy for a single module's derivations.\n * Translates unprefixed keys to prefixed: `status` → `auth::status`\n *\n * Proxies are cached per derive store and namespace for performance.\n */\nfunction createModuleDeriveProxy(\n\tderive: Record<string, unknown>,\n\tnamespace: string,\n): Record<string, unknown> {\n\t// Check cache first\n\tlet namespaceCache = moduleDeriveProxyCache.get(derive);\n\tif (namespaceCache) {\n\t\tconst cached = namespaceCache.get(namespace);\n\t\tif (cached) return cached;\n\t} else {\n\t\tnamespaceCache = new Map();\n\t\tmoduleDeriveProxyCache.set(derive, namespaceCache);\n\t}\n\n\tconst proxy = new Proxy({} as Record<string, unknown>, {\n\t\tget(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\t\t\treturn derive[`${namespace}${SEPARATOR}${prop}`];\n\t\t},\n\t\thas(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\t\t\treturn `${namespace}${SEPARATOR}${prop}` in derive;\n\t\t},\n\t});\n\n\tnamespaceCache.set(namespace, proxy);\n\treturn proxy;\n}\n\n/**\n * Create a nested proxy for namespaced derivations access.\n * `derive.auth.status` → reads `auth::status` from flat derive\n *\n * Uses Set for O(1) namespace lookups and caches the outer proxy.\n */\nfunction createNamespacedDeriveProxy(\n\tderive: Record<string, unknown>,\n\tmodulesMap: ModulesMap,\n\tgetModuleNames: () => string[],\n): Record<string, Record<string, unknown>> {\n\t// Check cache first\n\tconst cached = namespacedDeriveProxyCache.get(derive);\n\tif (cached) return cached;\n\n\tconst proxy = new Proxy({} as Record<string, Record<string, unknown>>, {\n\t\tget(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(namespace)) return undefined;\n\t\t\tif (!Object.hasOwn(modulesMap, namespace)) return undefined;\n\n\t\t\t// Return a cached proxy for this module's derivations\n\t\t\treturn createModuleDeriveProxy(derive, namespace);\n\t\t},\n\t\thas(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(namespace)) return false;\n\t\t\treturn Object.hasOwn(modulesMap, namespace);\n\t\t},\n\t\townKeys() {\n\t\t\treturn getModuleNames();\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return undefined;\n\t\t\tif (Object.hasOwn(modulesMap, namespace)) {\n\t\t\t\treturn { configurable: true, enumerable: true };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n\n\tnamespacedDeriveProxyCache.set(derive, proxy);\n\treturn proxy;\n}\n\n/**\n * WeakMap to cache module events proxies.\n */\nconst moduleEventsProxyCache = new WeakMap<\n\t// biome-ignore lint/suspicious/noExplicitAny: Engine type for cache key\n\tany,\n\tMap<string, Record<string, (payload?: Record<string, unknown>) => void>>\n>();\n\n/**\n * Create a nested proxy for namespaced events access.\n * `events.auth.login({ token })` → dispatches `{ type: \"auth::login\", token }`\n *\n * Uses Set for O(1) namespace lookups and caches proxies for performance.\n */\nfunction createNamespacedEventsProxy(\n\t// biome-ignore lint/suspicious/noExplicitAny: Engine type\n\tengine: any,\n\tmodulesMap: ModulesMap,\n\tgetModuleNames: () => string[],\n): Record<string, Record<string, (payload?: Record<string, unknown>) => void>> {\n\t// Get or create the namespace cache for this engine\n\tlet namespaceCache = moduleEventsProxyCache.get(engine);\n\tif (!namespaceCache) {\n\t\tnamespaceCache = new Map();\n\t\tmoduleEventsProxyCache.set(engine, namespaceCache);\n\t}\n\n\treturn new Proxy({} as Record<string, Record<string, (payload?: Record<string, unknown>) => void>>, {\n\t\tget(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(namespace)) return undefined;\n\t\t\tif (!Object.hasOwn(modulesMap, namespace)) return undefined;\n\n\t\t\t// Check cache for this namespace's event proxy\n\t\t\tconst cached = namespaceCache!.get(namespace);\n\t\t\tif (cached) return cached;\n\n\t\t\t// Create and cache the module events proxy\n\t\t\tconst moduleEventsProxy = new Proxy({} as Record<string, (payload?: Record<string, unknown>) => void>, {\n\t\t\t\tget(_, eventName: string | symbol) {\n\t\t\t\t\tif (typeof eventName === \"symbol\") return undefined;\n\t\t\t\t\tif (BLOCKED_PROPS.has(eventName)) return undefined;\n\n\t\t\t\t\t// Return a function that dispatches the prefixed event\n\t\t\t\t\treturn (payload?: Record<string, unknown>) => {\n\t\t\t\t\t\tengine.dispatch({ type: `${namespace}${SEPARATOR}${eventName}`, ...payload });\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tnamespaceCache!.set(namespace, moduleEventsProxy);\n\t\t\treturn moduleEventsProxy;\n\t\t},\n\t\thas(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(namespace)) return false;\n\t\t\treturn Object.hasOwn(modulesMap, namespace);\n\t\t},\n\t\townKeys() {\n\t\t\treturn getModuleNames();\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return undefined;\n\t\t\tif (Object.hasOwn(modulesMap, namespace)) {\n\t\t\t\treturn { configurable: true, enumerable: true };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n}\n\n// ============================================================================\n// Single Module System\n// ============================================================================\n\n/**\n * Create a system with a single module (no namespacing).\n * Facts, derivations, and events are accessed directly.\n */\nfunction createSingleModuleSystem<S extends ModuleSchema>(\n\toptions: CreateSystemOptionsSingle<S>,\n): SingleModuleSystem<S> {\n\tconst mod = options.module;\n\n\t// Validate module is provided\n\tif (!mod) {\n\t\tthrow new Error(\n\t\t\t\"[Directive] createSystem requires a module. Got: \" + typeof mod,\n\t\t);\n\t}\n\n\t// Validate tickMs if provided\n\tif (options.tickMs !== undefined && options.tickMs <= 0) {\n\t\tthrow new Error(\"[Directive] tickMs must be a positive number\");\n\t}\n\n\t// Validate initialFacts for prototype pollution\n\tif (options.initialFacts && !isPrototypeSafe(options.initialFacts)) {\n\t\tthrow new Error(\n\t\t\t\"[Directive] initialFacts contains potentially dangerous keys \" +\n\t\t\t\"(__proto__, constructor, or prototype). This may indicate a \" +\n\t\t\t\"prototype pollution attack.\",\n\t\t);\n\t}\n\n\t// Dev-mode warnings\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\t// Warn if crossModuleDeps is defined (ignored in single module mode)\n\t\tif (mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0) {\n\t\t\tconsole.warn(\n\t\t\t\t\"[Directive] Single module mode ignores crossModuleDeps. \" +\n\t\t\t\t\"Use multiple modules if cross-module access is needed: \" +\n\t\t\t\t\"createSystem({ modules: { ... } })\",\n\t\t\t);\n\t\t}\n\n\t\t// Warn if tickMs set without tick event handler\n\t\tif (options.tickMs && options.tickMs > 0) {\n\t\t\tconst hasTickHandler = mod.events && \"tick\" in mod.events;\n\t\t\tif (!hasTickHandler) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] tickMs is set to ${options.tickMs}ms but module has no \"tick\" event handler.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Apply zero-config defaults if enabled\n\tlet debug = options.debug;\n\tlet errorBoundary = options.errorBoundary;\n\n\tif (options.zeroConfig) {\n\t\tconst isDev = process.env.NODE_ENV !== \"production\";\n\n\t\tdebug = {\n\t\t\ttimeTravel: isDev,\n\t\t\tmaxSnapshots: 100,\n\t\t\t...options.debug,\n\t\t};\n\n\t\terrorBoundary = {\n\t\t\tonConstraintError: \"skip\",\n\t\t\tonResolverError: \"skip\",\n\t\t\tonEffectError: \"skip\",\n\t\t\tonDerivationError: \"skip\",\n\t\t\t...options.errorBoundary,\n\t\t};\n\t}\n\n\t// Store for hydrated facts\n\tlet hydratedFacts: Record<string, unknown> | null = null;\n\n\t// Engine reference\n\t// biome-ignore lint/suspicious/noExplicitAny: Engine type\n\tlet engine: any = null;\n\n\t// Create engine with the module directly (no prefixing needed)\n\tengine = createEngine({\n\t\tmodules: [\n\t\t\t{\n\t\t\t\tid: mod.id,\n\t\t\t\tschema: mod.schema.facts,\n\t\t\t\trequirements: mod.schema.requirements,\n\t\t\t\tinit: mod.init,\n\t\t\t\tderive: mod.derive,\n\t\t\t\tevents: mod.events,\n\t\t\t\teffects: mod.effects,\n\t\t\t\tconstraints: mod.constraints,\n\t\t\t\tresolvers: mod.resolvers,\n\t\t\t\thooks: mod.hooks,\n\t\t\t},\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Module format\n\t\t] as any,\n\t\tplugins: options.plugins,\n\t\tdebug,\n\t\terrorBoundary,\n\t\ttickMs: options.tickMs,\n\t\tonAfterModuleInit: () => {\n\t\t\t// Apply initialFacts\n\t\t\tif (options.initialFacts) {\n\t\t\t\tfor (const [key, value] of Object.entries(options.initialFacts)) {\n\t\t\t\t\tif (BLOCKED_PROPS.has(key)) continue;\n\t\t\t\t\t(engine.facts as Record<string, unknown>)[key] = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Apply hydrated facts (takes precedence)\n\t\t\tif (hydratedFacts) {\n\t\t\t\tfor (const [key, value] of Object.entries(hydratedFacts)) {\n\t\t\t\t\tif (BLOCKED_PROPS.has(key)) continue;\n\t\t\t\t\t(engine.facts as Record<string, unknown>)[key] = value;\n\t\t\t\t}\n\t\t\t\thydratedFacts = null;\n\t\t\t}\n\t\t},\n\t});\n\n\t// Create events proxy for direct access\n\tconst eventsProxy = new Proxy({} as Record<string, (payload?: Record<string, unknown>) => void>, {\n\t\tget(_, eventName: string | symbol) {\n\t\t\tif (typeof eventName === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(eventName)) return undefined;\n\n\t\t\treturn (payload?: Record<string, unknown>) => {\n\t\t\t\tengine.dispatch({ type: eventName, ...payload });\n\t\t\t};\n\t\t},\n\t});\n\n\t// Build the single module system\n\tlet tickInterval: ReturnType<typeof setInterval> | null = null;\n\tconst tickMs = options.tickMs;\n\n\tconst system: SingleModuleSystem<S> = {\n\t\t_mode: \"single\",\n\t\tfacts: engine.facts,\n\t\tdebug: engine.debug,\n\t\tderive: engine.derive,\n\t\tevents: eventsProxy as SingleModuleSystem<S>[\"events\"],\n\t\tconstraints: engine.constraints,\n\t\teffects: engine.effects,\n\n\t\tget isRunning() {\n\t\t\treturn engine.isRunning;\n\t\t},\n\n\t\tget isSettled() {\n\t\t\treturn engine.isSettled;\n\t\t},\n\n\t\tget isInitialized() {\n\t\t\treturn engine.isInitialized;\n\t\t},\n\n\t\tget isReady() {\n\t\t\treturn engine.isReady;\n\t\t},\n\n\t\twhenReady: engine.whenReady.bind(engine),\n\n\t\tasync hydrate(\n\t\t\tloader: () => Promise<Record<string, unknown>> | Record<string, unknown>,\n\t\t) {\n\t\t\tif (engine.isRunning) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"[Directive] hydrate() must be called before start(). \" +\n\t\t\t\t\t\"The system is already running.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst result = await loader();\n\t\t\tif (result && typeof result === \"object\") {\n\t\t\t\thydratedFacts = result as Record<string, unknown>;\n\t\t\t}\n\t\t},\n\n\t\tstart(): void {\n\t\t\tengine.start();\n\n\t\t\tif (tickMs && tickMs > 0) {\n\t\t\t\tconst hasTickHandler = mod.events && \"tick\" in mod.events;\n\t\t\t\tif (hasTickHandler) {\n\t\t\t\t\ttickInterval = setInterval(() => {\n\t\t\t\t\t\tengine.dispatch({ type: \"tick\" });\n\t\t\t\t\t}, tickMs);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tstop(): void {\n\t\t\tif (tickInterval) {\n\t\t\t\tclearInterval(tickInterval);\n\t\t\t\ttickInterval = null;\n\t\t\t}\n\t\t\tengine.stop();\n\t\t},\n\n\t\tdestroy(): void {\n\t\t\tthis.stop();\n\t\t\tengine.destroy();\n\t\t},\n\n\t\tdispatch(event: { type: string; [key: string]: unknown }) {\n\t\t\tengine.dispatch(event);\n\t\t},\n\n\t\tbatch: engine.batch.bind(engine),\n\n\t\tread<T = unknown>(derivationId: string): T {\n\t\t\treturn engine.read(derivationId);\n\t\t},\n\n\t\tsubscribe(ids: string[], listener: () => void): () => void {\n\t\t\treturn engine.subscribe(ids, listener);\n\t\t},\n\n\t\twatch<T = unknown>(\n\t\t\tid: string,\n\t\t\tcallback: (newValue: T, previousValue: T | undefined) => void,\n\t\t\toptions?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n\t\t): () => void {\n\t\t\treturn engine.watch(id, callback, options);\n\t\t},\n\n\t\twhen(\n\t\t\tpredicate: (facts: Record<string, unknown>) => boolean,\n\t\t\toptions?: { timeout?: number },\n\t\t): Promise<void> {\n\t\t\treturn engine.when(predicate, options);\n\t\t},\n\n\t\tonSettledChange: engine.onSettledChange.bind(engine),\n\t\tonTimeTravelChange: engine.onTimeTravelChange.bind(engine),\n\t\tinspect: engine.inspect.bind(engine),\n\t\tsettle: engine.settle.bind(engine),\n\t\texplain: engine.explain.bind(engine),\n\t\tgetSnapshot: engine.getSnapshot.bind(engine),\n\t\trestore: engine.restore.bind(engine),\n\t\tgetDistributableSnapshot: engine.getDistributableSnapshot.bind(engine),\n\t\twatchDistributableSnapshot: engine.watchDistributableSnapshot.bind(engine),\n\n\t\tregisterModule(moduleDef: ModuleDef<ModuleSchema>): void {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Engine registerModule type\n\t\t\t(engine as any).registerModule({\n\t\t\t\tid: moduleDef.id,\n\t\t\t\tschema: moduleDef.schema.facts,\n\t\t\t\trequirements: moduleDef.schema.requirements,\n\t\t\t\tinit: moduleDef.init,\n\t\t\t\tderive: moduleDef.derive,\n\t\t\t\tevents: moduleDef.events,\n\t\t\t\teffects: moduleDef.effects,\n\t\t\t\tconstraints: moduleDef.constraints,\n\t\t\t\tresolvers: moduleDef.resolvers,\n\t\t\t\thooks: moduleDef.hooks,\n\t\t\t});\n\t\t},\n\t// biome-ignore lint/suspicious/noExplicitAny: Type narrowing\n\t} as any;\n\n\treturn system;\n}\n\n","/**\n * Builder Pattern API for Directive Modules\n *\n * An alternative, fluent API for creating modules that provides\n * a more declarative style for module definition.\n *\n * @example\n * ```typescript\n * import { module, t } from '@directive-run/core';\n *\n * const counter = module(\"counter\")\n * .schema({\n * facts: { count: t.number(), lastAction: t.string() },\n * derivations: { doubled: t.number(), isPositive: t.boolean() },\n * events: { increment: {}, decrement: {} },\n * requirements: {},\n * })\n * .init((facts) => {\n * facts.count = 0;\n * facts.lastAction = \"\";\n * })\n * .derive({\n * doubled: (facts) => facts.count * 2,\n * isPositive: (facts) => facts.count > 0,\n * })\n * .events({\n * increment: (facts) => {\n * facts.count += 1;\n * facts.lastAction = \"increment\";\n * },\n * decrement: (facts) => {\n * facts.count -= 1;\n * facts.lastAction = \"decrement\";\n * },\n * })\n * .build();\n * ```\n */\n\nimport type {\n\tModuleSchema,\n\tDerivationsSchema,\n\tFacts,\n\tEffectsDef,\n\tModuleDef,\n\tModuleHooks,\n} from \"./types.js\";\n\n// ============================================================================\n// Builder Types\n// ============================================================================\n\n/**\n * Module builder interface - provides fluent API for building modules.\n *\n * @typeParam M - The module schema type (set after calling `.schema()`)\n */\nexport interface ModuleBuilder<M extends ModuleSchema = ModuleSchema> {\n\t/**\n\t * Define the schema for this module (facts, derivations, events, requirements).\n\t */\n\tschema<NewM extends ModuleSchema>(schema: NewM): ModuleBuilder<NewM>;\n\n\t/**\n\t * Define the initialization function for this module.\n\t */\n\tinit(initFn: (facts: Facts<M[\"facts\"]>) => void): ModuleBuilder<M>;\n\n\t/**\n\t * Define derivation implementations for this module.\n\t * Keys must match those declared in schema.derivations.\n\t */\n\tderive<D extends Record<string, (facts: Facts<M[\"facts\"]>, derive: DeriveAccessor<M>) => unknown>>(\n\t\tderivations: D\n\t): ModuleBuilder<M>;\n\n\t/**\n\t * Define event handler implementations for this module.\n\t * Keys must match those declared in schema.events.\n\t */\n\tevents<E extends Record<string, (facts: Facts<M[\"facts\"]>, payload: unknown) => void>>(\n\t\tevents: E\n\t): ModuleBuilder<M>;\n\n\t/**\n\t * Define effects (side effects) for this module.\n\t */\n\teffects(effects: EffectsDef<M[\"facts\"]>): ModuleBuilder<M>;\n\n\t/**\n\t * Define constraints for this module.\n\t */\n\tconstraints<C extends Record<string, ConstraintDef<M>>>(constraints: C): ModuleBuilder<M>;\n\n\t/**\n\t * Define resolvers for this module.\n\t */\n\tresolvers<R extends Record<string, ResolverDef<M>>>(resolvers: R): ModuleBuilder<M>;\n\n\t/**\n\t * Define lifecycle hooks for this module.\n\t */\n\thooks(hooks: ModuleHooks<M>): ModuleBuilder<M>;\n\n\t/**\n\t * Build the module definition.\n\t */\n\tbuild(): ModuleDef<M>;\n}\n\n// ============================================================================\n// Helper Types\n// ============================================================================\n\n/**\n * Accessor for reading other derivations within a derivation function.\n */\ntype DeriveAccessor<M extends ModuleSchema> = M[\"derivations\"] extends DerivationsSchema\n\t? { readonly [K in keyof M[\"derivations\"]]: InferSchemaType<M[\"derivations\"][K]> }\n\t: Record<string, never>;\n\n/**\n * Infer the TypeScript type from a schema type definition.\n */\n// biome-ignore lint/suspicious/noExplicitAny: Type inference utility\ntype InferSchemaType<T> = T extends { _type: infer U } ? U : any;\n\n/**\n * Constraint definition for the builder.\n */\ninterface ConstraintDef<M extends ModuleSchema> {\n\twhen: (facts: Facts<M[\"facts\"]>) => boolean;\n\trequire:\n\t\t| { type: string; [key: string]: unknown }\n\t\t| ((facts: Facts<M[\"facts\"]>) => { type: string; [key: string]: unknown } | null);\n\tpriority?: number;\n}\n\n/**\n * Resolver definition for the builder.\n */\ninterface ResolverDef<M extends ModuleSchema> {\n\trequirement: string | ((req: { type: string; [key: string]: unknown }) => boolean);\n\tresolve: (\n\t\treq: { type: string; [key: string]: unknown },\n\t\tctx: { facts: Facts<M[\"facts\"]>; signal?: AbortSignal }\n\t) => void | Promise<void>;\n\tretry?: {\n\t\tattempts?: number;\n\t\tbackoff?: \"linear\" | \"exponential\";\n\t\tdelay?: number;\n\t};\n\ttimeout?: number;\n\tkey?: (req: { type: string; [key: string]: unknown }) => string;\n}\n\n// ============================================================================\n// Builder Implementation\n// ============================================================================\n\n/**\n * Create a new module builder.\n *\n * @param id - The unique identifier for this module\n * @returns A module builder\n */\nexport function module(id: string): ModuleBuilder<ModuleSchema> {\n\t// Internal state for building the module\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _schema: any = { facts: {}, derivations: {}, events: {}, requirements: {} };\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _init: any;\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _events: any;\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _derive: any;\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _effects: any;\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _constraints: any;\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _resolvers: any;\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _hooks: any;\n\n\t// biome-ignore lint/suspicious/noExplicitAny: Builder needs flexibility for fluent API\n\tconst builder: ModuleBuilder<any> = {\n\t\tschema(schema) {\n\t\t\t_schema = schema;\n\t\t\treturn builder;\n\t\t},\n\n\t\tinit(initFn) {\n\t\t\t_init = initFn;\n\t\t\treturn builder;\n\t\t},\n\n\t\tderive(derivations) {\n\t\t\t_derive = derivations;\n\t\t\treturn builder;\n\t\t},\n\n\t\tevents(events) {\n\t\t\t_events = events;\n\t\t\treturn builder;\n\t\t},\n\n\t\teffects(effects) {\n\t\t\t_effects = effects;\n\t\t\treturn builder;\n\t\t},\n\n\t\tconstraints(constraints) {\n\t\t\t_constraints = constraints;\n\t\t\treturn builder;\n\t\t},\n\n\t\tresolvers(resolvers) {\n\t\t\t_resolvers = resolvers;\n\t\t\treturn builder;\n\t\t},\n\n\t\thooks(hooks) {\n\t\t\t_hooks = hooks;\n\t\t\treturn builder;\n\t\t},\n\n\t\tbuild() {\n\t\t\t// Validate schema is defined\n\t\t\tif (!_schema || !_schema.facts) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Module \"${id}\" requires a schema with at least facts defined. ` +\n\t\t\t\t\t\"Call .schema({ facts: { ... } }) before .build().\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Validate derivations match schema\n\t\t\tconst schemaDerivationKeys = Object.keys(_schema.derivations ?? {});\n\t\t\tconst deriveKeys = Object.keys(_derive ?? {});\n\t\t\tconst missingDerives = schemaDerivationKeys.filter(k => !deriveKeys.includes(k));\n\t\t\tif (missingDerives.length > 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Module \"${id}\" is missing derivation implementations: ${missingDerives.join(\", \")}. ` +\n\t\t\t\t\t\"All derivations declared in schema.derivations must have implementations in .derive().\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Validate events match schema\n\t\t\tconst schemaEventKeys = Object.keys(_schema.events ?? {});\n\t\t\tconst eventKeys = Object.keys(_events ?? {});\n\t\t\tconst missingEvents = schemaEventKeys.filter(k => !eventKeys.includes(k));\n\t\t\tif (missingEvents.length > 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Module \"${id}\" is missing event handler implementations: ${missingEvents.join(\", \")}. ` +\n\t\t\t\t\t\"All events declared in schema.events must have implementations in .events().\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tid,\n\t\t\t\tschema: _schema,\n\t\t\t\tinit: _init,\n\t\t\t\tevents: _events,\n\t\t\t\tderive: _derive,\n\t\t\t\teffects: _effects,\n\t\t\t\tconstraints: _constraints,\n\t\t\t\tresolvers: _resolvers,\n\t\t\t\thooks: _hooks,\n\t\t\t};\n\t\t},\n\t};\n\n\treturn builder;\n}\n","/**\n * Constraint Builder API\n *\n * Fluent builders for creating typed constraint definitions.\n *\n * @example Full builder\n * ```typescript\n * import { constraint } from '@directive-run/core';\n *\n * const escalate = constraint<typeof schema>()\n * .when(f => f.confidence < 0.7)\n * .require({ type: 'ESCALATE' })\n * .priority(50)\n * .build();\n * ```\n *\n * @example Quick shorthand\n * ```typescript\n * import { when } from '@directive-run/core';\n *\n * const pause = when<typeof schema>(f => f.errors > 3)\n * .require({ type: 'PAUSE' });\n * ```\n */\n\nimport type { ModuleSchema, InferRequirements } from \"./types/schema.js\";\nimport type { Facts } from \"./types/facts.js\";\nimport type { TypedConstraintDef, RequirementOutput } from \"./types/module.js\";\n\n// ============================================================================\n// Builder Types\n// ============================================================================\n\ntype WhenFn<M extends ModuleSchema> = (facts: Facts<M[\"facts\"]>) => boolean | Promise<boolean>;\ntype RequireValue<M extends ModuleSchema> =\n\t| RequirementOutput<InferRequirements<M>>\n\t| ((facts: Facts<M[\"facts\"]>) => RequirementOutput<InferRequirements<M>>);\n\n/** Builder after constraint() — must call .when() first */\nexport interface ConstraintBuilderStart<M extends ModuleSchema> {\n\twhen(condition: WhenFn<M>): ConstraintBuilderWithWhen<M>;\n}\n\n/** Builder after .when() — must call .require() next */\nexport interface ConstraintBuilderWithWhen<M extends ModuleSchema> {\n\trequire(req: RequireValue<M>): ConstraintBuilderComplete<M>;\n}\n\n/** Builder after .require() — optional chaining + .build() */\nexport interface ConstraintBuilderComplete<M extends ModuleSchema> {\n\tpriority(n: number): ConstraintBuilderComplete<M>;\n\tafter(...ids: string[]): ConstraintBuilderComplete<M>;\n\tdeps(...keys: string[]): ConstraintBuilderComplete<M>;\n\ttimeout(ms: number): ConstraintBuilderComplete<M>;\n\tasync(value: boolean): ConstraintBuilderComplete<M>;\n\tbuild(): TypedConstraintDef<M>;\n}\n\n/** Result from when().require() — a valid constraint with optional immutable chaining */\nexport type WhenConstraint<M extends ModuleSchema> = TypedConstraintDef<M> & {\n\twithPriority(n: number): WhenConstraint<M>;\n\twithAfter(...ids: string[]): WhenConstraint<M>;\n\twithDeps(...keys: string[]): WhenConstraint<M>;\n\twithTimeout(ms: number): WhenConstraint<M>;\n\twithAsync(value: boolean): WhenConstraint<M>;\n};\n\n/** Result from when() — must call .require() */\nexport interface WhenBuilder<M extends ModuleSchema> {\n\trequire(req: RequireValue<M>): WhenConstraint<M>;\n}\n\n// ============================================================================\n// constraint() Builder\n// ============================================================================\n\n/**\n * Create a constraint using the full builder pattern.\n * Requires `.when()`, `.require()`, and `.build()`.\n *\n * @example\n * ```typescript\n * const c = constraint<typeof schema>()\n * .when(f => f.phase === \"red\")\n * .require({ type: \"TRANSITION\", to: \"green\" })\n * .priority(50)\n * .after(\"healthCheck\")\n * .build();\n * ```\n */\nexport function constraint<M extends ModuleSchema>(): ConstraintBuilderStart<M> {\n\treturn {\n\t\twhen(condition: WhenFn<M>): ConstraintBuilderWithWhen<M> {\n\t\t\treturn {\n\t\t\t\trequire(req: RequireValue<M>): ConstraintBuilderComplete<M> {\n\t\t\t\t\tlet _priority: number | undefined;\n\t\t\t\t\tlet _after: string[] | undefined;\n\t\t\t\t\tlet _deps: string[] | undefined;\n\t\t\t\t\tlet _timeout: number | undefined;\n\t\t\t\t\tlet _async: boolean | undefined;\n\n\t\t\t\t\tconst complete: ConstraintBuilderComplete<M> = {\n\t\t\t\t\t\tpriority(n) {\n\t\t\t\t\t\t\t_priority = n;\n\t\t\t\t\t\t\treturn complete;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tafter(...ids) {\n\t\t\t\t\t\t\t_after = _after ? [..._after, ...ids] : [...ids];\n\t\t\t\t\t\t\treturn complete;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdeps(...keys) {\n\t\t\t\t\t\t\t_deps = _deps ? [..._deps, ...keys] : [...keys];\n\t\t\t\t\t\t\treturn complete;\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttimeout(ms) {\n\t\t\t\t\t\t\t_timeout = ms;\n\t\t\t\t\t\t\treturn complete;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tasync(value) {\n\t\t\t\t\t\t\t_async = value;\n\t\t\t\t\t\t\treturn complete;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbuild(): TypedConstraintDef<M> {\n\t\t\t\t\t\t\tconst def: TypedConstraintDef<M> = {\n\t\t\t\t\t\t\t\twhen: condition,\n\t\t\t\t\t\t\t\trequire: req,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tif (_priority !== undefined) def.priority = _priority;\n\t\t\t\t\t\t\tif (_after !== undefined) def.after = _after;\n\t\t\t\t\t\t\tif (_deps !== undefined) def.deps = _deps;\n\t\t\t\t\t\t\tif (_timeout !== undefined) def.timeout = _timeout;\n\t\t\t\t\t\t\tif (_async !== undefined) def.async = _async;\n\t\t\t\t\t\t\treturn def;\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\n\t\t\t\t\treturn complete;\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\n// ============================================================================\n// when() Shorthand\n// ============================================================================\n\n/**\n * Create a WhenConstraint — an immutable, chainable object that produces\n * a plain TypedConstraintDef<M> when spread or assigned.\n */\nfunction createWhenConstraint<M extends ModuleSchema>(\n\tbase: TypedConstraintDef<M>,\n): WhenConstraint<M> {\n\tconst obj = { ...base } as WhenConstraint<M>;\n\n\tobj.withPriority = (n: number) =>\n\t\tcreateWhenConstraint<M>({ ...base, priority: n });\n\n\tobj.withAfter = (...ids: string[]) =>\n\t\tcreateWhenConstraint<M>({\n\t\t\t...base,\n\t\t\tafter: base.after ? [...base.after, ...ids] : [...ids],\n\t\t});\n\n\tobj.withDeps = (...keys: string[]) =>\n\t\tcreateWhenConstraint<M>({\n\t\t\t...base,\n\t\t\tdeps: base.deps ? [...base.deps, ...keys] : [...keys],\n\t\t});\n\n\tobj.withTimeout = (ms: number) =>\n\t\tcreateWhenConstraint<M>({ ...base, timeout: ms });\n\n\tobj.withAsync = (value: boolean) =>\n\t\tcreateWhenConstraint<M>({ ...base, async: value });\n\n\treturn obj;\n}\n\n/**\n * Quick shorthand for creating constraints.\n * Returns a valid constraint directly (no `.build()` needed).\n *\n * @example\n * ```typescript\n * const pause = when<typeof schema>(f => f.errors > 3)\n * .require({ type: 'PAUSE' });\n *\n * // With optional chaining (immutable — returns new constraint)\n * const halt = when<typeof schema>(f => f.errors > 10)\n * .require({ type: 'HALT' })\n * .withPriority(100)\n * .withAfter('healthCheck');\n * ```\n */\nexport function when<M extends ModuleSchema>(\n\tcondition: WhenFn<M>,\n): WhenBuilder<M> {\n\treturn {\n\t\trequire(req: RequireValue<M>): WhenConstraint<M> {\n\t\t\treturn createWhenConstraint<M>({ when: condition, require: req });\n\t\t},\n\t};\n}\n","/**\n * System Builder API\n *\n * Fluent builder for creating Directive systems.\n *\n * @example Single module\n * ```typescript\n * import { system } from '@directive-run/core';\n *\n * const sys = system()\n * .module(counterModule)\n * .plugins([loggingPlugin()])\n * .debug({ timeTravel: true })\n * .build();\n * ```\n *\n * @example Multiple modules\n * ```typescript\n * const sys = system()\n * .modules({ auth: authModule, cart: cartModule })\n * .plugins([loggingPlugin()])\n * .build();\n * ```\n */\n\nimport { createSystem } from \"./system.js\";\nimport type {\n\tModuleSchema,\n\tModuleDef,\n\tModulesMap,\n\tPlugin,\n\tDebugConfig,\n\tErrorBoundaryConfig,\n\tInferFacts,\n\tExtractSchema,\n\tSingleModuleSystem,\n\tNamespacedSystem,\n} from \"./types.js\";\n\n// ============================================================================\n// Builder Types\n// ============================================================================\n\n/** Initial builder — must choose .module() or .modules() */\nexport interface SystemBuilderStart {\n\tmodule<S extends ModuleSchema>(mod: ModuleDef<S>): SingleModuleSystemBuilder<S>;\n\tmodules<const Modules extends ModulesMap>(mods: Modules): NamespacedSystemBuilder<Modules>;\n}\n\n/** Builder for single-module system */\nexport interface SingleModuleSystemBuilder<S extends ModuleSchema> {\n\tplugins(plugins: Array<Plugin<ModuleSchema>>): SingleModuleSystemBuilder<S>;\n\tdebug(config: DebugConfig): SingleModuleSystemBuilder<S>;\n\terrorBoundary(config: ErrorBoundaryConfig): SingleModuleSystemBuilder<S>;\n\ttickMs(ms: number): SingleModuleSystemBuilder<S>;\n\tzeroConfig(enabled?: boolean): SingleModuleSystemBuilder<S>;\n\tinitialFacts(facts: Partial<InferFacts<S>>): SingleModuleSystemBuilder<S>;\n\tbuild(): SingleModuleSystem<S>;\n}\n\n/** Builder for namespaced multi-module system */\nexport interface NamespacedSystemBuilder<Modules extends ModulesMap> {\n\tplugins(plugins: Array<Plugin<ModuleSchema>>): NamespacedSystemBuilder<Modules>;\n\tdebug(config: DebugConfig): NamespacedSystemBuilder<Modules>;\n\terrorBoundary(config: ErrorBoundaryConfig): NamespacedSystemBuilder<Modules>;\n\ttickMs(ms: number): NamespacedSystemBuilder<Modules>;\n\tzeroConfig(enabled?: boolean): NamespacedSystemBuilder<Modules>;\n\tinitialFacts(facts: Partial<{\n\t\t[K in keyof Modules]: Partial<InferFacts<ExtractSchema<Modules[K]>>>;\n\t}>): NamespacedSystemBuilder<Modules>;\n\tinitOrder(order: \"auto\" | \"declaration\" | Array<keyof Modules & string>): NamespacedSystemBuilder<Modules>;\n\tbuild(): NamespacedSystem<Modules>;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Create a system using the fluent builder pattern.\n * Choose `.module()` for single-module or `.modules()` for namespaced.\n *\n * @example\n * ```typescript\n * const sys = system()\n * .module(counterModule)\n * .plugins([loggingPlugin()])\n * .build();\n * ```\n */\nexport function system(): SystemBuilderStart {\n\treturn {\n\t\tmodule<S extends ModuleSchema>(mod: ModuleDef<S>): SingleModuleSystemBuilder<S> {\n\t\t\treturn createSingleBuilder<S>(mod);\n\t\t},\n\t\tmodules<const Modules extends ModulesMap>(mods: Modules): NamespacedSystemBuilder<Modules> {\n\t\t\treturn createNamespacedBuilder<Modules>(mods);\n\t\t},\n\t};\n}\n\nfunction createSingleBuilder<S extends ModuleSchema>(\n\tmod: ModuleDef<S>,\n): SingleModuleSystemBuilder<S> {\n\tlet _plugins: Array<Plugin<ModuleSchema>> | undefined;\n\tlet _debug: DebugConfig | undefined;\n\tlet _errorBoundary: ErrorBoundaryConfig | undefined;\n\tlet _tickMs: number | undefined;\n\tlet _zeroConfig: boolean | undefined;\n\tlet _initialFacts: Partial<InferFacts<S>> | undefined;\n\n\tconst builder: SingleModuleSystemBuilder<S> = {\n\t\tplugins(plugins) {\n\t\t\t_plugins = plugins;\n\t\t\treturn builder;\n\t\t},\n\t\tdebug(config) {\n\t\t\t_debug = config;\n\t\t\treturn builder;\n\t\t},\n\t\terrorBoundary(config) {\n\t\t\t_errorBoundary = config;\n\t\t\treturn builder;\n\t\t},\n\t\ttickMs(ms) {\n\t\t\t_tickMs = ms;\n\t\t\treturn builder;\n\t\t},\n\t\tzeroConfig(enabled = true) {\n\t\t\t_zeroConfig = enabled;\n\t\t\treturn builder;\n\t\t},\n\t\tinitialFacts(facts) {\n\t\t\t_initialFacts = facts;\n\t\t\treturn builder;\n\t\t},\n\t\tbuild(): SingleModuleSystem<S> {\n\t\t\treturn createSystem<S>({\n\t\t\t\tmodule: mod,\n\t\t\t\tplugins: _plugins,\n\t\t\t\tdebug: _debug,\n\t\t\t\terrorBoundary: _errorBoundary,\n\t\t\t\ttickMs: _tickMs,\n\t\t\t\tzeroConfig: _zeroConfig,\n\t\t\t\tinitialFacts: _initialFacts,\n\t\t\t});\n\t\t},\n\t};\n\n\treturn builder;\n}\n\nfunction createNamespacedBuilder<Modules extends ModulesMap>(\n\tmods: Modules,\n): NamespacedSystemBuilder<Modules> {\n\tlet _plugins: Array<Plugin<ModuleSchema>> | undefined;\n\tlet _debug: DebugConfig | undefined;\n\tlet _errorBoundary: ErrorBoundaryConfig | undefined;\n\tlet _tickMs: number | undefined;\n\tlet _zeroConfig: boolean | undefined;\n\t// biome-ignore lint/suspicious/noExplicitAny: Partial namespaced facts typing\n\tlet _initialFacts: any;\n\tlet _initOrder: \"auto\" | \"declaration\" | Array<keyof Modules & string> | undefined;\n\n\tconst builder: NamespacedSystemBuilder<Modules> = {\n\t\tplugins(plugins) {\n\t\t\t_plugins = plugins;\n\t\t\treturn builder;\n\t\t},\n\t\tdebug(config) {\n\t\t\t_debug = config;\n\t\t\treturn builder;\n\t\t},\n\t\terrorBoundary(config) {\n\t\t\t_errorBoundary = config;\n\t\t\treturn builder;\n\t\t},\n\t\ttickMs(ms) {\n\t\t\t_tickMs = ms;\n\t\t\treturn builder;\n\t\t},\n\t\tzeroConfig(enabled = true) {\n\t\t\t_zeroConfig = enabled;\n\t\t\treturn builder;\n\t\t},\n\t\tinitialFacts(facts) {\n\t\t\t_initialFacts = facts;\n\t\t\treturn builder;\n\t\t},\n\t\tinitOrder(order) {\n\t\t\t_initOrder = order;\n\t\t\treturn builder;\n\t\t},\n\t\tbuild(): NamespacedSystem<Modules> {\n\t\t\treturn createSystem<Modules>({\n\t\t\t\tmodules: mods,\n\t\t\t\tplugins: _plugins,\n\t\t\t\tdebug: _debug,\n\t\t\t\terrorBoundary: _errorBoundary,\n\t\t\t\ttickMs: _tickMs,\n\t\t\t\tzeroConfig: _zeroConfig,\n\t\t\t\tinitialFacts: _initialFacts,\n\t\t\t\tinitOrder: _initOrder,\n\t\t\t});\n\t\t},\n\t};\n\n\treturn builder;\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\t/** Number of pending (unmet) requirements of this type */\n\tpending: number;\n\t/** Number of inflight (being resolved) requirements of this type */\n\tinflight: number;\n\t/** Number of failed requirements of this type */\n\tfailed: number;\n\t/** Whether any requirements of this type are loading (pending or inflight) */\n\tisLoading: boolean;\n\t/** Whether any requirements of this type have failed */\n\thasError: boolean;\n\t/** Last error for this type (if any) */\n\tlastError: Error | null;\n}\n\n/** Status tracking state */\ninterface StatusState {\n\tpending: Map<string, Set<string>>; // type -> set of requirement IDs\n\tinflight: Map<string, Set<string>>; // type -> set of requirement IDs\n\tfailed: Map<string, Set<string>>; // type -> set of requirement IDs\n\terrors: Map<string, Error>; // type -> last error\n\tlisteners: 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\tplugin: Plugin<never>;\n\tgetStatus: (type: string) => RequirementTypeStatus;\n\tgetAllStatus: () => Map<string, RequirementTypeStatus>;\n\tsubscribe: (listener: () => void) => () => void;\n\treset: () => void;\n} {\n\tconst state: StatusState = {\n\t\tpending: new Map(),\n\t\tinflight: new Map(),\n\t\tfailed: new Map(),\n\t\terrors: new Map(),\n\t\tlisteners: new Set(),\n\t};\n\n\t/** Notify all listeners */\n\tfunction notify(): void {\n\t\tfor (const listener of state.listeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n\n\t/** Get or create a set for a type in a map */\n\tfunction getOrCreateSet(map: Map<string, Set<string>>, type: string): Set<string> {\n\t\tlet set = map.get(type);\n\t\tif (!set) {\n\t\t\tset = new Set();\n\t\t\tmap.set(type, set);\n\t\t}\n\t\treturn set;\n\t}\n\n\t/** Get status for a requirement type */\n\tfunction getStatus(type: string): RequirementTypeStatus {\n\t\tconst pendingSet = state.pending.get(type) ?? new Set();\n\t\tconst inflightSet = state.inflight.get(type) ?? new Set();\n\t\tconst failedSet = state.failed.get(type) ?? new Set();\n\t\tconst lastError = state.errors.get(type) ?? null;\n\n\t\treturn {\n\t\t\tpending: pendingSet.size,\n\t\t\tinflight: inflightSet.size,\n\t\t\tfailed: failedSet.size,\n\t\t\tisLoading: pendingSet.size > 0 || inflightSet.size > 0,\n\t\t\thasError: failedSet.size > 0,\n\t\t\tlastError,\n\t\t};\n\t}\n\n\t/** Get status for all tracked types */\n\tfunction getAllStatus(): Map<string, RequirementTypeStatus> {\n\t\tconst allTypes = new Set([\n\t\t\t...state.pending.keys(),\n\t\t\t...state.inflight.keys(),\n\t\t\t...state.failed.keys(),\n\t\t]);\n\n\t\tconst result = new Map<string, RequirementTypeStatus>();\n\t\tfor (const type of allTypes) {\n\t\t\tresult.set(type, getStatus(type));\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Subscribe to status changes */\n\tfunction subscribe(listener: () => void): () => void {\n\t\tstate.listeners.add(listener);\n\t\treturn () => state.listeners.delete(listener);\n\t}\n\n\t/** Reset all status */\n\tfunction reset(): void {\n\t\tstate.pending.clear();\n\t\tstate.inflight.clear();\n\t\tstate.failed.clear();\n\t\tstate.errors.clear();\n\t\tnotify();\n\t}\n\n\tconst plugin: Plugin<never> = {\n\t\tname: \"requirement-status\",\n\n\t\tonRequirementCreated(req: RequirementWithId) {\n\t\t\tconst type = req.requirement.type;\n\t\t\tgetOrCreateSet(state.pending, type).add(req.id);\n\t\t\t// Clear from failed when a new requirement is created\n\t\t\tstate.failed.get(type)?.delete(req.id);\n\t\t\tnotify();\n\t\t},\n\n\t\tonResolverStart(_resolver: string, req: RequirementWithId) {\n\t\t\tconst type = req.requirement.type;\n\t\t\t// Move from pending to inflight\n\t\t\tstate.pending.get(type)?.delete(req.id);\n\t\t\tgetOrCreateSet(state.inflight, type).add(req.id);\n\t\t\tnotify();\n\t\t},\n\n\t\tonResolverComplete(_resolver: string, req: RequirementWithId) {\n\t\t\tconst type = req.requirement.type;\n\t\t\t// Remove from inflight\n\t\t\tstate.inflight.get(type)?.delete(req.id);\n\t\t\tstate.pending.get(type)?.delete(req.id);\n\t\t\tnotify();\n\t\t},\n\n\t\tonResolverError(_resolver: string, req: RequirementWithId, error: unknown) {\n\t\t\tconst type = req.requirement.type;\n\t\t\t// Move from inflight to failed\n\t\t\tstate.inflight.get(type)?.delete(req.id);\n\t\t\tgetOrCreateSet(state.failed, type).add(req.id);\n\t\t\tstate.errors.set(type, error instanceof Error ? error : new Error(String(error)));\n\t\t\tnotify();\n\t\t},\n\n\t\tonResolverCancel(_resolver: string, req: RequirementWithId) {\n\t\t\tconst type = req.requirement.type;\n\t\t\t// Remove from all tracking\n\t\t\tstate.pending.get(type)?.delete(req.id);\n\t\t\tstate.inflight.get(type)?.delete(req.id);\n\t\t\tnotify();\n\t\t},\n\n\t\tonRequirementMet(req: RequirementWithId) {\n\t\t\tconst type = req.requirement.type;\n\t\t\t// Clean up when requirement is met\n\t\t\tstate.pending.get(type)?.delete(req.id);\n\t\t\tstate.inflight.get(type)?.delete(req.id);\n\t\t\tnotify();\n\t\t},\n\t};\n\n\treturn {\n\t\tplugin,\n\t\tgetStatus,\n\t\tgetAllStatus,\n\t\tsubscribe,\n\t\treset,\n\t};\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\tstatusPlugin: ReturnType<typeof createRequirementStatusPlugin>,\n): (type: string) => RequirementTypeStatus {\n\t// This returns a function that can be used with useSyncExternalStore\n\t// The actual hook implementation would be in the React adapter\n\treturn (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\tModuleDef,\n\tPlugin,\n\tDebugConfig,\n\tErrorBoundaryConfig,\n\tModuleSchema,\n\tSingleModuleSystem,\n} from \"../core/types.js\";\nimport { createRequirementStatusPlugin } from \"./requirement-status.js\";\n\n/** Options for createSystemWithStatus */\nexport interface CreateSystemWithStatusOptions<M extends ModuleSchema> {\n\t/** The module to use for the system */\n\tmodule: ModuleDef<M>;\n\t/** Additional plugins to include alongside the status plugin */\n\t// biome-ignore lint/suspicious/noExplicitAny: Plugin generic contravariance issues\n\tplugins?: Plugin<any>[];\n\t/** Debug configuration */\n\tdebug?: DebugConfig;\n\t/** Error boundary configuration */\n\terrorBoundary?: ErrorBoundaryConfig;\n\t/** Tick interval in milliseconds */\n\ttickMs?: number;\n\t/** Enable zero-config mode */\n\tzeroConfig?: boolean;\n\t/** Initial facts to set on the system */\n\t// biome-ignore lint/suspicious/noExplicitAny: Facts type varies by module\n\tinitialFacts?: Record<string, any>;\n}\n\n/** Return type for createSystemWithStatus */\nexport interface SystemWithStatus<M extends ModuleSchema> {\n\t/**\n\t * The Directive system instance.\n\t * This is a SingleModuleSystem - use system.facts, system.dispatch(), etc.\n\t */\n\tsystem: SingleModuleSystem<M>;\n\t/** The status plugin for use with useRequirementStatus hooks */\n\tstatusPlugin: 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\toptions: CreateSystemWithStatusOptions<M>,\n): SystemWithStatus<M> {\n\t// Create the status plugin\n\tconst statusPlugin = createRequirementStatusPlugin();\n\n\t// Add the plugin to the options\n\tconst existingPlugins = options.plugins ?? [];\n\n\t// Create the system with the status plugin included\n\t// Use type assertion to bypass overload resolution issues\n\t// biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n\tconst allPlugins = [...existingPlugins, statusPlugin.plugin] as Plugin<any>[];\n\t// biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n\tconst system = createSystem({\n\t\tmodule: options.module,\n\t\tplugins: allPlugins,\n\t\tdebug: options.debug,\n\t\terrorBoundary: options.errorBoundary,\n\t\ttickMs: options.tickMs,\n\t\tzeroConfig: options.zeroConfig,\n\t\tinitialFacts: options.initialFacts,\n\t// biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n\t} as any);\n\n\treturn {\n\t\t// The system returned by createSystem with a single module is a SingleModuleSystem\n\t\tsystem: system as SingleModuleSystem<M>,\n\t\tstatusPlugin,\n\t};\n}\n","/**\n * Migration Utilities for Directive\n *\n * Helpers for migrating from Redux, Zustand, or XState to Directive.\n * These utilities help you understand your existing state management\n * and generate equivalent Directive module structures.\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Redux slice configuration (simplified) */\nexport interface ReduxSliceConfig {\n\tname: string;\n\tinitialState: Record<string, unknown>;\n\treducers: Record<string, (state: unknown, action?: { payload?: unknown }) => void>;\n}\n\n/** Zustand store configuration (simplified) */\nexport interface ZustandStoreConfig {\n\tstate: Record<string, unknown>;\n\tactions: Record<string, (...args: unknown[]) => void>;\n}\n\n/** XState machine configuration (simplified) */\nexport interface XStateMachineConfig {\n\tid: string;\n\tinitial: string;\n\tstates: Record<string, { on?: Record<string, string | { target: string }> }>;\n\tcontext?: Record<string, unknown>;\n}\n\n/** Generated Directive module structure */\nexport interface DirectiveModuleStructure {\n\tname: string;\n\tfacts: Record<string, string>;\n\tderivations: Record<string, string>;\n\tevents: Record<string, Record<string, string>>;\n\trequirements: Record<string, unknown>;\n\tinitCode: string;\n\tderiveCode: Record<string, string>;\n\teventsCode: Record<string, string>;\n}\n\n// ============================================================================\n// Redux Migration\n// ============================================================================\n\n/**\n * Analyze a Redux slice and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const reduxConfig = {\n * name: 'counter',\n * initialState: { value: 0, status: 'idle' },\n * reducers: {\n * increment: (state) => { state.value += 1; },\n * decrement: (state) => { state.value -= 1; },\n * },\n * };\n *\n * const structure = analyzeReduxSlice(reduxConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeReduxSlice(config: ReduxSliceConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze initial state to generate facts\n\tfor (const [key, value] of Object.entries(config.initialState)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze reducers to generate events\n\tfor (const reducerName of Object.keys(config.reducers)) {\n\t\t// Simple heuristic: if reducer name suggests payload, add it\n\t\tconst hasPayload = reducerName.includes(\"By\") || reducerName.includes(\"Set\") || reducerName.includes(\"With\");\n\t\tif (hasPayload) {\n\t\t\tevents[reducerName] = { payload: \"t.any()\" };\n\t\t\teventsCode[reducerName] = `(facts, { payload }) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t} else {\n\t\t\tevents[reducerName] = {};\n\t\t\teventsCode[reducerName] = `(facts) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.initialState)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: config.name,\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Zustand Migration\n// ============================================================================\n\n/**\n * Analyze a Zustand store and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const zustandConfig = {\n * state: { count: 0, loading: false },\n * actions: {\n * increment: () => {},\n * decrement: () => {},\n * setLoading: (loading: boolean) => {},\n * },\n * };\n *\n * const structure = analyzeZustandStore(zustandConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeZustandStore(config: ZustandStoreConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze state\n\tfor (const [key, value] of Object.entries(config.state)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze actions\n\tfor (const actionName of Object.keys(config.actions)) {\n\t\tevents[actionName] = {};\n\t\teventsCode[actionName] = `(facts) => {\\n // TODO: Implement ${actionName}\\n }`;\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.state)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: \"store\",\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// XState Migration\n// ============================================================================\n\n/**\n * Analyze an XState machine and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const xstateConfig = {\n * id: 'toggle',\n * initial: 'inactive',\n * states: {\n * inactive: { on: { TOGGLE: 'active' } },\n * active: { on: { TOGGLE: 'inactive' } },\n * },\n * };\n *\n * const structure = analyzeXStateMachine(xstateConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeXStateMachine(config: XStateMachineConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {\n\t\tstate: `t.string<${Object.keys(config.states).map(s => `'${s}'`).join(\" | \")}>()`,\n\t};\n\tconst derivations: Record<string, string> = {};\n\tconst deriveCode: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Add context to facts\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tfacts[key] = inferTypeString(value);\n\t\t}\n\t}\n\n\t// Generate state derivations (isActive, isInactive, etc.)\n\tfor (const stateName of Object.keys(config.states)) {\n\t\tconst derivationName = `is${capitalize(stateName)}`;\n\t\tderivations[derivationName] = \"t.boolean()\";\n\t\tderiveCode[derivationName] = `(facts) => facts.state === '${stateName}'`;\n\t}\n\n\t// Collect all events and their transitions\n\tconst eventTransitions = new Map<string, Map<string, string>>();\n\tfor (const [stateName, stateConfig] of Object.entries(config.states)) {\n\t\tif (!stateConfig.on) continue;\n\t\tfor (const [eventName, target] of Object.entries(stateConfig.on)) {\n\t\t\tif (!eventTransitions.has(eventName)) {\n\t\t\t\teventTransitions.set(eventName, new Map());\n\t\t\t}\n\t\t\tconst targetState = typeof target === \"string\" ? target : target.target;\n\t\t\teventTransitions.get(eventName)!.set(stateName, targetState);\n\t\t}\n\t}\n\n\t// Generate events and handlers\n\tfor (const [eventName, transitions] of eventTransitions) {\n\t\tevents[eventName] = {};\n\n\t\tif (transitions.size === 1) {\n\t\t\tconst firstEntry = [...transitions.entries()][0];\n\t\t\tconst toState = firstEntry ? firstEntry[1] : \"unknown\";\n\t\t\teventsCode[eventName] = `(facts) => {\\n facts.state = '${toState}';\\n }`;\n\t\t} else {\n\t\t\tconst cases = [...transitions.entries()]\n\t\t\t\t.map(([from, to]) => ` case '${from}': facts.state = '${to}'; break;`)\n\t\t\t\t.join(\"\\n\");\n\t\t\teventsCode[eventName] = `(facts) => {\\n switch (facts.state) {\\n${cases}\\n }\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = [` facts.state = '${config.initial}';`];\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tinitLines.push(` facts.${key} = ${JSON.stringify(value)};`);\n\t\t}\n\t}\n\tconst initCode = `(facts) => {\\n${initLines.join(\"\\n\")}\\n }`;\n\n\treturn {\n\t\tname: config.id,\n\t\tfacts,\n\t\tderivations,\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode,\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Code Generation\n// ============================================================================\n\n/**\n * Generate Directive module code from a structure.\n */\nexport function generateModuleCode(structure: DirectiveModuleStructure): string {\n\tconst lines: string[] = [\n\t\t`import { createModule, t } from '@directive-run/core';`,\n\t\t``,\n\t\t`const ${structure.name}Module = createModule('${structure.name}', {`,\n\t\t` schema: {`,\n\t\t` facts: {`,\n\t];\n\n\t// Facts\n\tfor (const [key, type] of Object.entries(structure.facts)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Derivations\n\tlines.push(` derivations: {`);\n\tfor (const [key, type] of Object.entries(structure.derivations)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Events\n\tlines.push(` events: {`);\n\tfor (const [key, schema] of Object.entries(structure.events)) {\n\t\tconst schemaStr = Object.entries(schema)\n\t\t\t.map(([k, v]) => `${k}: ${v}`)\n\t\t\t.join(\", \");\n\t\tlines.push(` ${key}: { ${schemaStr} },`);\n\t}\n\tlines.push(` },`);\n\n\t// Requirements\n\tlines.push(` requirements: {},`);\n\tlines.push(` },`);\n\n\t// Init\n\tlines.push(` init: ${structure.initCode},`);\n\n\t// Derive\n\tif (Object.keys(structure.deriveCode).length > 0) {\n\t\tlines.push(` derive: {`);\n\t\tfor (const [key, code] of Object.entries(structure.deriveCode)) {\n\t\t\tlines.push(` ${key}: ${code},`);\n\t\t}\n\t\tlines.push(` },`);\n\t}\n\n\t// Events handlers\n\tlines.push(` events: {`);\n\tfor (const [key, code] of Object.entries(structure.eventsCode)) {\n\t\tlines.push(` ${key}: ${code},`);\n\t}\n\tlines.push(` },`);\n\n\tlines.push(`});`);\n\tlines.push(``);\n\tlines.push(`export { ${structure.name}Module };`);\n\n\treturn lines.join(\"\\n\");\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Infer a t.* type string from a JavaScript value.\n */\nfunction inferTypeString(value: unknown): string {\n\tif (value === null) return \"t.any().nullable()\";\n\tif (value === undefined) return \"t.any().optional()\";\n\n\tswitch (typeof value) {\n\t\tcase \"number\":\n\t\t\treturn \"t.number()\";\n\t\tcase \"string\":\n\t\t\treturn \"t.string()\";\n\t\tcase \"boolean\":\n\t\t\treturn \"t.boolean()\";\n\t\tcase \"object\":\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\treturn \"t.array(t.any())\";\n\t\t\t}\n\t\t\treturn \"t.object()\";\n\t\tdefault:\n\t\t\treturn \"t.any()\";\n\t}\n}\n\n/**\n * Capitalize first letter.\n */\nfunction capitalize(str: string): string {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// ============================================================================\n// Migration Checklist Generator\n// ============================================================================\n\n/**\n * Generate a migration checklist for a given state management pattern.\n */\nexport function generateMigrationChecklist(\n\tsource: \"redux\" | \"zustand\" | \"xstate\",\n): string[] {\n\tconst common = [\n\t\t\"[ ] Install directive: pnpm add directive\",\n\t\t\"[ ] Create module file(s) for your state\",\n\t\t\"[ ] Define schema with facts, derivations, events\",\n\t\t\"[ ] Implement init function for initial state\",\n\t\t\"[ ] Implement event handlers\",\n\t\t\"[ ] Update imports in consuming code\",\n\t\t\"[ ] Test the new implementation\",\n\t\t\"[ ] Remove old state management code\",\n\t];\n\n\tconst sourceSpecific: Record<string, string[]> = {\n\t\tredux: [\n\t\t\t\"[ ] Convert reducers to event handlers\",\n\t\t\t\"[ ] Convert selectors to derivations\",\n\t\t\t\"[ ] Convert thunks to constraints + resolvers\",\n\t\t\t\"[ ] Update useSelector to useDerived\",\n\t\t\t\"[ ] Update useDispatch to system.dispatch\",\n\t\t],\n\t\tzustand: [\n\t\t\t\"[ ] Convert store state to facts\",\n\t\t\t\"[ ] Convert store actions to events\",\n\t\t\t\"[ ] Convert computed getters to derivations\",\n\t\t\t\"[ ] Update useStore hooks to useDirective hooks\",\n\t\t],\n\t\txstate: [\n\t\t\t\"[ ] Convert machine states to a 'state' fact\",\n\t\t\t\"[ ] Convert state checks to derivations (isActive, etc.)\",\n\t\t\t\"[ ] Convert events to Directive events\",\n\t\t\t\"[ ] Convert guards to constraint 'when' conditions\",\n\t\t\t\"[ ] Convert services/actors to constraints + resolvers\",\n\t\t\t\"[ ] Update useMachine to useDirective hooks\",\n\t\t],\n\t};\n\n\tconst specific = sourceSpecific[source] ?? [];\n\treturn [...specific, ...common];\n}\n","/**\n * @directive-run/core\n *\n * Constraint-driven runtime for TypeScript.\n *\n * Also available:\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 codemods\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\n// ============================================================================\n\nexport type {\n\t// Schema\n\tSchema,\n\tSchemaType,\n\tInferSchema,\n\tInferSchemaType,\n\t// Consolidated Module Schema\n\tModuleSchema,\n\tDerivationsSchema,\n\tEventsSchema,\n\tEventPayloadSchema,\n\tInferFacts,\n\tInferDerivations,\n\tInferSelectorState,\n\tInferEventPayloadFromSchema,\n\tInferEvents,\n\tInferRequirementPayloadFromSchema,\n\tInferRequirements,\n\tInferRequirementTypes,\n\t// Facts\n\tFacts,\n\tFactsSnapshot,\n\tFactsStore,\n\tFactChange,\n\t// Derivations\n\tDerivationsDef,\n\tDerivationState,\n\tDerivedValues,\n\tTypedDerivationsDef,\n\t// Effects\n\tEffectsDef,\n\tEffectCleanup,\n\t// Requirements\n\tRequirement,\n\tRequirementWithId,\n\tRequirementKeyFn,\n\tRequirementPayloadSchema,\n\tRequirementsSchema,\n\tRequirementOutput,\n\t// Constraints\n\tConstraintsDef,\n\tConstraintState,\n\tTypedConstraintDef,\n\tTypedConstraintsDef,\n\t// Resolvers\n\tResolversDef,\n\tResolverContext,\n\tResolverStatus,\n\tRetryPolicy,\n\tBatchConfig,\n\tBatchItemResult,\n\tBatchResolveResults,\n\tTypedResolverContext,\n\tTypedResolverDef,\n\tTypedResolversDef,\n\t// Plugins\n\tPlugin,\n\tReconcileResult,\n\tSnapshot,\n\tRecoveryStrategy,\n\t// Errors\n\tErrorSource,\n\tErrorBoundaryConfig,\n\tRetryLaterConfig,\n\tCircuitBreakerConfig,\n\tCircuitBreakerState,\n\t// Module\n\tModuleDef,\n\tModuleHooks,\n\tTypedEventsDef,\n\t// Events\n\tEventsDef,\n\tSystemEvent,\n\tEventsAccessorFromSchema,\n\tDispatchEventsFromSchema,\n\tFlexibleEventHandler,\n\t// System\n\tSystem,\n\tSystemConfig,\n\tSystemInspection,\n\tSystemSnapshot,\n\tDistributableSnapshotOptions,\n\tDistributableSnapshot,\n\tDebugConfig,\n\tTimeTravelAPI,\n\tTimeTravelState,\n\tSnapshotMeta,\n\tRequirementExplanation,\n\t// Accessors\n\tDeriveAccessor,\n\tEventsAccessor,\n\tFactKeys,\n\tFactReturnType,\n\tDerivationKeys,\n\tDerivationReturnType,\n\tObservableKeys,\n\t// Typed Helper Utilities\n\tTypedConstraint,\n\tTypedResolver,\n\t// Composition (Namespaced Multi-Module)\n\tModulesMap,\n\tNamespacedFacts,\n\tMutableNamespacedFacts,\n\tNamespacedDerivations,\n\tUnionEvents,\n\tNamespacedSystem,\n\tNamespacedEventsAccessor,\n\tCreateSystemOptionsNamed,\n\t// Single Module (no namespace)\n\tCreateSystemOptionsSingle,\n\tSingleModuleSystem,\n\t// Type Guards\n\tSystemMode,\n\tAnySystem,\n\t// Cross-Module Dependencies (for modules)\n\tCrossModuleDeps,\n\tCrossModuleFactsWithSelf,\n\tCrossModuleDerivationFn,\n\tCrossModuleDerivationsDef,\n\tCrossModuleConstraintDef,\n\tCrossModuleConstraintsDef,\n\tCrossModuleEffectDef,\n\tCrossModuleEffectsDef,\n} from \"./core/types.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 * Provides type-safe schema definitions with optional runtime validation:\n *\n * **Basic Types:**\n * - `t.string<T>()` - String type (with optional literal union)\n * - `t.number()` - Number type with `.min()` and `.max()` validation\n * - `t.boolean()` - Boolean type\n * - `t.bigint()` - BigInt type for large integers\n *\n * **Complex Types:**\n * - `t.array<T>()` - Array type with `.of()`, `.nonEmpty()`, `.minLength()`, `.maxLength()`\n * - `t.object<T>()` - Object type with `.shape()`, `.nonNull()`, `.hasKeys()`\n * - `t.record<V>(valueType)` - Record/map type `Record<string, V>`\n * - `t.tuple(types...)` - Fixed-length tuple type\n * - `t.union(types...)` - Union of multiple types\n *\n * **Literal & Enum Types:**\n * - `t.enum(...values)` - String enum from literal values\n * - `t.literal(value)` - Exact value matching (string, number, or boolean)\n *\n * **Wrappers:**\n * - `t.nullable(type)` - Nullable wrapper (`T | null`)\n * - `t.optional(type)` - Optional wrapper (`T | undefined`)\n *\n * **Validation Types:**\n * - `t.date()` - Date type\n * - `t.uuid()` - UUID string format\n * - `t.email()` - Email string format\n * - `t.url()` - URL string format\n *\n * **Escape Hatch:**\n * - `t.any<T>()` - Bypass validation (warns in dev)\n *\n * **Chainable Methods (available on most types):**\n * - `.default(value)` - Set default value\n * - `.transform(fn)` - Transform values\n * - `.brand<B>()` - Add branded/nominal type\n * - `.describe(text)` - Add schema documentation\n * - `.refine(predicate, message)` - Custom validation with error message\n * - `.nullable()` - Make nullable (chainable alternative to `t.nullable()`)\n * - `.optional()` - Make optional (chainable alternative to `t.optional()`)\n * - `.validate(fn)` - Add custom validator\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().describe(\"User's display name\"),\n * status: t.enum(\"idle\", \"loading\", \"success\", \"error\"),\n * user: t.object<User>().nullable(),\n * config: t.object<Config>().optional(),\n * userId: t.string().brand<\"UserId\">(),\n * age: t.number().refine(n => n >= 0, \"Age must be non-negative\"),\n * },\n * derivations: {\n * doubled: t.number(),\n * },\n * events: {\n * increment: {},\n * setStatus: { status: t.enum(\"idle\", \"loading\", \"success\", \"error\") },\n * },\n * requirements: {},\n * };\n * ```\n */\nexport { t, type Branded, type ExtendedSchemaType, type ChainableSchemaType } from \"./core/facts.js\";\n\n// ============================================================================\n// Module & System\n// ============================================================================\n\nexport {\n\tcreateModule,\n\tcreateModuleFactory,\n\ttype ModuleConfig,\n\ttype ModuleConfigWithDeps,\n} from \"./core/module.js\";\nexport { createSystem } from \"./core/system.js\";\nexport {\n\tmodule,\n\ttype ModuleBuilder,\n} from \"./core/builder.js\";\nexport {\n\tconstraint,\n\twhen,\n\ttype ConstraintBuilderStart,\n\ttype ConstraintBuilderWithWhen,\n\ttype ConstraintBuilderComplete,\n\ttype WhenConstraint,\n\ttype WhenBuilder,\n} from \"./core/constraint-builders.js\";\nexport {\n\tsystem,\n\ttype SystemBuilderStart,\n\ttype SingleModuleSystemBuilder,\n\ttype NamespacedSystemBuilder,\n} from \"./core/system-builder.js\";\n\n// Convenience helper for status plugin setup\nexport { createSystemWithStatus } from \"./utils/system-with-status.js\";\n\n// Helper factory functions for external constraint/resolver definitions\nexport {\n\tconstraintFactory,\n\tresolverFactory,\n\ttypedConstraint,\n\ttypedResolver,\n} from \"./core/types.js\";\n\n// ============================================================================\n// Requirements Helpers\n// ============================================================================\n\nexport {\n\treq,\n\tforType,\n\tisRequirementType,\n\tgenerateRequirementId,\n\tRequirementSet,\n} from \"./core/requirements.js\";\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nexport {\n\tisSingleModuleSystem,\n\tisNamespacedSystem,\n} from \"./core/types/composition.js\";\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/**\n * Backoff strategy constants for retry policies.\n * Use for autocomplete when configuring resolver retry policies.\n *\n * @example\n * ```ts\n * import { Backoff } from '@directive-run/core';\n *\n * const resolver = {\n * requirement: \"FETCH_DATA\",\n * retry: {\n * attempts: 3,\n * backoff: Backoff.Exponential, // Autocomplete-friendly!\n * initialDelay: 100,\n * },\n * resolve: async (req, ctx) => { ... },\n * };\n * ```\n */\nexport const Backoff = {\n\t/** No delay between retries */\n\tNone: \"none\",\n\t/** Linear delay increase (initialDelay * attempt) */\n\tLinear: \"linear\",\n\t/** Exponential delay increase (initialDelay * 2^attempt) */\n\tExponential: \"exponential\",\n} as const;\n\n// ============================================================================\n// Lower-level APIs (for advanced use)\n// ============================================================================\n\nexport { createFacts, createFactsStore, createFactsProxy } from \"./core/facts.js\";\nexport { createDerivationsManager } from \"./core/derivations.js\";\nexport { createEffectsManager } from \"./core/effects.js\";\nexport { createConstraintsManager } from \"./core/constraints.js\";\nexport { createResolversManager, type InflightInfo } from \"./core/resolvers.js\";\nexport { createPluginManager } from \"./core/plugins.js\";\nexport {\n\tcreateErrorBoundaryManager,\n\tcreateRetryLaterManager,\n\ttype PendingRetry,\n} from \"./core/errors.js\";\nexport { createTimeTravelManager, createDisabledTimeTravel } from \"./utils/time-travel.js\";\nexport { createEngine } from \"./core/engine.js\";\n\n// ============================================================================\n// Tracking (for custom derivations)\n// ============================================================================\n\nexport {\n\tgetCurrentTracker,\n\tisTracking,\n\twithTracking,\n\twithoutTracking,\n\ttrackAccess,\n} from \"./core/tracking.js\";\n\n// ============================================================================\n// Requirement Status Utilities\n// ============================================================================\n\nexport {\n\tcreateRequirementStatusPlugin,\n\tcreateStatusHook,\n\ttype RequirementTypeStatus,\n} from \"./utils/requirement-status.js\";\n\n// ============================================================================\n// Distributable Snapshot Utilities\n// ============================================================================\n\nexport {\n\tshallowEqual,\n\tisSnapshotExpired,\n\tvalidateSnapshot,\n\tdiffSnapshots,\n\tsignSnapshot,\n\tverifySnapshotSignature,\n\tisSignedSnapshot,\n\ttype DistributableSnapshotLike,\n\ttype SnapshotDiff,\n\ttype SnapshotDiffEntry,\n\ttype SignedSnapshot,\n} from \"./utils/utils.js\";\n\n// ============================================================================\n// Migration Utilities\n// ============================================================================\n\nexport {\n\tanalyzeReduxSlice,\n\tanalyzeZustandStore,\n\tanalyzeXStateMachine,\n\tgenerateModuleCode,\n\tgenerateMigrationChecklist,\n\ttype ReduxSliceConfig,\n\ttype ZustandStoreConfig,\n\ttype XStateMachineConfig,\n\ttype DirectiveModuleStructure,\n} from \"./utils/migration.js\";\n"]}
1
+ {"version":3,"sources":["../src/core/types/errors.ts","../src/core/types/helpers.ts","../src/core/types/composition.ts","../src/core/tracking.ts","../src/core/facts.ts","../src/core/module.ts","../src/utils/utils.ts","../src/core/requirements.ts","../src/core/constraints.ts","../src/core/derivations.ts","../src/core/effects.ts","../src/core/errors.ts","../src/core/plugins.ts","../src/core/resolvers.ts","../src/utils/time-travel.ts","../src/core/engine.ts","../src/core/system.ts","../src/core/builder.ts","../src/core/constraint-builders.ts","../src/core/system-builder.ts","../src/utils/requirement-status.ts","../src/utils/system-with-status.ts","../src/utils/migration.ts","../src/index.ts"],"names":["DirectiveError","message","source","sourceId","context","recoverable","constraintFactory","constraint","resolverFactory","resolver","typedConstraint","typedResolver","isSingleModuleSystem","system","isNamespacedSystem","trackingStack","createTrackingContext","dependencies","key","nullContext","getCurrentTracker","isTracking","withTracking","fn","withoutTracking","saved","trackAccess","safeStringify","value","maxLength","createSchemaType","validators","typeName","defaultValue","transform","description","refinements","createChainableType","v","intermediate","desc","predicate","newRefinements","t","createChainableNumber","n","createChainableArray","elementType","indexRef","chainable","ref","et","newRef","i","item","validator","createChainableObject","shapeSchema","schemaType","schemaT","keys","k","values","valueSet","innerType","innerTypeName","types","typeNames","valueType","valueTypeName","val","uuidRegex","emailRegex","createFactsStore","options","schema","onChange","onBatch","isTypeAssertionSchema","validate","strictKeys","redactErrors","map","knownKeys","keyListeners","allListeners","batching","batchChanges","dirtyKeys","isNotifying","pendingNonBatchedChanges","MAX_NOTIFY_ITERATIONS","isZodSchema","getExpectedType","st","def","formatValueForError","validateValue","result","valuePreview","errorMessage","expectedType","indexHint","validatorHint","notifyKey","listener","notifyAll","notifyNonBatched","prev","iterations","deferred","change","flush","store","keyStr","set","newSchema","BLOCKED_PROPS","createFactsProxy","snapshot","_","prop","createFacts","facts","createModule","id","config","schemaDerivations","deriveImpl","schemaDerivationKeys","deriveKeys","schemaEvents","eventImpl","schemaEventKeys","eventKeys","schemaEventKeysForValidation","eventName","requirementTypes","resolverName","resolverDef","crossModuleDeps","createModuleFactory","name","withTimeout","promise","ms","timeoutId","timeoutPromise","reject","stableStringify","maxDepth","seen","stringify","depth","type","obj","isPrototypeSafe","dangerousKeys","check","objVal","shallowEqual","a","b","keysA","keysB","hashObject","str","hash","isSnapshotExpired","now","validateSnapshot","expiredAt","diffSnapshots","oldSnapshot","newSnapshot","changes","compare","oldObj","newObj","path","oldRecord","newRecord","allKeys","childPath","versionChanged","isSignedSnapshot","signSnapshot","secret","payload","signature","hmacSha256","verifySnapshotSignature","signedSnapshot","expectedSignature","timingSafeEqual","secretBytes","algorithm","messageBytes","generateRequirementId","req","keyFn","rest","sortedRest","createRequirementWithId","requirement","fromConstraint","props","isRequirementType","forType","RequirementSet","_RequirementSet","copy","other","added","removed","unchanged","DEFAULT_TIMEOUT","createConstraintsManager","definitions","requirementKeys","defaultTimeout","onEvaluate","onError","states","disabled","asyncConstraintIds","constraintDeps","factToConstraints","dirtyConstraints","latestWhenDeps","lastRequirements","hasEvaluated","resolvedConstraints","noFireConstraints","dependsOnMe","topologicalOrder","topologicalIndex","buildReverseDependencyMap","depId","detectCyclesAndComputeTopoOrder","visited","visiting","postOrder","visit","cycleStart","cycle","index","isAsyncConstraint","initState","isAsync","state","getState","updateDependencies","newDeps","oldDeps","dep","constraints","evaluateSync","tracked","asyncResult","error","evaluateAsync","timeout","depsSet","resultPromise","MAX_REQUIREMENTS_WARNING_THRESHOLD","normalizeRequirements","output","constraintId","filtered","r","getRequirements","requireDef","deps","mergeDependencies","additionalDeps","existingDeps","sortedConstraintIds","getSortedConstraintIds","stateA","priorityDiff","topoA","topoB","areAfterDependenciesSatisfied","changedKeys","requirements","allConstraintIds","constraintsToEvaluate","affected","dependentConstraints","lastReqs","processConstraintResult","active","whenDeps","reqs","requireDeps","combinedDeps","reqsWithId","reqWithId","evaluateConstraintBatch","constraintIds","blockedConstraints","readyToEvaluate","syncConstraints","asyncConstraints","unexpectedAsync","asyncResults","remainingToEvaluate","maxPasses","previousRemaining","factKey","dependents","newDefs","createDerivationsManager","_store","onCompute","onInvalidate","listeners","factToDerivedDeps","derivedToDerivedDeps","invalidationDepth","pendingNotifications","isFlushing","MAX_FLUSH_ITERATIONS","derivedProxy","computeDerivation","depSet","flushNotifications","remaining","ids","invalidateDerivation","dependent","factKeys","idStr","listenerSet","createEffectsManager","onRun","previousSnapshot","stopped","createSnapshot","shouldRun","runCleanup","storeCleanup","runEffect","effectPromise","trackedDeps","trackingResult","effectsToRun","effectIds","createRetryLaterManager","delayMs","maxRetries","backoffMultiplier","maxDelayMs","pendingRetries","calculateDelay","attempt","delay","callback","entry","dueRetries","DEFAULT_STRATEGIES","createErrorBoundaryManager","onRecovery","errors","maxErrors","retryLaterManager","retryAttempts","toDirectiveError","getStrategy","handler","e","directiveError","strategy","createPluginManager","plugins","safeCall","safeCallAsync","plugin","p","byResolver","duration","from","to","DEFAULT_RETRY","DEFAULT_BATCH","policy","backoff","initialDelay","maxDelay","createResolversManager","onStart","onComplete","onRetry","onCancel","onResolutionComplete","inflight","statuses","MAX_STATUSES","batches","resolversByType","MAX_RESOLVER_CACHE","cleanupStatuses","entriesToRemove","iterator","hasStringRequirement","hasFunctionRequirement","resolverHandles","findResolver","reqType","cached","oldest","typeResolvers","createContext","signal","executeResolve","resolverId","controller","retryPolicy","lastError","ctx","resolvePromise","resolve","abortHandler","executeBatch","batchConfig","startedAt","reqPayloads","results","hasFailures","addToBatch","batch","processBatch","requirementId","status","createTimeTravelManager","onSnapshot","onTimeTravel","isEnabled","maxSnapshots","snapshots","currentIndex","nextId","paused","restoring","changesets","pendingChangesetLabel","pendingChangesetStart","getCurrentFacts","serializeFacts","factsObj","deserializeFacts","serialized","trigger","steps","fromIndex","toIndex","cs","c","earlierCs","snapshotId","s","json","data","snap","label","createDisabledTimeTravel","noopSnapshot","createEngine","mergedSchema","mergedEvents","mergedDerive","mergedEffects","mergedConstraints","mergedResolvers","schemaOwners","module","validateKeys","section","existingOwner","snapshotEventNames","m","mod","dispatchDepth","shouldTakeSnapshot","derivationNames","pluginManager","errorBoundary","invalidateManyDerivations","timeTravelRef","scheduleReconcile","derivationsManager","effectsManager","constraintsManager","resolversManager","notifySettlementChange","timeTravelListeners","notifyTimeTravelChange","timeTravelManager","settlementListeners","MAX_RECONCILE_DEPTH","reconcileDepth","reconcile","keysForConstraints","currentRequirements","currentSet","inflightInfo","deriveAccessor","eventsAccessor","event","derivationId","derivationIds","unsubs","u","isEqual","previousValue","newValue","oldValue","next","old","unsub","timer","cleanup","current","constraintState","resolverStatus","relevantFacts","factsSnapshot","lines","reqDetails","factEntries","prefix","valueStr","maxWait","startTime","inspection","details","unmet","includeDerivations","excludeDerivations","includeFacts","ttlSeconds","metadata","includeVersion","allDerivationKeys","derivationKeys","unknown","excludeSet","allFactKeys","createdAt","previousVersion","registerModule","existingFactKeys","SEPARATOR","topologicalSort","modulesMap","namespaces","namespace","depNamespace","moduleFactsProxyCache","namespacedFactsProxyCache","namespacedDeriveProxyCache","moduleDeriveProxyCache","createSystem","createSingleModuleSystem","namedOptions","createNamespacedSystem","moduleNamespaces","snapshotModulesSet","orderedNamespaces","initOrder","explicitOrder","missingModules","ns","debug","flatModules","hasCrossModuleDeps","depNamespaces","prefixedFacts","prefixedDerivations","prefixedEvents","prefixedInit","moduleFactsProxy","createModuleFactsProxy","prefixedDerive","derive","factsProxy","createCrossModuleFactsProxy","deriveProxy","createModuleDeriveProxy","prefixedEventHandlers","prefixedConstraints","constraintDef","prefixedResolvers","namespacedFacts","createNamespacedFactsProxy","prefixedEffects","effect","effectDef","prevProxy","hydratedFacts","engine","applyNamespacedFacts","namespaceKeysMap","moduleNamesCache","getModuleNames","namespacedFactsProxy","namespacedDeriveProxy","createNamespacedDeriveProxy","namespacedEventsProxy","createNamespacedEventsProxy","tickInterval","tickMs","loader","tickEventKey","toInternalKey","internalIds","internalOptions","namespacedData","sepIndex","localKey","moduleDef","namespaceCache","proxy","crossModuleFactsProxyCache","selfNamespace","cacheKey","depNamesSet","moduleEventsProxyCache","moduleEventsProxy","eventsProxy","_schema","_init","_events","_derive","_effects","_constraints","_resolvers","_hooks","builder","initFn","derivations","events","effects","resolvers","hooks","missingDerives","missingEvents","condition","_priority","_after","_deps","_timeout","_async","complete","createWhenConstraint","base","when","createSingleBuilder","mods","createNamespacedBuilder","_plugins","_debug","_errorBoundary","_tickMs","_zeroConfig","_initialFacts","enabled","_initOrder","order","createRequirementStatusPlugin","notify","getOrCreateSet","getStatus","pendingSet","inflightSet","failedSet","getAllStatus","allTypes","subscribe","reset","_resolver","createStatusHook","statusPlugin","createSystemWithStatus","allPlugins","analyzeReduxSlice","eventsCode","inferTypeString","reducerName","initCode","analyzeZustandStore","actionName","analyzeXStateMachine","deriveCode","stateName","derivationName","capitalize","eventTransitions","stateConfig","target","targetState","transitions","firstEntry","toState","cases","initLines","generateModuleCode","structure","schemaStr","code","generateMigrationChecklist","common","Backoff"],"mappings":"AAsCO,IAAMA,GAAN,cAA6B,KAAM,CACzC,WAAA,CACCC,CAAAA,CACgBC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EAAuB,IAAA,CACtC,CACD,MAAMJ,CAAO,CAAA,CALG,YAAAC,CAAAA,CACA,IAAA,CAAA,QAAA,CAAAC,EACA,IAAA,CAAA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAA,WAAA,C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AE,WAAA,EAAY,CAAIA,CAAAA,CAAI,KAAA,CAAM,CAAC,CACjD,CASO,SAASiiB,EAAAA,CACfrsB,CAAAA,CACW,CACX,IAAMssB,CAAAA,CAAS,CACd,2CAAA,CACA,0CAAA,CACA,mDAAA,CACA,+CAAA,CACA,8BAAA,CACA,sCAAA,CACA,iCAAA,CACA,sCACD,CAAA,CA2BA,OAAO,CAAC,GAzByC,CAChD,KAAA,CAAO,CACN,wCAAA,CACA,sCAAA,CACA,+CAAA,CACA,sCAAA,CACA,2CACD,CAAA,CACA,OAAA,CAAS,CACR,kCAAA,CACA,qCAAA,CACA,6CAAA,CACA,iDACD,CAAA,CACA,MAAA,CAAQ,CACP,8CAAA,CACA,0DAAA,CACA,wCAAA,CACA,oDAAA,CACA,wDAAA,CACA,6CACD,CACD,CAAA,CAEgCtsB,CAAM,CAAA,EAAK,EAAC,CACvB,GAAGssB,CAAM,CAC/B,CCrGO,IAAMC,EAAAA,CAAU,CAEtB,IAAA,CAAM,MAAA,CAEN,MAAA,CAAQ,QAAA,CAER,WAAA,CAAa,aACd","file":"index.js","sourcesContent":["/**\n * Error Types - Type definitions for error handling\n */\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\n/** Error source types */\nexport type ErrorSource = \"constraint\" | \"resolver\" | \"effect\" | \"derivation\" | \"system\";\n\n/**\n * Extended Error class with source tracking, recovery metadata, and\n * arbitrary context for structured error handling within Directive.\n *\n * Thrown or returned by the error boundary manager. The `source` and\n * `sourceId` fields identify where the error originated, and `recoverable`\n * indicates whether the engine can apply a recovery strategy.\n *\n * @param message - Human-readable error description\n * @param source - Which subsystem produced the error (`\"constraint\"`, `\"resolver\"`, `\"effect\"`, `\"derivation\"`, or `\"system\"`)\n * @param sourceId - The ID of the specific constraint, resolver, effect, or derivation that failed\n * @param context - Optional arbitrary data for debugging (e.g., the requirement that triggered a resolver error)\n * @param recoverable - Whether the error boundary can apply a recovery strategy (default `true`; `false` for system errors)\n *\n * @example\n * ```ts\n * try {\n * await system.settle();\n * } catch (err) {\n * if (err instanceof DirectiveError) {\n * console.log(err.source); // \"resolver\"\n * console.log(err.sourceId); // \"fetchUser\"\n * console.log(err.recoverable); // true\n * }\n * }\n * ```\n */\nexport class DirectiveError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly source: ErrorSource,\n\t\tpublic readonly sourceId: string,\n\t\tpublic readonly context?: unknown,\n\t\tpublic readonly recoverable: boolean = true,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"DirectiveError\";\n\t}\n}\n\n/** Recovery strategy for errors */\nexport type RecoveryStrategy = \"skip\" | \"retry\" | \"retry-later\" | \"disable\" | \"throw\";\n\n/**\n * Configuration for retry-later strategy.\n * When an error occurs, the system will wait for `delayMs` before retrying.\n */\nexport interface RetryLaterConfig {\n\t/** Delay in milliseconds before retrying (default: 1000) */\n\tdelayMs?: number;\n\t/** Maximum retries before giving up (default: 3) */\n\tmaxRetries?: number;\n\t/** Backoff multiplier for each retry (default: 2) */\n\tbackoffMultiplier?: number;\n\t/** Maximum delay in milliseconds (default: 30000) */\n\tmaxDelayMs?: number;\n}\n\n/**\n * Circuit breaker configuration for automatic failure protection.\n * After `failureThreshold` consecutive failures, the circuit opens\n * and all requests fail fast for `resetTimeoutMs`.\n */\nexport interface CircuitBreakerConfig {\n\t/** Number of consecutive failures before opening the circuit (default: 5) */\n\tfailureThreshold?: number;\n\t/** Time in milliseconds before attempting to close the circuit (default: 60000) */\n\tresetTimeoutMs?: number;\n\t/** Number of successful requests needed to close a half-open circuit (default: 1) */\n\tsuccessThreshold?: number;\n}\n\n/** Circuit breaker state */\nexport type CircuitBreakerState = \"closed\" | \"open\" | \"half-open\";\n\n/** Error boundary configuration */\nexport interface ErrorBoundaryConfig {\n\tonConstraintError?: RecoveryStrategy | ((error: Error, constraint: string) => void);\n\tonResolverError?: RecoveryStrategy | ((error: Error, resolver: string) => void);\n\tonEffectError?: RecoveryStrategy | ((error: Error, effect: string) => void);\n\tonDerivationError?: RecoveryStrategy | ((error: Error, derivation: string) => void);\n\tonError?: (error: DirectiveError) => void;\n\n\t/** Configuration for retry-later strategy */\n\tretryLater?: RetryLaterConfig;\n\n\t/** Circuit breaker configuration (applies to resolvers only) */\n\tcircuitBreaker?: CircuitBreakerConfig;\n}\n","/**\n * Type Helpers - External typed constraint and resolver definitions\n *\n * These types enable defining constraints and resolvers with full type safety\n * outside of module definitions, while maintaining proper type inference.\n */\n\nimport type { Schema } from \"./schema.js\";\nimport type { Facts } from \"./facts.js\";\nimport type { Requirement, RequirementOutput } from \"./requirements.js\";\nimport type { ResolverContext, RetryPolicy, BatchConfig } from \"./resolvers.js\";\n\n// ============================================================================\n// Typed Constraint Definition\n// ============================================================================\n\n/**\n * External constraint definition with full typing.\n * Use this when defining constraints outside of createModule().\n *\n * @typeParam S - The schema type\n * @typeParam R - The requirement type (defaults to Requirement)\n *\n * @example\n * ```typescript\n * // Define a typed constraint factory\n * const createMaxCountConstraint = <S extends Schema>(\n * maxCount: number\n * ): TypedConstraint<S, { type: \"RESET_COUNT\" }> => ({\n * priority: 10,\n * when: (facts) => (facts as { count: number }).count > maxCount,\n * require: { type: \"RESET_COUNT\" },\n * });\n *\n * // Use in module\n * const module = createModule(\"counter\", {\n * schema: { count: t.number() },\n * constraints: {\n * maxCount: createMaxCountConstraint(100),\n * },\n * });\n * ```\n */\nexport interface TypedConstraint<\n\tS extends Schema,\n\tR extends Requirement = Requirement,\n> {\n\t/** Priority for ordering (higher runs first) */\n\tpriority?: number;\n\t/** Mark this constraint as async (avoids runtime detection) */\n\tasync?: boolean;\n\t/** Condition function (sync or async) */\n\twhen: (facts: Facts<S>) => boolean | Promise<boolean>;\n\t/**\n\t * Requirement(s) to produce when condition is met.\n\t */\n\trequire: RequirementOutput<R> | ((facts: Facts<S>) => RequirementOutput<R>);\n\t/** Timeout for async constraints (ms) */\n\ttimeout?: number;\n\t/**\n\t * Constraint IDs whose resolvers must complete before this constraint is evaluated.\n\t * - If dependency's `when()` returns false, this constraint proceeds (nothing to wait for)\n\t * - If dependency's resolver fails, this constraint remains blocked until it succeeds\n\t * - Cross-module: use the constraint ID as it appears in the merged system\n\t */\n\tafter?: string[];\n}\n\n// ============================================================================\n// Typed Resolver Definition\n// ============================================================================\n\n/**\n * External resolver definition with full typing.\n * Use this when defining resolvers outside of createModule().\n *\n * @typeParam S - The schema type\n * @typeParam R - The requirement type (defaults to Requirement)\n *\n * @example\n * ```typescript\n * // Define a typed resolver factory\n * interface FetchUserReq extends Requirement {\n * type: \"FETCH_USER\";\n * userId: string;\n * }\n *\n * const createFetchUserResolver = <S extends Schema>(\n * fetchFn: (userId: string) => Promise<User>\n * ): TypedResolver<S, FetchUserReq> => ({\n * requirement: (req): req is FetchUserReq => req.type === \"FETCH_USER\",\n * key: (req) => `fetch-user-${req.userId}`,\n * retry: { attempts: 3, backoff: \"exponential\" },\n * resolve: async (req, ctx) => {\n * const user = await fetchFn(req.userId);\n * (ctx.facts as { user: User }).user = user;\n * },\n * });\n * ```\n */\nexport interface TypedResolver<\n\tS extends Schema,\n\tR extends Requirement = Requirement,\n> {\n\t/**\n\t * Requirement type to handle.\n\t * - String: matches `req.type` directly (e.g., `requirement: \"FETCH_USER\"`)\n\t * - Function: type guard predicate (e.g., `requirement: (req) => req.type === \"FETCH_USER\"`)\n\t */\n\trequirement: R[\"type\"] | ((req: Requirement) => req is R);\n\t/** Custom key function for deduplication */\n\tkey?: (req: R) => string;\n\t/** Retry policy */\n\tretry?: RetryPolicy;\n\t/** Timeout for resolver execution (ms) */\n\ttimeout?: number;\n\t/** Batch configuration */\n\tbatch?: BatchConfig;\n\t/** Resolve function for single requirement */\n\tresolve?: (req: R, ctx: ResolverContext<S>) => Promise<void>;\n\t/** Resolve function for batched requirements */\n\tresolveBatch?: (reqs: R[], ctx: ResolverContext<S>) => Promise<void>;\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create a typed constraint factory for a specific schema.\n * This enables creating reusable constraint definitions with proper typing.\n *\n * @example\n * ```typescript\n * const schema = { count: t.number(), threshold: t.number() };\n * const factory = constraintFactory<typeof schema>();\n *\n * const maxCountConstraint = factory.create({\n * when: (facts) => facts.count > facts.threshold,\n * require: { type: \"RESET\" },\n * });\n * ```\n */\nexport function constraintFactory<S extends Schema>() {\n\treturn {\n\t\t/**\n\t\t * Create a typed constraint\n\t\t */\n\t\tcreate<R extends Requirement = Requirement>(\n\t\t\tconstraint: TypedConstraint<S, R>,\n\t\t): TypedConstraint<S, R> {\n\t\t\treturn constraint;\n\t\t},\n\t};\n}\n\n/**\n * Create a typed resolver factory for a specific schema.\n * This enables creating reusable resolver definitions with proper typing.\n *\n * @example\n * ```typescript\n * const schema = { user: t.object<User>() };\n * const factory = resolverFactory<typeof schema>();\n *\n * const fetchUserResolver = factory.create<FetchUserReq>({\n * requirement: (req): req is FetchUserReq => req.type === \"FETCH_USER\",\n * resolve: async (req, ctx) => {\n * ctx.facts.user = await fetchUser(req.userId);\n * },\n * });\n * ```\n */\nexport function resolverFactory<S extends Schema>() {\n\treturn {\n\t\t/**\n\t\t * Create a typed resolver\n\t\t */\n\t\tcreate<R extends Requirement = Requirement>(\n\t\t\tresolver: TypedResolver<S, R>,\n\t\t): TypedResolver<S, R> {\n\t\t\treturn resolver;\n\t\t},\n\t};\n}\n\n// ============================================================================\n// Simple Helper Functions\n// ============================================================================\n\n/**\n * Type-safe constraint creator.\n * Simpler alternative to constraintFactory when you don't need a factory pattern.\n *\n * @example\n * ```typescript\n * const constraint = typedConstraint<typeof schema, { type: \"RESET\" }>({\n * when: (facts) => facts.count > 100,\n * require: { type: \"RESET\" },\n * });\n * ```\n */\nexport function typedConstraint<\n\tS extends Schema,\n\tR extends Requirement = Requirement,\n>(constraint: TypedConstraint<S, R>): TypedConstraint<S, R> {\n\treturn constraint;\n}\n\n/**\n * Type-safe resolver creator.\n * Simpler alternative to resolverFactory when you don't need a factory pattern.\n *\n * @example\n * ```typescript\n * const resolver = typedResolver<typeof schema, FetchUserReq>({\n * requirement: (req): req is FetchUserReq => req.type === \"FETCH_USER\",\n * resolve: async (req, ctx) => {\n * ctx.facts.user = await fetchUser(req.userId);\n * },\n * });\n * ```\n */\nexport function typedResolver<\n\tS extends Schema,\n\tR extends Requirement = Requirement,\n>(resolver: TypedResolver<S, R>): TypedResolver<S, R> {\n\treturn resolver;\n}\n","/**\n * Composition Types - Type definitions for single and multi-module systems\n *\n * Single module = direct access (no namespace):\n * @example\n * ```typescript\n * const system = createSystem({ modules: counterModule });\n * system.facts.count // Direct access\n * system.events.increment() // Direct events\n * ```\n *\n * Multiple modules = namespaced access:\n * @example\n * ```typescript\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n * system.facts.auth.token // Namespaced access\n * system.derive.data.userCount // Namespaced derivations\n * system.events.auth.login() // Namespaced events\n * ```\n */\n\nimport type {\n\tModuleSchema,\n\tInferFacts,\n\tInferDerivations,\n\tInferEvents,\n} from \"./schema.js\";\nimport type { Facts } from \"./facts.js\";\nimport type { ModuleDef } from \"./module.js\";\nimport type {\n\tDebugConfig,\n\tTimeTravelAPI,\n\tSystemInspection,\n\tSystemSnapshot,\n\tDistributableSnapshotOptions,\n\tDistributableSnapshot,\n} from \"./system.js\";\nimport type { Plugin } from \"./plugins.js\";\nimport type { ErrorBoundaryConfig } from \"./errors.js\";\n\n// ============================================================================\n// Module Map Types\n// ============================================================================\n\n/**\n * Extract the schema type from a module definition.\n */\nexport type ExtractSchema<M> = M extends ModuleDef<infer S> ? S : never;\n\n/**\n * Map of module name to module definition (object form).\n *\n * Uses `ModuleDef<any>` instead of `ModuleDef<ModuleSchema>` to preserve\n * specific schema types during inference. The actual schema types are\n * extracted via `ExtractSchema<M>` where needed.\n */\n// biome-ignore lint/suspicious/noExplicitAny: Required for TypeScript to preserve specific module schema types during inference\nexport type ModulesMap = Record<string, ModuleDef<any>>;\n\n// ============================================================================\n// Cross-Module Facts Types (for module-level type hints)\n// ============================================================================\n\n/**\n * Map of module name to schema (for cross-module typing).\n */\nexport type SchemasMap = Record<string, ModuleSchema>;\n\n/**\n * Create namespaced facts type from a map of schemas.\n * Use this to type cross-module effects and constraints within modules.\n *\n * @example\n * ```typescript\n * // types.ts - Create the combined type from schemas\n * import { authSchema } from './modules/auth';\n * import { dataSchema } from './modules/data';\n * import { uiSchema } from './modules/ui';\n * import type { CrossModuleFacts } from '@directive-run/core';\n *\n * export type AllFacts = CrossModuleFacts<{\n * auth: typeof authSchema;\n * data: typeof dataSchema;\n * ui: typeof uiSchema;\n * }>;\n *\n * // modules/ui.ts - Use the combined type in effects\n * import type { AllFacts } from '../types';\n *\n * effects: {\n * onAuthChange: {\n * run: (facts: AllFacts, prev: AllFacts | undefined) => {\n * facts.auth.isAuthenticated // ✅ typed!\n * facts.data.users // ✅ typed!\n * }\n * }\n * }\n * ```\n */\nexport type CrossModuleFacts<Schemas extends SchemasMap> = {\n\t[K in keyof Schemas]: InferFacts<Schemas[K]>;\n};\n\n/**\n * Create namespaced derivations type from a map of schemas.\n * Use this to type cross-module effects that read derivations.\n *\n * @example\n * ```typescript\n * import type { CrossModuleDerivations } from '@directive-run/core';\n *\n * export type AllDerivations = CrossModuleDerivations<{\n * auth: typeof authSchema;\n * data: typeof dataSchema;\n * }>;\n * ```\n */\nexport type CrossModuleDerivations<Schemas extends SchemasMap> = {\n\treadonly [K in keyof Schemas]: InferDerivations<Schemas[K]>;\n};\n\n// ============================================================================\n// Cross-Module Dependencies Types (for module-level crossModuleDeps)\n// ============================================================================\n\n/**\n * Map of namespace to schema for cross-module dependencies.\n * Used in module config to declare type-safe access to other modules' facts.\n */\nexport type CrossModuleDeps = Record<string, ModuleSchema>;\n\n/**\n * Cross-module facts type using \"self\" for own module.\n * Own module accessed via `facts.self.*`, dependencies via `facts.{dep}.*`.\n *\n * @example\n * ```typescript\n * // For a \"data\" module with crossModuleDeps: { auth: authSchema }\n * facts.self.users // ✅ own module via \"self\"\n * facts.auth.isAuthenticated // ✅ cross-module via namespace\n * ```\n */\nexport type CrossModuleFactsWithSelf<\n\tOwnSchema extends ModuleSchema,\n\tDeps extends CrossModuleDeps,\n> = { self: InferFacts<OwnSchema> } & {\n\t[K in keyof Deps]: InferFacts<Deps[K]>;\n};\n\n// ============================================================================\n// Namespaced Facts Types\n// ============================================================================\n\n/**\n * Namespace facts under module keys.\n * `facts.auth.token` instead of `facts.auth_token`\n */\nexport type NamespacedFacts<Modules extends ModulesMap> = {\n\treadonly [K in keyof Modules]: InferFacts<ExtractSchema<Modules[K]>>;\n};\n\n/**\n * Mutable version for constraint/resolver callbacks.\n */\nexport type MutableNamespacedFacts<Modules extends ModulesMap> = {\n\t[K in keyof Modules]: InferFacts<ExtractSchema<Modules[K]>>;\n};\n\n// ============================================================================\n// Namespaced Derivations Types\n// ============================================================================\n\n/**\n * Namespace derivations under module keys.\n * `derive.auth.status` instead of `derive.auth_status`\n */\nexport type NamespacedDerivations<Modules extends ModulesMap> = {\n\treadonly [K in keyof Modules]: InferDerivations<ExtractSchema<Modules[K]>>;\n};\n\n// ============================================================================\n// Union Event Types\n// ============================================================================\n\n/**\n * Union of all module events (not namespaced).\n * Events stay as discriminated union for dispatch.\n */\nexport type UnionEvents<Modules extends ModulesMap> = {\n\t[K in keyof Modules]: InferEvents<ExtractSchema<Modules[K]>>;\n}[keyof Modules];\n\n// ============================================================================\n// Namespaced System Options\n// ============================================================================\n\n/**\n * Options for createSystem with object modules (namespaced mode).\n */\nexport interface CreateSystemOptionsNamed<Modules extends ModulesMap> {\n\t/** Modules as object = namespaced access */\n\tmodules: Modules;\n\t/** Plugins to register */\n\tplugins?: Array<Plugin<ModuleSchema>>;\n\t/** Debug configuration */\n\tdebug?: DebugConfig;\n\t/** Error boundary configuration */\n\terrorBoundary?: ErrorBoundaryConfig;\n\t/**\n\t * Tick interval for time-based systems (ms).\n\t */\n\ttickMs?: number;\n\t/**\n\t * Enable zero-config mode with sensible defaults.\n\t */\n\tzeroConfig?: boolean;\n\t/**\n\t * Initial facts to set after module init (namespaced format).\n\t * Applied after all module `init()` functions but before reconciliation.\n\t *\n\t * @example\n\t * ```typescript\n\t * createSystem({\n\t * modules: { auth, data },\n\t * initialFacts: {\n\t * auth: { token: \"restored-token\", user: cachedUser },\n\t * data: { users: preloadedUsers },\n\t * },\n\t * });\n\t * ```\n\t */\n\tinitialFacts?: Partial<{\n\t\t[K in keyof Modules]: Partial<InferFacts<ExtractSchema<Modules[K]>>>;\n\t}>;\n\t/**\n\t * Init order strategy:\n\t * - \"auto\" (default): Sort by crossModuleDeps topology\n\t * - \"declaration\": Use object key order (current behavior)\n\t * - string[]: Explicit order by namespace\n\t */\n\tinitOrder?: \"auto\" | \"declaration\" | Array<keyof Modules & string>;\n}\n\n// ============================================================================\n// Namespaced System Interface\n// ============================================================================\n\n/**\n * System interface for namespaced modules.\n * Facts and derivations are accessed via module namespaces.\n */\nexport interface NamespacedSystem<Modules extends ModulesMap> {\n\t/** System mode discriminator for type guards */\n\treadonly _mode: \"namespaced\";\n\t/** Namespaced facts accessor: system.facts.auth.token */\n\treadonly facts: MutableNamespacedFacts<Modules>;\n\t/** Time-travel debugging API (if enabled) */\n\treadonly debug: TimeTravelAPI | null;\n\t/** Namespaced derivations accessor: system.derive.auth.status */\n\treadonly derive: NamespacedDerivations<Modules>;\n\t/** Events accessor (union of all module events) */\n\treadonly events: NamespacedEventsAccessor<Modules>;\n\n\t/** Start the system (initialize modules, begin reconciliation) */\n\tstart(): void;\n\t/** Stop the system (cancel resolvers, stop reconciliation) */\n\tstop(): void;\n\t/** Destroy the system (stop and cleanup) */\n\tdestroy(): void;\n\n\t/** Whether the system is currently running */\n\treadonly isRunning: boolean;\n\t/** Whether all resolvers have completed */\n\treadonly isSettled: boolean;\n\t/** Whether all modules have completed initialization */\n\treadonly isInitialized: boolean;\n\t/** Whether system has completed first reconciliation */\n\treadonly isReady: boolean;\n\n\t/** Wait for system to be fully ready (after first reconciliation) */\n\twhenReady(): Promise<void>;\n\n\t/**\n\t * Hydrate facts from async source (call before start).\n\t * Useful for restoring state from localStorage, API, etc.\n\t *\n\t * @example\n\t * ```typescript\n\t * const system = createSystem({ modules: { auth, data } });\n\t * await system.hydrate(async () => {\n\t * const stored = localStorage.getItem(\"app-state\");\n\t * return stored ? JSON.parse(stored) : {};\n\t * });\n\t * system.start();\n\t * ```\n\t */\n\thydrate(\n\t\tloader: () => Promise<Partial<{\n\t\t\t[K in keyof Modules]: Partial<InferFacts<ExtractSchema<Modules[K]>>>;\n\t\t}>> | Partial<{\n\t\t\t[K in keyof Modules]: Partial<InferFacts<ExtractSchema<Modules[K]>>>;\n\t\t}>,\n\t): Promise<void>;\n\n\t/** Dispatch an event (union of all module events) */\n\tdispatch(event: UnionEvents<Modules>): void;\n\n\t/** Batch multiple fact changes */\n\tbatch(fn: () => void): void;\n\n\t/**\n\t * Subscribe to settlement state changes.\n\t * Called whenever the system's settled state may have changed\n\t * (resolver starts/completes, reconcile starts/ends).\n\t */\n\tonSettledChange(listener: () => void): () => void;\n\n\t/** Subscribe to time-travel state changes (snapshot taken, navigation). */\n\tonTimeTravelChange(listener: () => void): () => void;\n\n\t/**\n\t * Read a derivation value by namespaced key.\n\t * Accepts \"namespace.key\" format (e.g., \"auth.status\").\n\t *\n\t * @example\n\t * system.read(\"auth.status\") // → \"authenticated\"\n\t * system.read(\"data.count\") // → 5\n\t */\n\tread<T = unknown>(derivationId: string): T;\n\n\t/**\n\t * Subscribe to fact or derivation changes using namespaced keys.\n\t * Keys are auto-detected — pass any mix of fact keys and derivation keys.\n\t * Accepts \"namespace.key\" format (e.g., \"auth.status\", \"auth.token\").\n\t * Supports wildcard \"namespace.*\" to subscribe to all keys in a module.\n\t *\n\t * @example\n\t * system.subscribe([\"auth.token\", \"data.count\"], () => {\n\t * console.log(\"Auth or data changed\");\n\t * });\n\t *\n\t * @example Wildcard\n\t * system.subscribe([\"game.*\"], () => render());\n\t */\n\tsubscribe(ids: string[], listener: () => void): () => void;\n\n\t/**\n\t * Subscribe to ALL fact and derivation changes in a module namespace.\n\t * Shorthand for subscribing to every key in a module.\n\t *\n\t * @example\n\t * system.subscribeModule(\"game\", () => render());\n\t * system.subscribeModule(\"chat\", () => render());\n\t */\n\tsubscribeModule(namespace: keyof Modules & string, listener: () => void): () => void;\n\n\t/**\n\t * Watch a fact or derivation for changes using namespaced key.\n\t * The key is auto-detected -- works with both fact keys and derivation keys.\n\t * Accepts \"namespace.key\" format (e.g., \"auth.status\", \"auth.token\").\n\t * Pass `options.equalityFn` for custom comparison (e.g., shallow equality for objects).\n\t *\n\t * @example\n\t * system.watch(\"auth.token\", (newVal, oldVal) => {\n\t * console.log(`Token changed from ${oldVal} to ${newVal}`);\n\t * });\n\t */\n\twatch<T = unknown>(\n\t\tid: string,\n\t\tcallback: (newValue: T, previousValue: T | undefined) => void,\n\t\toptions?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n\t): () => void;\n\n\t/**\n\t * Returns a promise that resolves when the predicate becomes true.\n\t * The predicate is evaluated against current facts and re-evaluated on every change.\n\t * Uses namespaced facts: `facts.auth.token`, `facts.data.count`, etc.\n\t * Optionally pass a timeout in ms -- rejects with an error if exceeded.\n\t *\n\t * @example\n\t * await system.when((facts) => facts.auth.token !== null);\n\t * await system.when((facts) => facts.auth.token !== null, { timeout: 5000 });\n\t */\n\twhen(\n\t\tpredicate: (facts: Readonly<MutableNamespacedFacts<Modules>>) => boolean,\n\t\toptions?: { timeout?: number },\n\t): Promise<void>;\n\n\t/** Inspect system state */\n\tinspect(): SystemInspection;\n\t/** Wait for system to settle (all resolvers complete) */\n\tsettle(maxWait?: number): Promise<void>;\n\t/** Explain why a requirement exists */\n\texplain(requirementId: string): string | null;\n\t/** Get serializable snapshot of system state */\n\tgetSnapshot(): SystemSnapshot;\n\t/** Restore system state from snapshot */\n\trestore(snapshot: SystemSnapshot): void;\n\n\t/**\n\t * Register a new module into a running system.\n\t * The module is initialized, wired into constraint/resolver/derivation graphs,\n\t * and reconciliation is triggered.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Lazy-load a module\n\t * const chatModule = await import('./modules/chat');\n\t * system.registerModule(\"chat\", chatModule.default);\n\t * ```\n\t */\n\tregisterModule<S extends ModuleSchema>(\n\t\tnamespace: string,\n\t\tmoduleDef: ModuleDef<S>,\n\t): void;\n\n\t/**\n\t * Get a distributable snapshot of computed derivations.\n\t * Use \"namespace.key\" format for derivation keys.\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = system.getDistributableSnapshot({\n\t * includeDerivations: ['auth.effectivePlan', 'auth.canUseFeature'],\n\t * ttlSeconds: 3600,\n\t * });\n\t * await redis.setex(`entitlements:${userId}`, 3600, JSON.stringify(snapshot));\n\t * ```\n\t */\n\tgetDistributableSnapshot<T = Record<string, unknown>>(\n\t\toptions?: DistributableSnapshotOptions,\n\t): DistributableSnapshot<T>;\n\n\t/**\n\t * Watch for changes to distributable snapshot derivations.\n\t * Calls the callback whenever any of the included derivations change.\n\t * Use \"namespace.key\" format for derivation keys.\n\t * Returns an unsubscribe function.\n\t *\n\t * @example\n\t * ```typescript\n\t * const unsubscribe = system.watchDistributableSnapshot(\n\t * { includeDerivations: ['auth.effectivePlan', 'auth.canUseFeature'] },\n\t * (snapshot) => {\n\t * await redis.setex(`entitlements:${userId}`, 3600, JSON.stringify(snapshot));\n\t * }\n\t * );\n\t * ```\n\t */\n\twatchDistributableSnapshot<T = Record<string, unknown>>(\n\t\toptions: DistributableSnapshotOptions,\n\t\tcallback: (snapshot: DistributableSnapshot<T>) => void,\n\t): () => void;\n}\n\n/**\n * Events accessor that groups event dispatchers by module namespace.\n */\nexport type NamespacedEventsAccessor<Modules extends ModulesMap> = {\n\treadonly [K in keyof Modules]: EventsDispatcherForModule<Modules[K]>;\n};\n\n/**\n * Event dispatcher functions for a single module.\n */\ntype EventsDispatcherForModule<M> = M extends ModuleDef<infer S>\n\t? S extends ModuleSchema\n\t\t? S[\"events\"] extends Record<string, unknown>\n\t\t\t? {\n\t\t\t\t\t[E in keyof S[\"events\"]]: S[\"events\"][E] extends Record<string, unknown>\n\t\t\t\t\t\t? keyof S[\"events\"][E] extends never\n\t\t\t\t\t\t\t? () => void\n\t\t\t\t\t\t\t: (payload: InferEventPayload<S[\"events\"][E]>) => void\n\t\t\t\t\t\t: () => void;\n\t\t\t\t}\n\t\t\t: Record<string, never>\n\t\t: Record<string, never>\n\t: Record<string, never>;\n\n/**\n * Infer event payload from event schema.\n */\ntype InferEventPayload<E> = E extends Record<string, unknown>\n\t? { [K in keyof E]: E[K] extends { _type: infer T } ? T : E[K] }\n\t: never;\n\n// ============================================================================\n// Merged Schema Type (for internal use)\n// ============================================================================\n\n/**\n * Merge multiple module schemas into a single flat schema.\n * Used internally by the engine for storage.\n *\n * @example\n * ```typescript\n * // auth: { facts: { token: string } }\n * // data: { facts: { users: User[] } }\n * // Merged: { auth_token: string, data_users: User[] }\n * ```\n */\nexport type MergedModuleSchema<Modules extends ModulesMap> = {\n\tfacts: MergeFactsWithPrefix<Modules>;\n\tderivations: MergeDerivationsWithPrefix<Modules>;\n\tevents: MergeEventsWithPrefix<Modules>;\n\trequirements: MergeRequirementsWithPrefix<Modules>;\n};\n\ntype MergeFactsWithPrefix<Modules extends ModulesMap> = {\n\t[K in keyof Modules as `${K & string}::${keyof ExtractSchema<Modules[K]>[\"facts\"] & string}`]: ExtractSchema<Modules[K]>[\"facts\"][keyof ExtractSchema<Modules[K]>[\"facts\"]];\n};\n\ntype MergeDerivationsWithPrefix<Modules extends ModulesMap> = {\n\t[K in keyof Modules as ExtractSchema<Modules[K]>[\"derivations\"] extends Record<string, unknown>\n\t\t? `${K & string}::${keyof ExtractSchema<Modules[K]>[\"derivations\"] & string}`\n\t\t: never]: ExtractSchema<Modules[K]>[\"derivations\"] extends Record<string, unknown>\n\t\t? ExtractSchema<Modules[K]>[\"derivations\"][keyof ExtractSchema<Modules[K]>[\"derivations\"]]\n\t\t: never;\n};\n\ntype MergeEventsWithPrefix<Modules extends ModulesMap> = {\n\t[K in keyof Modules as ExtractSchema<Modules[K]>[\"events\"] extends Record<string, unknown>\n\t\t? `${K & string}::${keyof ExtractSchema<Modules[K]>[\"events\"] & string}`\n\t\t: never]: ExtractSchema<Modules[K]>[\"events\"] extends Record<string, unknown>\n\t\t? ExtractSchema<Modules[K]>[\"events\"][keyof ExtractSchema<Modules[K]>[\"events\"]]\n\t\t: never;\n};\n\ntype MergeRequirementsWithPrefix<Modules extends ModulesMap> = {\n\t[K in keyof Modules as ExtractSchema<Modules[K]>[\"requirements\"] extends Record<string, unknown>\n\t\t? keyof ExtractSchema<Modules[K]>[\"requirements\"] & string\n\t\t: never]: ExtractSchema<Modules[K]>[\"requirements\"] extends Record<string, unknown>\n\t\t? ExtractSchema<Modules[K]>[\"requirements\"][keyof ExtractSchema<Modules[K]>[\"requirements\"]]\n\t\t: never;\n};\n\n// ============================================================================\n// Single Module Types (no namespace)\n// ============================================================================\n\n/**\n * Options for createSystem with a single module (no namespacing).\n */\nexport interface CreateSystemOptionsSingle<S extends ModuleSchema> {\n\t/** Single module = direct access (use `modules` for multiple) */\n\tmodule: ModuleDef<S>;\n\t/** Plugins to register */\n\tplugins?: Array<Plugin<ModuleSchema>>;\n\t/** Debug configuration */\n\tdebug?: DebugConfig;\n\t/** Error boundary configuration */\n\terrorBoundary?: ErrorBoundaryConfig;\n\t/** Tick interval for time-based systems (ms) */\n\ttickMs?: number;\n\t/** Enable zero-config mode with sensible defaults */\n\tzeroConfig?: boolean;\n\t/**\n\t * Initial facts to set after module init.\n\t * Applied after module `init()` but before reconciliation.\n\t */\n\tinitialFacts?: Partial<InferFacts<S>>;\n}\n\n/**\n * System interface for a single module (no namespace).\n * Facts, derivations, and events are accessed directly.\n */\nexport interface SingleModuleSystem<S extends ModuleSchema> {\n\t/** System mode discriminator for type guards */\n\treadonly _mode: \"single\";\n\t/** Direct facts accessor: system.facts.count */\n\treadonly facts: Facts<S[\"facts\"]>;\n\t/** Time-travel debugging API (if enabled) */\n\treadonly debug: TimeTravelAPI | null;\n\t/** Direct derivations accessor: system.derive.doubled */\n\treadonly derive: InferDerivations<S>;\n\t/** Direct events accessor: system.events.increment() */\n\treadonly events: SingleModuleEvents<S>;\n\n\t/** Start the system (initialize modules, begin reconciliation) */\n\tstart(): void;\n\t/** Stop the system (cancel resolvers, stop reconciliation) */\n\tstop(): void;\n\t/** Destroy the system (stop and cleanup) */\n\tdestroy(): void;\n\n\t/** Whether the system is currently running */\n\treadonly isRunning: boolean;\n\t/** Whether all resolvers have completed */\n\treadonly isSettled: boolean;\n\t/** Whether module has completed initialization */\n\treadonly isInitialized: boolean;\n\t/** Whether system has completed first reconciliation */\n\treadonly isReady: boolean;\n\n\t/** Wait for system to be fully ready (after first reconciliation) */\n\twhenReady(): Promise<void>;\n\n\t/**\n\t * Hydrate facts from async source (call before start).\n\t */\n\thydrate(\n\t\tloader: () => Promise<Partial<InferFacts<S>>> | Partial<InferFacts<S>>,\n\t): Promise<void>;\n\n\t/** Dispatch an event */\n\tdispatch(event: InferEvents<S>): void;\n\n\t/** Batch multiple fact changes */\n\tbatch(fn: () => void): void;\n\n\t/**\n\t * Subscribe to settlement state changes.\n\t * Called whenever the system's settled state may have changed\n\t * (resolver starts/completes, reconcile starts/ends).\n\t */\n\tonSettledChange(listener: () => void): () => void;\n\n\t/** Subscribe to time-travel state changes (snapshot taken, navigation). */\n\tonTimeTravelChange(listener: () => void): () => void;\n\n\t/**\n\t * Read a derivation value by key.\n\t * @example system.read(\"doubled\")\n\t */\n\tread<T = unknown>(derivationId: string): T;\n\n\t/**\n\t * Subscribe to fact or derivation changes.\n\t * Keys are auto-detected -- pass any mix of fact keys and derivation keys.\n\t * @example system.subscribe([\"count\", \"doubled\"], () => { ... })\n\t */\n\tsubscribe(ids: string[], listener: () => void): () => void;\n\n\t/**\n\t * Watch a fact or derivation for value changes.\n\t * The key is auto-detected -- works with both fact keys and derivation keys.\n\t * Pass `options.equalityFn` for custom comparison (e.g., shallow equality for objects).\n\t * @example system.watch(\"count\", (newVal, oldVal) => { ... })\n\t * @example system.watch(\"derived\", cb, { equalityFn: shallowEqual })\n\t */\n\twatch<T = unknown>(\n\t\tid: string,\n\t\tcallback: (newValue: T, previousValue: T | undefined) => void,\n\t\toptions?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n\t): () => void;\n\n\t/**\n\t * Returns a promise that resolves when the predicate becomes true.\n\t * The predicate is evaluated against current facts and re-evaluated on every change.\n\t * Optionally pass a timeout in ms -- rejects with an error if exceeded.\n\t *\n\t * @example\n\t * await system.when((facts) => facts.count > 10);\n\t * await system.when((facts) => facts.count > 10, { timeout: 5000 });\n\t */\n\twhen(\n\t\tpredicate: (facts: Readonly<InferFacts<S>>) => boolean,\n\t\toptions?: { timeout?: number },\n\t): Promise<void>;\n\n\t/** Inspect system state */\n\tinspect(): SystemInspection;\n\t/** Wait for system to settle (all resolvers complete) */\n\tsettle(maxWait?: number): Promise<void>;\n\t/** Explain why a requirement exists */\n\texplain(requirementId: string): string | null;\n\t/** Get serializable snapshot of system state */\n\tgetSnapshot(): SystemSnapshot;\n\t/** Restore system state from snapshot */\n\trestore(snapshot: SystemSnapshot): void;\n\n\t/**\n\t * Register a new module into a running system.\n\t * Module facts, derivations, effects, constraints, and resolvers are merged\n\t * into the existing engine and reconciliation is triggered.\n\t *\n\t * @example\n\t * ```typescript\n\t * const analyticsModule = await import('./modules/analytics');\n\t * system.registerModule(analyticsModule.default);\n\t * ```\n\t */\n\tregisterModule<S2 extends ModuleSchema>(moduleDef: ModuleDef<S2>): void;\n\n\t/**\n\t * Get a distributable snapshot of computed derivations.\n\t *\n\t * @example\n\t * ```typescript\n\t * const snapshot = system.getDistributableSnapshot({\n\t * includeDerivations: ['effectivePlan', 'canUseFeature'],\n\t * ttlSeconds: 3600,\n\t * });\n\t * await redis.setex(`entitlements:${userId}`, 3600, JSON.stringify(snapshot));\n\t * ```\n\t */\n\tgetDistributableSnapshot<T = Record<string, unknown>>(\n\t\toptions?: DistributableSnapshotOptions,\n\t): DistributableSnapshot<T>;\n\n\t/**\n\t * Watch for changes to distributable snapshot derivations.\n\t * Calls the callback whenever any of the included derivations change.\n\t * Returns an unsubscribe function.\n\t *\n\t * @example\n\t * ```typescript\n\t * const unsubscribe = system.watchDistributableSnapshot(\n\t * { includeDerivations: ['effectivePlan', 'canUseFeature'] },\n\t * (snapshot) => {\n\t * await redis.setex(`entitlements:${userId}`, 3600, JSON.stringify(snapshot));\n\t * }\n\t * );\n\t * ```\n\t */\n\twatchDistributableSnapshot<T = Record<string, unknown>>(\n\t\toptions: DistributableSnapshotOptions,\n\t\tcallback: (snapshot: DistributableSnapshot<T>) => void,\n\t): () => void;\n}\n\n/**\n * Events dispatcher for a single module (direct access).\n */\ntype SingleModuleEvents<S extends ModuleSchema> = S[\"events\"] extends Record<\n\tstring,\n\tunknown\n>\n\t? {\n\t\t\t[E in keyof S[\"events\"]]: S[\"events\"][E] extends Record<string, unknown>\n\t\t\t\t? keyof S[\"events\"][E] extends never\n\t\t\t\t\t? () => void\n\t\t\t\t\t: (payload: InferEventPayload<S[\"events\"][E]>) => void\n\t\t\t\t: () => void;\n\t\t}\n\t: Record<string, never>;\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * System mode discriminator.\n * - \"single\": Single module with direct access (`system.facts.count`)\n * - \"namespaced\": Multiple modules with namespaced access (`system.facts.auth.token`)\n */\nexport type SystemMode = \"single\" | \"namespaced\";\n\n/**\n * Base system type for type guards.\n * Use this for functions that accept either system type.\n */\nexport interface AnySystem {\n\treadonly _mode: SystemMode;\n\treadonly isRunning: boolean;\n\treadonly isSettled: boolean;\n\treadonly isInitialized: boolean;\n\treadonly isReady: boolean;\n\tstart(): void;\n\tstop(): void;\n\tdestroy(): void;\n}\n\n/**\n * Check if a system is a single module system.\n * Returns true if the system was created with `module:` (singular).\n *\n * @example\n * ```typescript\n * const system = createSystem({ module: counterModule });\n *\n * if (isSingleModuleSystem(system)) {\n * // system._mode === \"single\"\n * console.log(system.facts.count);\n * }\n * ```\n */\nexport function isSingleModuleSystem(system: AnySystem): boolean {\n\treturn system._mode === \"single\";\n}\n\n/**\n * Check if a system is a namespaced (multi-module) system.\n * Returns true if the system was created with `modules:` (plural, object).\n *\n * @example\n * ```typescript\n * const system = createSystem({ modules: { auth, data } });\n *\n * if (isNamespacedSystem(system)) {\n * // system._mode === \"namespaced\"\n * console.log(system.facts.auth.token);\n * }\n * ```\n */\nexport function isNamespacedSystem(system: AnySystem): boolean {\n\treturn system._mode === \"namespaced\";\n}\n","/**\n * Dependency tracking context for auto-tracking derivations\n *\n * Uses a stack-based approach to handle nested derivation computations.\n * When a derivation accesses a fact, the tracking context records it.\n */\n\nimport type { TrackingContext } from \"./types.js\";\n\n/** Stack of active tracking contexts */\nconst trackingStack: TrackingContext[] = [];\n\n/** Create a new tracking context */\nfunction createTrackingContext(): TrackingContext {\n\tconst dependencies = new Set<string>();\n\n\treturn {\n\t\tget isTracking() {\n\t\t\treturn true;\n\t\t},\n\t\ttrack(key: string) {\n\t\t\tdependencies.add(key);\n\t\t},\n\t\tgetDependencies() {\n\t\t\treturn dependencies;\n\t\t},\n\t};\n}\n\n/** Null tracking context when not tracking */\nconst nullContext: TrackingContext = {\n\tisTracking: false,\n\ttrack() {},\n\tgetDependencies() {\n\t\treturn new Set();\n\t},\n};\n\n/**\n * Get the current tracking context.\n * Returns null context if no tracking is active.\n */\nexport function getCurrentTracker(): TrackingContext {\n\treturn trackingStack[trackingStack.length - 1] ?? nullContext;\n}\n\n/**\n * Check if we're currently tracking dependencies.\n */\nexport function isTracking(): boolean {\n\treturn trackingStack.length > 0;\n}\n\n/**\n * Run a function with dependency tracking.\n * Returns the computed value and the set of dependencies accessed.\n */\nexport function withTracking<T>(fn: () => T): { value: T; deps: Set<string> } {\n\tconst context = createTrackingContext();\n\ttrackingStack.push(context);\n\n\ttry {\n\t\tconst value = fn();\n\t\treturn { value, deps: context.getDependencies() };\n\t} finally {\n\t\ttrackingStack.pop();\n\t}\n}\n\n/**\n * Run a function without tracking.\n * Useful for reading facts without creating dependencies.\n */\nexport function withoutTracking<T>(fn: () => T): T {\n\t// Temporarily clear the stack\n\tconst saved = trackingStack.splice(0, trackingStack.length);\n\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\t// Restore the stack\n\t\ttrackingStack.push(...saved);\n\t}\n}\n\n/**\n * Track a specific key in the current context.\n * No-op if not currently tracking.\n */\nexport function trackAccess(key: string): void {\n\tgetCurrentTracker().track(key);\n}\n","/**\n * Facts Store - Proxy-based reactive state with auto-tracking\n *\n * Features:\n * - Proxy-based access (facts.phase instead of facts.get(\"phase\"))\n * - Automatic dependency tracking via tracking context\n * - Batched updates with coalesced notifications\n * - Granular subscriptions by key\n * - Schema validation in development mode\n */\n\nimport { trackAccess, withoutTracking } from \"./tracking.js\";\nimport type {\n\tFacts,\n\tFactsSnapshot,\n\tFactsStore,\n\tInferSchema,\n\tSchema,\n\tSchemaType,\n} 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\treadonly _typeName?: string;\n\treadonly _default?: T | (() => T);\n\treadonly _transform?: (value: unknown) => T;\n\treadonly _description?: string;\n\treadonly _refinements?: Array<{ predicate: (value: T) => boolean; message: string }>;\n\t/** Mutable - set by array validators to indicate which element failed */\n\t_lastFailedIndex?: number;\n}\n\n/** Safely stringify a value for error messages */\nfunction safeStringify(value: unknown, maxLength = 100): string {\n\ttry {\n\t\treturn JSON.stringify(value)?.slice(0, maxLength) ?? String(value);\n\t} catch {\n\t\treturn \"[circular or non-serializable]\";\n\t}\n}\n\n/** Create a schema type builder with optional type name */\nfunction createSchemaType<T>(\n\tvalidators: Array<(v: T) => boolean> = [],\n\ttypeName?: string,\n\tdefaultValue?: T | (() => T),\n\ttransform?: (value: unknown) => T,\n\tdescription?: string,\n\trefinements?: Array<{ predicate: (value: T) => boolean; message: string }>,\n): ExtendedSchemaType<T> {\n\treturn {\n\t\t_type: undefined as unknown as T,\n\t\t_validators: validators,\n\t\t_typeName: typeName,\n\t\t_default: defaultValue,\n\t\t_transform: transform,\n\t\t_description: description,\n\t\t_refinements: refinements,\n\t\tvalidate(fn: (value: T) => boolean) {\n\t\t\treturn createSchemaType([...validators, fn], typeName, defaultValue, transform, description, refinements);\n\t\t},\n\t};\n}\n\n/** Chainable schema type with all common methods */\nexport interface ChainableSchemaType<T> extends ExtendedSchemaType<T> {\n\tdefault(value: T | (() => T)): ChainableSchemaType<T>;\n\ttransform<U>(fn: (value: T) => U): ChainableSchemaType<U>;\n\tbrand<B extends string>(): ChainableSchemaType<Branded<T, B>>;\n\tdescribe(description: string): ChainableSchemaType<T>;\n\trefine(predicate: (value: T) => boolean, message: string): ChainableSchemaType<T>;\n\tnullable(): ChainableSchemaType<T | null>;\n\toptional(): ChainableSchemaType<T | undefined>;\n}\n\n/** Create a chainable schema type with common methods */\nfunction createChainableType<T>(\n\tvalidators: Array<(v: T) => boolean>,\n\ttypeName: string,\n\tdefaultValue?: T | (() => T),\n\ttransform?: (value: unknown) => T,\n\tdescription?: string,\n\trefinements?: Array<{ predicate: (value: T) => boolean; message: string }>,\n): ChainableSchemaType<T> {\n\tconst base = createSchemaType<T>(validators, typeName, defaultValue, transform, description, refinements);\n\treturn {\n\t\t...base,\n\t\tdefault(value: T | (() => T)) {\n\t\t\treturn createChainableType(validators, typeName, value, transform, description, refinements);\n\t\t},\n\t\ttransform<U>(fn: (value: T) => U) {\n\t\t\tconst newTransform = (v: unknown) => {\n\t\t\t\tconst intermediate = transform ? transform(v) : v as T;\n\t\t\t\treturn fn(intermediate);\n\t\t\t};\n\t\t\treturn createChainableType<U>([], typeName, undefined, newTransform as (v: unknown) => U, description);\n\t\t},\n\t\tbrand<B extends string>() {\n\t\t\treturn createChainableType<Branded<T, B>>(\n\t\t\t\tvalidators as Array<(v: Branded<T, B>) => boolean>,\n\t\t\t\t`Branded<${typeName}>`,\n\t\t\t\tdefaultValue as Branded<T, B> | (() => Branded<T, B>),\n\t\t\t\ttransform as (value: unknown) => Branded<T, B>,\n\t\t\t\tdescription,\n\t\t\t\trefinements as Array<{ predicate: (value: Branded<T, B>) => boolean; message: string }>,\n\t\t\t);\n\t\t},\n\t\tdescribe(desc: string) {\n\t\t\treturn createChainableType(validators, typeName, defaultValue, transform, desc, refinements);\n\t\t},\n\t\trefine(predicate: (value: T) => boolean, message: string) {\n\t\t\tconst newRefinements = [...(refinements ?? []), { predicate, message }];\n\t\t\treturn createChainableType(\n\t\t\t\t[...validators, predicate],\n\t\t\t\ttypeName,\n\t\t\t\tdefaultValue,\n\t\t\t\ttransform,\n\t\t\t\tdescription,\n\t\t\t\tnewRefinements,\n\t\t\t);\n\t\t},\n\t\tnullable() {\n\t\t\treturn createChainableType<T | null>(\n\t\t\t\t[(v): v is T | null => v === null || validators.every(fn => fn(v as T))],\n\t\t\t\t`${typeName} | null`,\n\t\t\t\tdefaultValue as (T | null) | (() => T | null),\n\t\t\t\ttransform as (value: unknown) => T | null,\n\t\t\t\tdescription,\n\t\t\t);\n\t\t},\n\t\toptional() {\n\t\t\treturn createChainableType<T | undefined>(\n\t\t\t\t[(v): v is T | undefined => v === undefined || validators.every(fn => fn(v as T))],\n\t\t\t\t`${typeName} | undefined`,\n\t\t\t\tdefaultValue as (T | undefined) | (() => T | undefined),\n\t\t\t\ttransform as (value: unknown) => T | undefined,\n\t\t\t\tdescription,\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * Schema type builders for defining fact types.\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 */\nexport const t = {\n\t/**\n\t * Create a string schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Basic string\n\t * schema: { name: t.string() }\n\t *\n\t * // String literal union (for type safety)\n\t * schema: { phase: t.string<\"red\" | \"green\" | \"yellow\">() }\n\t *\n\t * // With custom validation\n\t * schema: { email: t.string().validate(s => s.includes(\"@\")) }\n\t *\n\t * // With transform\n\t * schema: { trimmed: t.string().transform(s => s.trim()) }\n\t *\n\t * // With brand\n\t * schema: { userId: t.string().brand<\"UserId\">() }\n\t * ```\n\t */\n\tstring<T extends string = string>() {\n\t\treturn createChainableType<T>([\n\t\t\t(v): v is T => typeof v === \"string\",\n\t\t], \"string\") as ChainableSchemaType<T>;\n\t},\n\n\t/**\n\t * Create a number schema type with optional min/max constraints.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Basic number\n\t * schema: { count: t.number() }\n\t *\n\t * // With range constraints\n\t * schema: { age: t.number().min(0).max(150) }\n\t *\n\t * // With custom validation\n\t * schema: { even: t.number().validate(n => n % 2 === 0) }\n\t *\n\t * // With default\n\t * schema: { count: t.number().default(0) }\n\t *\n\t * // With transform (from string)\n\t * schema: { age: t.number().transform(v => parseInt(String(v), 10)) }\n\t * ```\n\t */\n\tnumber() {\n\t\ttype ChainableNumber = ChainableSchemaType<number> & {\n\t\t\tmin(n: number): ChainableNumber;\n\t\t\tmax(n: number): ChainableNumber;\n\t\t};\n\n\t\tconst createChainableNumber = (\n\t\t\tvalidators: Array<(v: number) => boolean>,\n\t\t\tdefaultValue?: number | (() => number),\n\t\t\ttransform?: (value: unknown) => number,\n\t\t\tdescription?: string,\n\t\t\trefinements?: Array<{ predicate: (value: number) => boolean; message: string }>,\n\t\t): ChainableNumber => {\n\t\t\tconst chainable = createChainableType<number>(validators, \"number\", defaultValue, transform, description, refinements);\n\t\t\treturn {\n\t\t\t\t...chainable,\n\t\t\t\tmin(n: number) {\n\t\t\t\t\treturn createChainableNumber([...validators, (v) => v >= n], defaultValue, transform, description, refinements);\n\t\t\t\t},\n\t\t\t\tmax(n: number) {\n\t\t\t\t\treturn createChainableNumber([...validators, (v) => v <= n], defaultValue, transform, description, refinements);\n\t\t\t\t},\n\t\t\t\tdefault(value: number | (() => number)) {\n\t\t\t\t\treturn createChainableNumber(validators, value, transform, description, refinements);\n\t\t\t\t},\n\t\t\t\tdescribe(desc: string) {\n\t\t\t\t\treturn createChainableNumber(validators, defaultValue, transform, desc, refinements);\n\t\t\t\t},\n\t\t\t\trefine(predicate: (value: number) => boolean, message: string) {\n\t\t\t\t\tconst newRefinements = [...(refinements ?? []), { predicate, message }];\n\t\t\t\t\treturn createChainableNumber([...validators, predicate], defaultValue, transform, description, newRefinements);\n\t\t\t\t},\n\t\t\t};\n\t\t};\n\t\treturn createChainableNumber([(v) => typeof v === \"number\"]);\n\t},\n\n\t/**\n\t * Create a boolean schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * schema: {\n\t * active: t.boolean(),\n\t * verified: t.boolean().default(false),\n\t * }\n\t * ```\n\t */\n\tboolean() {\n\t\treturn createChainableType<boolean>([(v) => typeof v === \"boolean\"], \"boolean\");\n\t},\n\n\t/**\n\t * Create an array schema type.\n\t * Can be used with or without element validation:\n\t * - `t.array<string>()` - Type-only, no element validation\n\t * - `t.array<string>().of(t.string())` - With element validation\n\t */\n\tarray<T>() {\n\t\ttype ChainableArray = ChainableSchemaType<T[]> & {\n\t\t\tof(elementType: SchemaType<T>): ChainableArray;\n\t\t\tnonEmpty(): ChainableArray;\n\t\t\tmaxLength(n: number): ChainableArray;\n\t\t\tminLength(n: number): ChainableArray;\n\t\t\t_lastFailedIndex?: number;\n\t\t};\n\n\t\tconst createChainableArray = (\n\t\t\tvalidators: Array<(v: T[]) => boolean>,\n\t\t\telementType?: SchemaType<T>,\n\t\t\tdefaultValue?: T[] | (() => T[]),\n\t\t\tdescription?: string,\n\t\t\tindexRef?: { value: number },\n\t\t): ChainableArray => {\n\t\t\tconst chainable = createChainableType<T[]>(validators, \"array\", defaultValue, undefined, description);\n\t\t\t// Use ref for storing failed index (shared with validator closure)\n\t\t\tconst ref = indexRef ?? { value: -1 };\n\t\t\tconst result: ChainableArray = {\n\t\t\t\t...chainable,\n\t\t\t\tget _lastFailedIndex() { return ref.value; },\n\t\t\t\tset _lastFailedIndex(v: number) { ref.value = v; },\n\t\t\t\tof(et: SchemaType<T>) {\n\t\t\t\t\t// Create a new ref for this chain\n\t\t\t\t\tconst newRef = { value: -1 };\n\t\t\t\t\treturn createChainableArray([\n\t\t\t\t\t\t...validators,\n\t\t\t\t\t\t(v) => {\n\t\t\t\t\t\t\tfor (let i = 0; i < v.length; i++) {\n\t\t\t\t\t\t\t\tconst item = v[i];\n\t\t\t\t\t\t\t\tif (!et._validators.every((validator) => validator(item))) {\n\t\t\t\t\t\t\t\t\tnewRef.value = i;\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t},\n\t\t\t\t\t], et, defaultValue, description, newRef);\n\t\t\t\t},\n\t\t\t\tnonEmpty() {\n\t\t\t\t\treturn createChainableArray([...validators, (v) => v.length > 0], elementType, defaultValue, description, ref);\n\t\t\t\t},\n\t\t\t\tmaxLength(n: number) {\n\t\t\t\t\treturn createChainableArray([...validators, (v) => v.length <= n], elementType, defaultValue, description, ref);\n\t\t\t\t},\n\t\t\t\tminLength(n: number) {\n\t\t\t\t\treturn createChainableArray([...validators, (v) => v.length >= n], elementType, defaultValue, description, ref);\n\t\t\t\t},\n\t\t\t\tdefault(value: T[] | (() => T[])) {\n\t\t\t\t\treturn createChainableArray(validators, elementType, value, description, ref);\n\t\t\t\t},\n\t\t\t\tdescribe(desc: string) {\n\t\t\t\t\treturn createChainableArray(validators, elementType, defaultValue, desc, ref);\n\t\t\t\t},\n\t\t\t};\n\t\t\treturn result;\n\t\t};\n\t\treturn createChainableArray([(v) => Array.isArray(v)]);\n\t},\n\n\t/**\n\t * Create an object schema type.\n\t * Can be used with or without shape validation:\n\t * - `t.object<User>()` - Type-only, no property validation\n\t * - `t.object<User>().shape({ name: t.string(), age: t.number() })` - With property validation\n\t */\n\tobject<T extends Record<string, unknown>>() {\n\t\ttype ChainableObject = ChainableSchemaType<T> & {\n\t\t\tshape(schema: { [K in keyof T]?: SchemaType<T[K]> }): ChainableObject;\n\t\t\tnonNull(): ChainableObject;\n\t\t\thasKeys(...keys: string[]): ChainableObject;\n\t\t};\n\n\t\tconst createChainableObject = (\n\t\t\tvalidators: Array<(v: T) => boolean>,\n\t\t\tdefaultValue?: T | (() => T),\n\t\t\tdescription?: string,\n\t\t): ChainableObject => {\n\t\t\tconst chainable = createChainableType<T>(validators, \"object\", defaultValue, undefined, description);\n\t\t\treturn {\n\t\t\t\t...chainable,\n\t\t\t\tshape(shapeSchema: { [K in keyof T]?: SchemaType<T[K]> }) {\n\t\t\t\t\treturn createChainableObject([\n\t\t\t\t\t\t...validators,\n\t\t\t\t\t\t(v) => {\n\t\t\t\t\t\t\tfor (const [key, schemaType] of Object.entries(shapeSchema)) {\n\t\t\t\t\t\t\t\tconst value = (v as Record<string, unknown>)[key];\n\t\t\t\t\t\t\t\tconst schemaT = schemaType as SchemaType<unknown>;\n\t\t\t\t\t\t\t\tif (schemaT && !schemaT._validators.every((validator) => validator(value))) {\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t},\n\t\t\t\t\t], defaultValue, description);\n\t\t\t\t},\n\t\t\t\tnonNull() {\n\t\t\t\t\treturn createChainableObject([...validators, (v) => v !== null && v !== undefined], defaultValue, description);\n\t\t\t\t},\n\t\t\t\thasKeys(...keys: string[]) {\n\t\t\t\t\treturn createChainableObject([\n\t\t\t\t\t\t...validators,\n\t\t\t\t\t\t(v) => keys.every((k) => k in (v as Record<string, unknown>)),\n\t\t\t\t\t], defaultValue, description);\n\t\t\t\t},\n\t\t\t\tdefault(value: T | (() => T)) {\n\t\t\t\t\treturn createChainableObject(validators, value, description);\n\t\t\t\t},\n\t\t\t\tdescribe(desc: string) {\n\t\t\t\t\treturn createChainableObject(validators, defaultValue, desc);\n\t\t\t\t},\n\t\t\t};\n\t\t};\n\t\treturn createChainableObject([\n\t\t\t(v) => typeof v === \"object\" && v !== null && !Array.isArray(v),\n\t\t]);\n\t},\n\n\t/**\n\t * Create an enum schema type for string literal unions.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Define allowed values\n\t * schema: { status: t.enum(\"idle\", \"loading\", \"success\", \"error\") }\n\t *\n\t * // Type is inferred as \"idle\" | \"loading\" | \"success\" | \"error\"\n\t * ```\n\t */\n\tenum<T extends string>(...values: T[]) {\n\t\tif (process.env.NODE_ENV !== \"production\" && values.length === 0) {\n\t\t\tconsole.warn(\"[Directive] t.enum() called with no values - this will reject all strings\");\n\t\t}\n\t\tconst valueSet = new Set(values);\n\t\treturn createChainableType<T>([\n\t\t\t(v): v is T => typeof v === \"string\" && valueSet.has(v as T),\n\t\t], `enum(${values.join(\"|\")})`);\n\t},\n\n\t/**\n\t * Create a literal schema type for exact value matching.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Exact string match\n\t * schema: { type: t.literal(\"user\") }\n\t *\n\t * // Exact number match\n\t * schema: { version: t.literal(1) }\n\t *\n\t * // Exact boolean\n\t * schema: { enabled: t.literal(true) }\n\t * ```\n\t */\n\tliteral<T extends string | number | boolean>(value: T) {\n\t\treturn createChainableType<T>([\n\t\t\t(v): v is T => v === value,\n\t\t], `literal(${String(value)})`);\n\t},\n\n\t/**\n\t * Create a nullable schema type (T | null).\n\t *\n\t * @example\n\t * ```typescript\n\t * // Nullable string\n\t * schema: { name: t.nullable(t.string()) }\n\t *\n\t * // Nullable object\n\t * schema: { user: t.nullable(t.object<User>()) }\n\t * ```\n\t */\n\tnullable<T>(innerType: SchemaType<T>) {\n\t\tconst innerTypeName = (innerType as ExtendedSchemaType<T>)._typeName ?? \"unknown\";\n\t\treturn createSchemaType<T | null>([\n\t\t\t(v): v is T | null => {\n\t\t\t\tif (v === null) return true;\n\t\t\t\treturn innerType._validators.every((validator) => validator(v as T));\n\t\t\t},\n\t\t], `${innerTypeName} | null`) as SchemaType<T | null>;\n\t},\n\n\t/**\n\t * Create an optional schema type (T | undefined).\n\t *\n\t * @example\n\t * ```typescript\n\t * // Optional string\n\t * schema: { nickname: t.optional(t.string()) }\n\t *\n\t * // Optional number\n\t * schema: { age: t.optional(t.number()) }\n\t * ```\n\t */\n\toptional<T>(innerType: SchemaType<T>) {\n\t\tconst innerTypeName = (innerType as ExtendedSchemaType<T>)._typeName ?? \"unknown\";\n\t\treturn createSchemaType<T | undefined>([\n\t\t\t(v): v is T | undefined => {\n\t\t\t\tif (v === undefined) return true;\n\t\t\t\treturn innerType._validators.every((validator) => validator(v as T));\n\t\t\t},\n\t\t], `${innerTypeName} | undefined`) as SchemaType<T | undefined>;\n\t},\n\n\t/**\n\t * Create a union schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * // String or number\n\t * schema: { value: t.union(t.string(), t.number()) }\n\t *\n\t * // Multiple types\n\t * schema: { data: t.union(t.string(), t.number(), t.boolean()) }\n\t * ```\n\t */\n\tunion<T extends SchemaType<unknown>[]>(...types: T) {\n\t\tif (process.env.NODE_ENV !== \"production\" && types.length === 0) {\n\t\t\tconsole.warn(\"[Directive] t.union() called with no types - this will reject all values\");\n\t\t}\n\t\ttype UnionType = T[number] extends SchemaType<infer U> ? U : never;\n\t\tconst typeNames = types.map(schemaType => (schemaType as ExtendedSchemaType<unknown>)._typeName ?? \"unknown\");\n\t\treturn createChainableType<UnionType>([\n\t\t\t(v): v is UnionType => types.some(schemaType => schemaType._validators.every(fn => fn(v))),\n\t\t], typeNames.join(\" | \"));\n\t},\n\n\t/**\n\t * Create a record schema type for dynamic key-value maps.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Record with string values\n\t * schema: { metadata: t.record(t.string()) }\n\t *\n\t * // Record with number values\n\t * schema: { scores: t.record(t.number()) }\n\t * ```\n\t */\n\trecord<V>(valueType: SchemaType<V>) {\n\t\tconst valueTypeName = (valueType as ExtendedSchemaType<V>)._typeName ?? \"unknown\";\n\t\treturn createChainableType<Record<string, V>>([\n\t\t\t(v): v is Record<string, V> => {\n\t\t\t\tif (typeof v !== \"object\" || v === null || Array.isArray(v)) return false;\n\t\t\t\treturn Object.values(v).every(val =>\n\t\t\t\t\tvalueType._validators.every(validator => validator(val))\n\t\t\t\t);\n\t\t\t},\n\t\t], `Record<string, ${valueTypeName}>`);\n\t},\n\n\t/**\n\t * Create a tuple schema type for fixed-length arrays with specific types.\n\t *\n\t * @example\n\t * ```typescript\n\t * // [string, number] tuple\n\t * schema: { coord: t.tuple(t.string(), t.number()) }\n\t *\n\t * // [x, y, z] coordinates\n\t * schema: { position: t.tuple(t.number(), t.number(), t.number()) }\n\t * ```\n\t */\n\ttuple<T extends SchemaType<unknown>[]>(...types: T) {\n\t\tif (process.env.NODE_ENV !== \"production\" && types.length === 0) {\n\t\t\tconsole.warn(\"[Directive] t.tuple() called with no types - this will only accept empty arrays\");\n\t\t}\n\t\ttype TupleType = { [K in keyof T]: T[K] extends SchemaType<infer U> ? U : never };\n\t\tconst typeNames = types.map(schemaType => (schemaType as ExtendedSchemaType<unknown>)._typeName ?? \"unknown\");\n\t\treturn createChainableType<TupleType>([\n\t\t\t(v): v is TupleType => {\n\t\t\t\tif (!Array.isArray(v) || v.length !== types.length) return false;\n\t\t\t\treturn types.every((schemaType, i) =>\n\t\t\t\t\tschemaType._validators.every(validator => validator(v[i]))\n\t\t\t\t);\n\t\t\t},\n\t\t], `[${typeNames.join(\", \")}]`);\n\t},\n\n\t/**\n\t * Create a date schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * schema: { createdAt: t.date() }\n\t * ```\n\t */\n\tdate() {\n\t\treturn createChainableType<Date>([\n\t\t\t(v): v is Date => v instanceof Date && !isNaN(v.getTime()),\n\t\t], \"Date\");\n\t},\n\n\t/**\n\t * Create a UUID schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * schema: { id: t.uuid() }\n\t * ```\n\t */\n\tuuid() {\n\t\tconst uuidRegex = /^[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\t\treturn createChainableType<string>([\n\t\t\t(v): v is string => typeof v === \"string\" && uuidRegex.test(v),\n\t\t], \"uuid\");\n\t},\n\n\t/**\n\t * Create an email schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * schema: { email: t.email() }\n\t * ```\n\t */\n\temail() {\n\t\t// Simple email regex - for comprehensive validation use Zod\n\t\tconst emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\t\treturn createChainableType<string>([\n\t\t\t(v): v is string => typeof v === \"string\" && emailRegex.test(v),\n\t\t], \"email\");\n\t},\n\n\t/**\n\t * Create a URL schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * schema: { website: t.url() }\n\t * ```\n\t */\n\turl() {\n\t\treturn createChainableType<string>([\n\t\t\t(v): v is string => {\n\t\t\t\tif (typeof v !== \"string\") return false;\n\t\t\t\ttry {\n\t\t\t\t\tnew URL(v);\n\t\t\t\t\treturn true;\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t},\n\t\t], \"url\");\n\t},\n\n\t/**\n\t * Create a bigint schema type.\n\t *\n\t * @example\n\t * ```typescript\n\t * schema: { largeNumber: t.bigint() }\n\t * ```\n\t */\n\tbigint() {\n\t\treturn createChainableType<bigint>([\n\t\t\t(v): v is bigint => typeof v === \"bigint\",\n\t\t], \"bigint\");\n\t},\n};\n\n// ============================================================================\n// Facts Store Implementation\n// ============================================================================\n\n/** Options for creating a facts store */\nexport interface CreateFactsStoreOptions<S extends Schema> {\n\tschema: S;\n\t/** Validate values against schema (default: process.env.NODE_ENV !== 'production') */\n\tvalidate?: boolean;\n\t/** Throw on unknown schema keys (default: true in dev mode) */\n\tstrictKeys?: boolean;\n\t/** Redact sensitive values in error messages */\n\tredactErrors?: boolean;\n\t/** Callback when facts change (for plugin hooks) */\n\tonChange?: (key: string, value: unknown, prev: unknown) => void;\n\t/** Callback for batch changes */\n\tonBatch?: (changes: Array<{ key: string; value: unknown; prev: unknown; type: \"set\" | \"delete\" }>) => void;\n}\n\n/**\n * Create a reactive facts store backed by a Map with schema validation,\n * batched mutations, and granular key-level subscriptions.\n *\n * The store is the low-level primitive that powers the `facts` proxy.\n * Most users should use {@link createFacts} or `createModule` instead.\n *\n * @param options - Store configuration including schema, validation settings, and change callbacks\n * @returns A `FactsStore<S>` with get/set/batch/subscribe methods and automatic schema validation\n *\n * @example\n * ```ts\n * const store = createFactsStore({\n * schema: { count: t.number(), name: t.string() },\n * });\n *\n * store.set(\"count\", 1);\n * store.get(\"count\"); // 1\n *\n * store.batch(() => {\n * store.set(\"count\", 2);\n * store.set(\"name\", \"hello\");\n * }); // listeners fire once after batch completes\n * ```\n */\nexport function createFactsStore<S extends Schema>(\n\toptions: CreateFactsStoreOptions<S>,\n): FactsStore<S> {\n\tconst { schema, onChange, onBatch } = options;\n\n\t// Detect if this is a type assertion schema (empty object with no keys)\n\tconst schemaKeys = Object.keys(schema);\n\tconst isTypeAssertionSchema = schemaKeys.length === 0;\n\n\t// Default strictKeys to false for type assertion schemas (they have no runtime keys)\n\tconst validate = options.validate ?? process.env.NODE_ENV !== \"production\";\n\tconst strictKeys = options.strictKeys ?? (process.env.NODE_ENV !== \"production\" && !isTypeAssertionSchema);\n\tconst redactErrors = options.redactErrors ?? false;\n\n\tconst map = new Map<string, unknown>();\n\tconst knownKeys = new Set<string>(); // Track all keys that have been set\n\tconst keyListeners = new Map<string, Set<() => void>>();\n\tconst allListeners = new Set<() => void>();\n\n\tlet batching = 0;\n\tconst batchChanges: Array<{ key: string; value: unknown; prev: unknown; type: \"set\" | \"delete\" }> = [];\n\tconst dirtyKeys = new Set<string>();\n\n\t// Notification coalescing: when notifyKey/notifyAll fires a listener that\n\t// calls store.set(), defer the new notification until the current cycle completes.\n\tlet isNotifying = false;\n\tconst pendingNonBatchedChanges: Array<{ key: string; value: unknown; prev: unknown }> = [];\n\tconst MAX_NOTIFY_ITERATIONS = 100;\n\n\t/** Check if a value is a Zod schema (robust detection) */\n\tfunction isZodSchema(v: unknown): v is { safeParse: (v: unknown) => { success: boolean; error?: { message?: string; issues?: Array<{ message: string }> } }; _def: unknown; parse: unknown } {\n\t\treturn (\n\t\t\tv !== null &&\n\t\t\ttypeof v === \"object\" &&\n\t\t\t\"safeParse\" in v && typeof (v as Record<string, unknown>).safeParse === \"function\" &&\n\t\t\t\"_def\" in v &&\n\t\t\t\"parse\" in v && typeof (v as Record<string, unknown>).parse === \"function\"\n\t\t);\n\t}\n\n\t/** Get expected type name from schema */\n\tfunction getExpectedType(schemaType: unknown): string {\n\t\t// Check for our SchemaType with _typeName\n\t\tconst st = schemaType as { _typeName?: string };\n\t\tif (st._typeName) return st._typeName;\n\n\t\t// Check for Zod schema\n\t\tif (isZodSchema(schemaType)) {\n\t\t\tconst def = (schemaType as { _def?: { typeName?: string } })._def;\n\t\t\tif (def?.typeName) {\n\t\t\t\t// Convert ZodString -> string, ZodNumber -> number, etc.\n\t\t\t\treturn def.typeName.replace(/^Zod/, \"\").toLowerCase();\n\t\t\t}\n\t\t}\n\n\t\treturn \"unknown\";\n\t}\n\n\t/** Format value for error message, respecting redactErrors option */\n\tfunction formatValueForError(value: unknown): string {\n\t\tif (redactErrors) return \"[redacted]\";\n\t\treturn safeStringify(value);\n\t}\n\n\t/** Validate a value against the schema */\n\tfunction validateValue(key: string, value: unknown): void {\n\t\tif (!validate) return;\n\n\t\tconst schemaType = schema[key];\n\t\tif (!schemaType) {\n\t\t\tif (strictKeys) {\n\t\t\t\tthrow new Error(`[Directive] Unknown fact key: \"${key}\". Key not defined in schema.`);\n\t\t\t}\n\t\t\tconsole.warn(`[Directive] Unknown fact key: \"${key}\"`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Check for Zod schema (robust detection: safeParse + _def + parse)\n\t\tif (isZodSchema(schemaType)) {\n\t\t\tconst result = schemaType.safeParse(value);\n\t\t\tif (!result.success) {\n\t\t\t\tconst valueType = value === null ? \"null\" : Array.isArray(value) ? \"array\" : typeof value;\n\t\t\t\tconst valuePreview = formatValueForError(value);\n\t\t\t\t// Extract error message safely from Zod error structure\n\t\t\t\tconst errorMessage = result.error?.message\n\t\t\t\t\t?? result.error?.issues?.[0]?.message\n\t\t\t\t\t?? \"Validation failed\";\n\t\t\t\tconst expectedType = getExpectedType(schemaType);\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Validation failed for \"${key}\": expected ${expectedType}, got ${valueType} ${valuePreview}. ${errorMessage}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Check for our SchemaType (has _validators array)\n\t\tconst st = schemaType as { _validators?: unknown; _typeName?: string; _lastFailedIndex?: number };\n\t\tconst validators = st._validators;\n\n\t\t// Ensure validators is an array before iterating\n\t\tif (!validators || !Array.isArray(validators) || validators.length === 0) {\n\t\t\treturn; // type assertion or empty validators - no validation\n\t\t}\n\n\t\tconst expectedType = st._typeName ?? \"unknown\";\n\n\t\tfor (let i = 0; i < validators.length; i++) {\n\t\t\tconst validator = validators[i];\n\t\t\tif (typeof validator !== \"function\") continue;\n\n\t\t\tif (!validator(value as never)) {\n\t\t\t\tconst valueType = value === null ? \"null\" : Array.isArray(value) ? \"array\" : typeof value;\n\t\t\t\tconst valuePreview = formatValueForError(value);\n\n\t\t\t\t// Check for array index failure from schema type\n\t\t\t\tlet indexHint = \"\";\n\t\t\t\tif (typeof st._lastFailedIndex === \"number\" && st._lastFailedIndex >= 0) {\n\t\t\t\t\tindexHint = ` (element at index ${st._lastFailedIndex} failed)`;\n\t\t\t\t\tst._lastFailedIndex = -1; // Reset for next validation\n\t\t\t\t}\n\n\t\t\t\t// Include expected type in error message\n\t\t\t\tconst validatorHint = i === 0 ? \"\" : ` (validator ${i + 1} failed)`;\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Validation failed for \"${key}\": expected ${expectedType}, got ${valueType} ${valuePreview}${validatorHint}${indexHint}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Notify listeners for a specific key */\n\tfunction notifyKey(key: string): void {\n\t\tkeyListeners.get(key)?.forEach((listener) => listener());\n\t}\n\n\t/** Notify all listeners */\n\tfunction notifyAll(): void {\n\t\tallListeners.forEach((listener) => listener());\n\t}\n\n\t/**\n\t * Run non-batched notifications with coalescing.\n\t * If a listener calls store.set(), the change is deferred and processed\n\t * after the current notification cycle completes.\n\t */\n\tfunction notifyNonBatched(key: string, value: unknown, prev: unknown): void {\n\t\tif (isNotifying) {\n\t\t\t// Re-entrant: defer to after current notification cycle\n\t\t\tpendingNonBatchedChanges.push({ key, value, prev });\n\t\t\treturn;\n\t\t}\n\n\t\tisNotifying = true;\n\t\ttry {\n\t\t\t// Fire onChange, notifyKey, notifyAll for the initial change\n\t\t\tonChange?.(key, value, prev);\n\t\t\tnotifyKey(key);\n\t\t\tnotifyAll();\n\n\t\t\t// Process any changes that were deferred during notification\n\t\t\tlet iterations = 0;\n\t\t\twhile (pendingNonBatchedChanges.length > 0) {\n\t\t\t\tif (++iterations > MAX_NOTIFY_ITERATIONS) {\n\t\t\t\t\tpendingNonBatchedChanges.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Infinite notification loop detected after ${MAX_NOTIFY_ITERATIONS} iterations. ` +\n\t\t\t\t\t\t\t`A listener is repeatedly mutating facts that re-trigger notifications.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst deferred = [...pendingNonBatchedChanges];\n\t\t\t\tpendingNonBatchedChanges.length = 0;\n\n\t\t\t\tfor (const change of deferred) {\n\t\t\t\t\tonChange?.(change.key, change.value, change.prev);\n\t\t\t\t\tnotifyKey(change.key);\n\t\t\t\t}\n\t\t\t\t// Single notifyAll for all deferred changes in this iteration\n\t\t\t\tnotifyAll();\n\t\t\t}\n\t\t} finally {\n\t\t\tisNotifying = false;\n\t\t}\n\t}\n\n\t/** Flush batched changes and notify */\n\tfunction flush(): void {\n\t\tif (batching > 0) return;\n\n\t\t// Notify batch callback\n\t\tif (onBatch && batchChanges.length > 0) {\n\t\t\tonBatch([...batchChanges]);\n\t\t}\n\n\t\t// Notify key-specific listeners (within coalescing guard)\n\t\tif (dirtyKeys.size > 0) {\n\t\t\tisNotifying = true;\n\t\t\ttry {\n\t\t\t\tfor (const key of dirtyKeys) {\n\t\t\t\t\tnotifyKey(key);\n\t\t\t\t}\n\t\t\t\tnotifyAll();\n\n\t\t\t\t// Process any changes deferred during flush notification\n\t\t\t\tlet iterations = 0;\n\t\t\t\twhile (pendingNonBatchedChanges.length > 0) {\n\t\t\t\t\tif (++iterations > MAX_NOTIFY_ITERATIONS) {\n\t\t\t\t\t\tpendingNonBatchedChanges.length = 0;\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`[Directive] Infinite notification loop detected during flush after ${MAX_NOTIFY_ITERATIONS} iterations.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst deferred = [...pendingNonBatchedChanges];\n\t\t\t\t\tpendingNonBatchedChanges.length = 0;\n\n\t\t\t\t\tfor (const change of deferred) {\n\t\t\t\t\t\tonChange?.(change.key, change.value, change.prev);\n\t\t\t\t\t\tnotifyKey(change.key);\n\t\t\t\t\t}\n\t\t\t\t\tnotifyAll();\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tisNotifying = false;\n\t\t\t}\n\t\t}\n\n\t\t// Clear batch state\n\t\tbatchChanges.length = 0;\n\t\tdirtyKeys.clear();\n\t}\n\n\tconst store: FactsStore<S> = {\n\t\tget<K extends keyof InferSchema<S>>(key: K): InferSchema<S>[K] | undefined {\n\t\t\t// Track access for auto-tracking\n\t\t\ttrackAccess(key as string);\n\t\t\treturn map.get(key as string) as InferSchema<S>[K] | undefined;\n\t\t},\n\n\t\thas(key: keyof InferSchema<S>): boolean {\n\t\t\t// Track access for auto-tracking\n\t\t\ttrackAccess(key as string);\n\t\t\treturn map.has(key as string);\n\t\t},\n\n\t\tset<K extends keyof InferSchema<S>>(key: K, value: InferSchema<S>[K]): void {\n\t\t\tvalidateValue(key as string, value);\n\n\t\t\tconst prev = map.get(key as string);\n\n\t\t\t// Skip if value hasn't changed (prevents unnecessary cascade)\n\t\t\tif (Object.is(prev, value)) return;\n\n\t\t\tmap.set(key as string, value);\n\t\t\tknownKeys.add(key as string); // Track known keys for serialization\n\n\t\t\t// Record change\n\t\t\tif (batching > 0) {\n\t\t\t\tbatchChanges.push({ key: key as string, value, prev, type: \"set\" });\n\t\t\t\tdirtyKeys.add(key as string);\n\t\t\t} else {\n\t\t\t\tnotifyNonBatched(key as string, value, prev);\n\t\t\t}\n\t\t},\n\n\t\tdelete(key: keyof InferSchema<S>): void {\n\t\t\tconst prev = map.get(key as string);\n\t\t\tmap.delete(key as string);\n\t\t\tknownKeys.delete(key as string); // Remove from known keys\n\n\t\t\t// Record change\n\t\t\tif (batching > 0) {\n\t\t\t\tbatchChanges.push({ key: key as string, value: undefined, prev, type: \"delete\" });\n\t\t\t\tdirtyKeys.add(key as string);\n\t\t\t} else {\n\t\t\t\tnotifyNonBatched(key as string, undefined, prev);\n\t\t\t}\n\t\t},\n\n\t\tbatch(fn: () => void): void {\n\t\t\tbatching++;\n\t\t\ttry {\n\t\t\t\tfn();\n\t\t\t} finally {\n\t\t\t\tbatching--;\n\t\t\t\tflush();\n\t\t\t}\n\t\t},\n\n\t\tsubscribe(\n\t\t\tkeys: Array<keyof InferSchema<S>>,\n\t\t\tlistener: () => void,\n\t\t): () => void {\n\t\t\tfor (const key of keys) {\n\t\t\t\tconst keyStr = key as string;\n\t\t\t\tif (!keyListeners.has(keyStr)) {\n\t\t\t\t\tkeyListeners.set(keyStr, new Set());\n\t\t\t\t}\n\t\t\t\tkeyListeners.get(keyStr)!.add(listener);\n\t\t\t}\n\n\t\t\treturn () => {\n\t\t\t\tfor (const key of keys) {\n\t\t\t\t\tconst set = keyListeners.get(key as string);\n\t\t\t\t\tif (set) {\n\t\t\t\t\t\tset.delete(listener);\n\t\t\t\t\t\tif (set.size === 0) {\n\t\t\t\t\t\t\tkeyListeners.delete(key as string);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\n\t\tsubscribeAll(listener: () => void): () => void {\n\t\t\tallListeners.add(listener);\n\t\t\treturn () => allListeners.delete(listener);\n\t\t},\n\n\t\ttoObject(): Record<string, unknown> {\n\t\t\tconst result: Record<string, unknown> = {};\n\t\t\tfor (const key of knownKeys) {\n\t\t\t\tif (map.has(key)) {\n\t\t\t\t\tresult[key] = map.get(key);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t};\n\n\t// Internal: register new schema keys for dynamic module registration.\n\t// Not part of the public FactsStore interface — used by engine.registerModule().\n\t(store as unknown as Record<string, unknown>).registerKeys = (newSchema: Record<string, unknown>) => {\n\t\tfor (const key of Object.keys(newSchema)) {\n\t\t\t// Defense-in-depth: skip prototype pollution keys\n\t\t\tif (BLOCKED_PROPS.has(key)) continue;\n\t\t\t// Add to schema for validation\n\t\t\t(schema as Record<string, unknown>)[key] = newSchema[key];\n\t\t\tknownKeys.add(key);\n\t\t}\n\t};\n\n\treturn store;\n}\n\n// ============================================================================\n// Proxy-based Facts Accessor\n// ============================================================================\n\n/** Prototype pollution guard - prevent access to dangerous properties */\nconst BLOCKED_PROPS = Object.freeze(new Set([\"__proto__\", \"constructor\", \"prototype\"]));\n\n/**\n * Create a Proxy wrapper around a {@link FactsStore} for clean property-style\n * access (`facts.phase`) with automatic dependency tracking.\n *\n * Reading a property calls `store.get()` (which tracks the access for\n * auto-tracked derivations). Writing a property calls `store.set()` (which\n * validates against the schema). The proxy also exposes `$store` for direct\n * store access and `$snapshot()` for untracked reads.\n *\n * @param store - The underlying facts store to wrap\n * @param schema - The schema definition (used for `ownKeys` enumeration)\n * @returns A `Facts<S>` proxy with property-style get/set and prototype pollution guards\n */\nexport function createFactsProxy<S extends Schema>(\n\tstore: FactsStore<S>,\n\tschema: S,\n): Facts<S> {\n\tconst snapshot = (): FactsSnapshot<S> => ({\n\t\tget: <K extends keyof InferSchema<S>>(key: K) =>\n\t\t\twithoutTracking(() => store.get(key)),\n\t\thas: (key: keyof InferSchema<S>) =>\n\t\t\twithoutTracking(() => store.has(key)),\n\t});\n\n\tconst proxy = new Proxy({} as Facts<S>, {\n\t\tget(_, prop: string | symbol) {\n\t\t\tif (prop === \"$store\") return store;\n\t\t\tif (prop === \"$snapshot\") return snapshot;\n\n\t\t\t// Special properties\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\n\t\t\t// Track and return the value\n\t\t\treturn store.get(prop as keyof InferSchema<S>);\n\t\t},\n\n\t\tset(_, prop: string | symbol, value: unknown) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\tif (prop === \"$store\" || prop === \"$snapshot\") return false;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\n\t\t\t// Validation is handled by store.set() when validate option is enabled\n\t\t\tstore.set(prop as keyof InferSchema<S>, value as InferSchema<S>[keyof InferSchema<S>]);\n\t\t\treturn true;\n\t\t},\n\n\t\tdeleteProperty(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\tif (prop === \"$store\" || prop === \"$snapshot\") return false;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\n\t\t\tstore.delete(prop as keyof InferSchema<S>);\n\t\t\treturn true;\n\t\t},\n\n\t\thas(_, prop: string | symbol) {\n\t\t\tif (prop === \"$store\" || prop === \"$snapshot\") return true;\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\n\t\t\treturn store.has(prop as keyof InferSchema<S>);\n\t\t},\n\n\t\townKeys() {\n\t\t\t// Return schema keys dynamically so Object.keys(facts) reflects\n\t\t\t// keys added via registerKeys (dynamic module registration)\n\t\t\treturn Object.keys(schema);\n\t\t},\n\n\t\tgetOwnPropertyDescriptor(_, prop: string | symbol) {\n\t\t\tif (prop === \"$store\" || prop === \"$snapshot\") {\n\t\t\t\treturn { configurable: true, enumerable: false, writable: false };\n\t\t\t}\n\t\t\treturn { configurable: true, enumerable: true, writable: true };\n\t\t},\n\t});\n\n\treturn proxy;\n}\n\n// ============================================================================\n// Combined Factory\n// ============================================================================\n\n/**\n * Convenience factory that creates both a {@link FactsStore} and its\n * {@link createFactsProxy | proxy wrapper} in a single call.\n *\n * This is the recommended entry point when you need low-level store access\n * outside of `createModule` / `createSystem`.\n *\n * @param options - Same options as {@link createFactsStore}\n * @returns An object with `store` (the reactive Map-backed store) and `facts` (the Proxy accessor)\n *\n * @example\n * ```ts\n * const { store, facts } = createFacts({\n * schema: { phase: t.string<\"red\" | \"green\">() },\n * });\n *\n * facts.phase = \"red\";\n * console.log(facts.phase); // \"red\"\n * store.subscribe([\"phase\"], () => console.log(\"phase changed\"));\n * ```\n */\nexport function createFacts<S extends Schema>(\n\toptions: CreateFactsStoreOptions<S>,\n): { store: FactsStore<S>; facts: Facts<S> } {\n\tconst store = createFactsStore(options);\n\tconst facts = createFactsProxy(store, options.schema);\n\treturn { store, facts };\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 type {\n\tModuleSchema,\n\tFacts,\n\tModuleDef,\n\tModuleHooks,\n\tEffectsDef,\n\tTypedDerivationsDef,\n\tTypedEventsDef,\n\tTypedConstraintsDef,\n\tTypedResolversDef,\n\tCrossModuleDeps,\n\tCrossModuleConstraintsDef,\n\tCrossModuleEffectsDef,\n\tCrossModuleDerivationsDef,\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\tschema: M;\n\tinit?: (facts: Facts<M[\"facts\"]>) => void;\n\tderive?: TypedDerivationsDef<M>;\n\tevents?: TypedEventsDef<M>;\n\teffects?: EffectsDef<M[\"facts\"]>;\n\tconstraints?: TypedConstraintsDef<M>;\n\tresolvers?: TypedResolversDef<M>;\n\thooks?: ModuleHooks<M>;\n\t/** Events that create time-travel snapshots for undo/redo. Omit to snapshot all events. */\n\tsnapshotEvents?: Array<keyof (M[\"events\"] extends Record<string, unknown> ? M[\"events\"] : Record<string, never>) & string>;\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\tM extends ModuleSchema,\n\tDeps extends CrossModuleDeps,\n> {\n\tschema: M;\n\t/**\n\t * Cross-module dependencies for type-safe access in derive/effects/constraints.\n\t *\n\t * **Access patterns by context:**\n\t * - `derive`, `effects`, `constraints`: Use `facts.self.*` for own module, `facts.{dep}.*` for cross-module\n\t * - `init`, `events`, `resolvers`: Use flat access (`facts.myFact`) - no cross-module access\n\t *\n\t * This separation ensures initialization and event handling stay scoped to own module,\n\t * while observers (derive/effects/constraints) can see across modules.\n\t *\n\t * @example\n\t * ```typescript\n\t * crossModuleDeps: { auth: authSchema },\n\t * init: (facts) => { facts.users = []; }, // flat access\n\t * derive: { count: (facts) => facts.self.users.length }, // facts.self.*\n\t * effects: { log: { run: (facts) => console.log(facts.auth.token) } }, // facts.{dep}.*\n\t * ```\n\t */\n\tcrossModuleDeps: Deps;\n\t/** Initialize module facts. Uses flat access (`facts.myFact`) to ensure modules initialize independently. */\n\tinit?: (facts: Facts<M[\"facts\"]>) => void;\n\t/** Derivations with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n\tderive?: CrossModuleDerivationsDef<M, Deps>;\n\t/** Event handlers. Uses flat access (`facts.myFact`) to keep mutations scoped to own module. */\n\tevents?: TypedEventsDef<M>;\n\t/** Effects with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n\teffects?: CrossModuleEffectsDef<M, Deps>;\n\t/** Constraints with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n\tconstraints?: CrossModuleConstraintsDef<M, Deps>;\n\t/** Resolvers. Uses flat access (`ctx.facts.myFact`) to keep async mutations scoped to own module. */\n\tresolvers?: TypedResolversDef<M>;\n\thooks?: ModuleHooks<M>;\n\t/** Events that create time-travel snapshots for undo/redo. Omit to snapshot all events. */\n\tsnapshotEvents?: Array<keyof (M[\"events\"] extends Record<string, unknown> ? M[\"events\"] : Record<string, never>) & string>;\n}\n\n/**\n * Create a module definition with full type inference.\n *\n * The consolidated schema provides:\n * - Derivation composition (`derive.otherDerivation` is typed)\n * - Event dispatch (`system.dispatch({ type: \"...\" })` has autocomplete)\n * - Resolver requirements (`req.payload` is typed based on requirement type)\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, derive) => {\n * // derive.isRed is typed as boolean!\n * return derive.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 * });\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// Overload 1: With crossModuleDeps\nexport function createModule<\n\tconst M extends ModuleSchema,\n\tconst Deps extends CrossModuleDeps,\n>(\n\tid: string,\n\tconfig: ModuleConfigWithDeps<M, Deps>,\n): ModuleDef<M>;\n\n// Overload 2: Without crossModuleDeps (original signature)\nexport function createModule<const M extends ModuleSchema>(\n\tid: string,\n\tconfig: ModuleConfig<M>,\n): ModuleDef<M>;\n\n// Overload 3: Union (used by createModuleFactory)\nexport function createModule<const M extends ModuleSchema>(\n\tid: string,\n\tconfig: ModuleConfigWithDeps<M, CrossModuleDeps> | ModuleConfig<M>,\n): ModuleDef<M>;\n\n// Implementation (must immediately follow overload declarations)\nexport function createModule<const M extends ModuleSchema>(\n\tid: string,\n\tconfig: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): ModuleDef<M> {\n\t// Dev-mode validations\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tif (!id || typeof id !== \"string\") {\n\t\t\tconsole.warn(\"[Directive] Module ID must be a non-empty string\");\n\t\t} else if (!/^[a-z][a-z0-9-]*$/i.test(id)) {\n\t\t\tconsole.warn(\n\t\t\t\t`[Directive] Module ID \"${id}\" should follow kebab-case convention (e.g., \"my-module\")`,\n\t\t\t);\n\t\t}\n\n\t\tif (!config.schema) {\n\t\t\tconsole.warn(\"[Directive] Module schema is required\");\n\t\t} else {\n\t\t\tif (!config.schema.facts) {\n\t\t\t\tconsole.warn(\"[Directive] Module schema.facts is required\");\n\t\t\t}\n\t\t\t// derivations, events, and requirements default to {} if not provided\n\t\t}\n\n\t\t// Validate derive keys match schema.derivations (if either is provided)\n\t\tconst schemaDerivations = config.schema?.derivations ?? {};\n\t\tconst deriveImpl = config.derive ?? {};\n\t\tconst schemaDerivationKeys = new Set(Object.keys(schemaDerivations));\n\t\tconst deriveKeys = new Set(Object.keys(deriveImpl));\n\n\t\tfor (const key of deriveKeys) {\n\t\t\tif (!schemaDerivationKeys.has(key)) {\n\t\t\t\tconsole.warn(`[Directive] Derivation \"${key}\" not declared in schema.derivations`);\n\t\t\t}\n\t\t}\n\t\tfor (const key of schemaDerivationKeys) {\n\t\t\tif (!deriveKeys.has(key)) {\n\t\t\t\tconsole.warn(`[Directive] schema.derivations[\"${key}\"] has no matching implementation in derive`);\n\t\t\t}\n\t\t}\n\n\t\t// Validate events keys match schema.events (if either is provided)\n\t\tconst schemaEvents = config.schema?.events ?? {};\n\t\tconst eventImpl = config.events ?? {};\n\t\tconst schemaEventKeys = new Set(Object.keys(schemaEvents));\n\t\tconst eventKeys = new Set(Object.keys(eventImpl));\n\n\t\tfor (const key of eventKeys) {\n\t\t\tif (!schemaEventKeys.has(key)) {\n\t\t\t\tconsole.warn(`[Directive] Event \"${key}\" not declared in schema.events`);\n\t\t\t}\n\t\t}\n\t\tfor (const key of schemaEventKeys) {\n\t\t\tif (!eventKeys.has(key)) {\n\t\t\t\tconsole.warn(`[Directive] schema.events[\"${key}\"] has no matching handler in events`);\n\t\t\t}\n\t\t}\n\n\t\t// Validate snapshotEvents reference valid event names\n\t\tif (config.snapshotEvents) {\n\t\t\tif (config.snapshotEvents.length === 0) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] snapshotEvents is an empty array — no events will create time-travel snapshots. ` +\n\t\t\t\t\t\t`Omit snapshotEvents entirely to snapshot all events, or list specific events.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst schemaEventKeysForValidation = new Set(Object.keys(config.schema?.events ?? {}));\n\t\t\tfor (const eventName of config.snapshotEvents) {\n\t\t\t\tif (!schemaEventKeysForValidation.has(eventName)) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] snapshotEvents entry \"${eventName}\" not declared in schema.events. ` +\n\t\t\t\t\t\t\t`Available events: ${[...schemaEventKeysForValidation].join(\", \") || \"(none)\"}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Validate resolvers reference valid requirement types\n\t\tif (config.resolvers && config.schema?.requirements) {\n\t\t\tconst requirementTypes = new Set(Object.keys(config.schema.requirements));\n\t\t\tfor (const [resolverName, resolver] of Object.entries(config.resolvers)) {\n\t\t\t\tconst resolverDef = resolver as { requirement?: string };\n\t\t\t\tif (\n\t\t\t\t\ttypeof resolverDef.requirement === \"string\" &&\n\t\t\t\t\t!requirementTypes.has(resolverDef.requirement)\n\t\t\t\t) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] Resolver \"${resolverName}\" references unknown requirement type \"${resolverDef.requirement}\". ` +\n\t\t\t\t\t\t\t`Available types: ${[...requirementTypes].join(\", \") || \"(none)\"}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Extract crossModuleDeps if present (for runtime proxy creation)\n\tconst crossModuleDeps = \"crossModuleDeps\" in config ? config.crossModuleDeps : undefined;\n\n\treturn {\n\t\tid,\n\t\tschema: config.schema,\n\t\tinit: config.init,\n\t\t// Cast to TypedDerivationsDef for ModuleDef compatibility (runtime handles both types)\n\t\tderive: (config.derive ?? {}) as TypedDerivationsDef<M>,\n\t\tevents: config.events ?? ({} as TypedEventsDef<M>),\n\t\teffects: config.effects as EffectsDef<M[\"facts\"]> | undefined,\n\t\tconstraints: config.constraints as TypedConstraintsDef<M> | undefined,\n\t\tresolvers: config.resolvers,\n\t\thooks: config.hooks,\n\t\tsnapshotEvents: config.snapshotEvents,\n\t\t// Store crossModuleDeps for runtime proxy creation\n\t\tcrossModuleDeps: crossModuleDeps as CrossModuleDeps | undefined,\n\t};\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 * @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 */\nexport function createModuleFactory<const M extends ModuleSchema>(\n\tconfig: ModuleConfig<M>,\n): (name: string) => ModuleDef<M>;\nexport function createModuleFactory<\n\tconst M extends ModuleSchema,\n\tconst Deps extends CrossModuleDeps,\n>(\n\tconfig: ModuleConfigWithDeps<M, Deps>,\n): (name: string) => ModuleDef<M>;\nexport function createModuleFactory<const M extends ModuleSchema>(\n\tconfig: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): (name: string) => ModuleDef<M> {\n\t// Pass config directly — createModule's implementation overload handles both types.\n\t// Do NOT cast to ModuleConfig<M> which would strip crossModuleDeps.\n\treturn (name: string) => createModule(name, config);\n}\n","/**\n * Shared utilities for Directive\n */\n\n/**\n * Execute a promise with a timeout, properly cleaning up the timer.\n * Used by both constraints and resolvers for timeout handling.\n *\n * @param promise - The promise to wrap with a timeout\n * @param ms - Timeout duration in milliseconds\n * @param errorMessage - Error message if timeout occurs\n * @returns The promise result\n * @throws Error if timeout is exceeded\n */\nexport async function withTimeout<T>(\n\tpromise: Promise<T>,\n\tms: number,\n\terrorMessage: string,\n): Promise<T> {\n\tlet timeoutId: ReturnType<typeof setTimeout>;\n\n\tconst timeoutPromise = new Promise<never>((_, reject) => {\n\t\ttimeoutId = setTimeout(() => reject(new Error(errorMessage)), ms);\n\t});\n\n\ttry {\n\t\treturn await Promise.race([promise, timeoutPromise]);\n\t} finally {\n\t\tclearTimeout(timeoutId!);\n\t}\n}\n\n/**\n * Normalize an error to an Error instance.\n * Ensures consistent error handling throughout the library.\n *\n * @param error - The error to normalize (can be anything)\n * @returns An Error instance\n */\nexport function normalizeError(error: unknown): Error {\n\tif (error instanceof Error) {\n\t\treturn error;\n\t}\n\treturn new Error(String(error));\n}\n\n/**\n * Create a stable JSON string with sorted keys.\n * Handles circular references and deeply nested objects safely.\n *\n * @param value - The value to stringify\n * @param maxDepth - Maximum nesting depth (default: 50)\n * @returns A stable JSON string\n */\nexport function stableStringify(value: unknown, maxDepth = 50): string {\n\tconst seen = new WeakSet();\n\n\tfunction stringify(val: unknown, depth: number): string {\n\t\tif (depth > maxDepth) {\n\t\t\treturn '\"[max depth exceeded]\"';\n\t\t}\n\n\t\tif (val === null) return \"null\";\n\t\tif (val === undefined) return \"undefined\";\n\n\t\tconst type = typeof val;\n\n\t\tif (type === \"string\") return JSON.stringify(val);\n\t\tif (type === \"number\" || type === \"boolean\") return String(val);\n\t\tif (type === \"function\") return '\"[function]\"';\n\t\tif (type === \"symbol\") return '\"[symbol]\"';\n\n\t\tif (Array.isArray(val)) {\n\t\t\t// Check for circular reference\n\t\t\tif (seen.has(val)) {\n\t\t\t\treturn '\"[circular]\"';\n\t\t\t}\n\t\t\tseen.add(val);\n\t\t\tconst result = `[${val.map((v) => stringify(v, depth + 1)).join(\",\")}]`;\n\t\t\tseen.delete(val);\n\t\t\treturn result;\n\t\t}\n\n\t\tif (type === \"object\") {\n\t\t\tconst obj = val as Record<string, unknown>;\n\t\t\t// Check for circular reference\n\t\t\tif (seen.has(obj)) {\n\t\t\t\treturn '\"[circular]\"';\n\t\t\t}\n\t\t\tseen.add(obj);\n\t\t\tconst keys = Object.keys(obj).sort();\n\t\t\tconst pairs = keys.map((k) => `${JSON.stringify(k)}:${stringify(obj[k], depth + 1)}`);\n\t\t\tconst result = `{${pairs.join(\",\")}}`;\n\t\t\tseen.delete(obj);\n\t\t\treturn result;\n\t\t}\n\n\t\treturn '\"[unknown]\"';\n\t}\n\n\treturn stringify(value, 0);\n}\n\n/**\n * Check for prototype pollution in an object, including nested objects.\n * Returns true if the object is safe, false if dangerous keys are found.\n *\n * @param obj - The object to check\n * @param maxDepth - Maximum nesting depth to check (default: 50)\n * @returns True if safe, false if dangerous keys found\n */\nexport function isPrototypeSafe(obj: unknown, maxDepth = 50): boolean {\n\tconst dangerousKeys = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\tconst seen = new WeakSet();\n\n\tfunction check(val: unknown, depth: number): boolean {\n\t\tif (depth > maxDepth) return false; // Fail safe at max depth - don't assume safety\n\t\tif (val === null || val === undefined) return true;\n\t\tif (typeof val !== \"object\") return true;\n\n\t\tconst objVal = val as Record<string, unknown>;\n\n\t\t// Check for circular reference\n\t\tif (seen.has(objVal)) return true;\n\t\tseen.add(objVal);\n\n\t\t// Check array elements\n\t\tif (Array.isArray(objVal)) {\n\t\t\tfor (const item of objVal) {\n\t\t\t\tif (!check(item, depth + 1)) {\n\t\t\t\t\tseen.delete(objVal);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tseen.delete(objVal);\n\t\t\treturn true;\n\t\t}\n\n\t\t// Check object keys and values\n\t\tfor (const key of Object.keys(objVal)) {\n\t\t\tif (dangerousKeys.has(key)) {\n\t\t\t\tseen.delete(objVal);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!check(objVal[key], depth + 1)) {\n\t\t\t\tseen.delete(objVal);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tseen.delete(objVal);\n\t\treturn true;\n\t}\n\n\treturn check(obj, 0);\n}\n\n/**\n * Shallow equality comparison for objects.\n * Used by React hooks to avoid unnecessary re-renders.\n *\n * @param a - First object\n * @param b - Second object\n * @returns True if objects are shallowly equal\n */\nexport function shallowEqual<T extends Record<string, unknown>>(a: T, b: T): boolean {\n\tif (a === b) return true;\n\tif (!a || !b) return false;\n\n\tconst keysA = Object.keys(a);\n\tconst keysB = Object.keys(b);\n\n\tif (keysA.length !== keysB.length) return false;\n\n\tfor (const key of keysA) {\n\t\tif (a[key] !== b[key]) return false;\n\t}\n\n\treturn true;\n}\n\n/**\n * Generate a simple hash string from an object.\n * Uses djb2 algorithm on the stable stringified value.\n *\n * **Limitations:**\n * - 32-bit hash output means collision probability increases with data set size\n * (birthday paradox: ~50% collision chance at ~77,000 distinct values)\n * - Suitable for: cache invalidation, change detection, deduplication of small sets\n * - NOT suitable for: cryptographic use, security-sensitive operations, large-scale deduplication\n *\n * For security-sensitive use cases requiring stronger collision resistance,\n * consider using a cryptographic hash like SHA-256.\n *\n * @param value - The value to hash\n * @returns A hex hash string (8 characters, 32 bits)\n */\nexport function hashObject(value: unknown): string {\n\tconst str = stableStringify(value);\n\tlet hash = 5381;\n\tfor (let i = 0; i < str.length; i++) {\n\t\thash = ((hash << 5) + hash) ^ str.charCodeAt(i);\n\t}\n\t// Convert to unsigned 32-bit and then to hex\n\treturn (hash >>> 0).toString(16);\n}\n\n// ============================================================================\n// Distributable Snapshot Utilities\n// ============================================================================\n\n/**\n * Distributable snapshot type for type-safe helper functions.\n */\nexport interface DistributableSnapshotLike<T = Record<string, unknown>> {\n\tdata: T;\n\tcreatedAt: number;\n\texpiresAt?: number;\n\tversion?: string;\n\tmetadata?: Record<string, unknown>;\n}\n\n/**\n * Check if a distributable snapshot has expired.\n * Returns false if the snapshot has no expiresAt field.\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({ ttlSeconds: 3600 });\n * // ... later ...\n * if (isSnapshotExpired(snapshot)) {\n * // Refresh the snapshot\n * }\n * ```\n *\n * @param snapshot - The snapshot to check\n * @param now - Optional current timestamp (defaults to Date.now())\n * @returns True if the snapshot has expired, false otherwise\n */\nexport function isSnapshotExpired<T>(\n\tsnapshot: DistributableSnapshotLike<T>,\n\tnow: number = Date.now(),\n): boolean {\n\treturn snapshot.expiresAt !== undefined && now > snapshot.expiresAt;\n}\n\n/**\n * Validate a distributable snapshot and return its data.\n * Throws if the snapshot is malformed or has expired.\n *\n * @example\n * ```typescript\n * const cached = JSON.parse(await redis.get(`entitlements:${userId}`));\n * try {\n * const data = validateSnapshot(cached);\n * // Use data.canUseFeature, etc.\n * } catch (e) {\n * // Snapshot invalid or expired, refresh it\n * }\n * ```\n *\n * @example Using custom timestamp for testing\n * ```typescript\n * const snapshot = { data: { test: true }, createdAt: 1000, expiresAt: 2000 };\n * validateSnapshot(snapshot, 1500); // Returns { test: true }\n * validateSnapshot(snapshot, 2500); // Throws: Snapshot expired\n * ```\n *\n * @param snapshot - The snapshot to validate\n * @param now - Optional current timestamp (defaults to Date.now())\n * @returns The snapshot data if valid\n * @throws Error if the snapshot is malformed or has expired\n */\nexport function validateSnapshot<T>(\n\tsnapshot: DistributableSnapshotLike<T>,\n\tnow: number = Date.now(),\n): T {\n\t// Structural validation\n\tif (!snapshot || typeof snapshot !== \"object\") {\n\t\tthrow new Error(\n\t\t\t\"[Directive] Invalid snapshot: expected an object with 'data' and 'createdAt' properties.\",\n\t\t);\n\t}\n\tif (!(\"data\" in snapshot)) {\n\t\tthrow new Error(\n\t\t\t\"[Directive] Invalid snapshot: missing required 'data' property.\",\n\t\t);\n\t}\n\tif (!(\"createdAt\" in snapshot) || typeof snapshot.createdAt !== \"number\") {\n\t\tthrow new Error(\n\t\t\t\"[Directive] Invalid snapshot: missing or invalid 'createdAt' property (expected number).\",\n\t\t);\n\t}\n\n\t// Expiration validation\n\tif (isSnapshotExpired(snapshot, now)) {\n\t\tconst expiredAt = new Date(snapshot.expiresAt!).toISOString();\n\t\tthrow new Error(\n\t\t\t`[Directive] Snapshot expired at ${expiredAt}. Obtain a fresh snapshot from the source.`,\n\t\t);\n\t}\n\treturn snapshot.data;\n}\n\n/**\n * Diff result for a single changed value.\n */\nexport interface SnapshotDiffEntry {\n\t/** The key path that changed (e.g., \"canUseApi\" or \"limits.apiCalls\") */\n\tpath: string;\n\t/** The value in the old snapshot */\n\toldValue: unknown;\n\t/** The value in the new snapshot */\n\tnewValue: unknown;\n\t/** Type of change: \"added\", \"removed\", or \"changed\" */\n\ttype: \"added\" | \"removed\" | \"changed\";\n}\n\n/**\n * Result of diffing two snapshots.\n */\nexport interface SnapshotDiff {\n\t/** Whether the snapshots are identical */\n\tidentical: boolean;\n\t/** List of changes between snapshots */\n\tchanges: SnapshotDiffEntry[];\n\t/** Whether the version changed (if both have versions) */\n\tversionChanged: boolean;\n\t/** Old version (if available) */\n\toldVersion?: string;\n\t/** New version (if available) */\n\tnewVersion?: string;\n}\n\n/**\n * Compare two distributable snapshots and return the differences.\n * Useful for debugging, audit logs, and webhook payloads.\n *\n * @example\n * ```typescript\n * const oldSnapshot = system.getDistributableSnapshot({ includeVersion: true });\n * system.dispatch({ type: \"upgradePlan\", plan: \"pro\" });\n * const newSnapshot = system.getDistributableSnapshot({ includeVersion: true });\n *\n * const diff = diffSnapshots(oldSnapshot, newSnapshot);\n * if (!diff.identical) {\n * console.log(\"Changes:\", diff.changes);\n * // [{ path: \"canUseApi\", oldValue: false, newValue: true, type: \"changed\" }]\n * }\n * ```\n *\n * @param oldSnapshot - The previous snapshot\n * @param newSnapshot - The new snapshot\n * @returns A diff result with all changes\n */\nexport function diffSnapshots<T = Record<string, unknown>>(\n\toldSnapshot: DistributableSnapshotLike<T>,\n\tnewSnapshot: DistributableSnapshotLike<T>,\n): SnapshotDiff {\n\tconst changes: SnapshotDiffEntry[] = [];\n\n\t// Deep compare function\n\tfunction compare(\n\t\toldObj: unknown,\n\t\tnewObj: unknown,\n\t\tpath: string,\n\t): void {\n\t\t// Handle null/undefined\n\t\tif (oldObj === null || oldObj === undefined) {\n\t\t\tif (newObj !== null && newObj !== undefined) {\n\t\t\t\tchanges.push({ path, oldValue: oldObj, newValue: newObj, type: \"added\" });\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (newObj === null || newObj === undefined) {\n\t\t\tchanges.push({ path, oldValue: oldObj, newValue: newObj, type: \"removed\" });\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle primitives\n\t\tif (typeof oldObj !== \"object\" || typeof newObj !== \"object\") {\n\t\t\tif (!Object.is(oldObj, newObj)) {\n\t\t\t\tchanges.push({ path, oldValue: oldObj, newValue: newObj, type: \"changed\" });\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle arrays\n\t\tif (Array.isArray(oldObj) && Array.isArray(newObj)) {\n\t\t\tif (oldObj.length !== newObj.length) {\n\t\t\t\tchanges.push({ path, oldValue: oldObj, newValue: newObj, type: \"changed\" });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (let i = 0; i < oldObj.length; i++) {\n\t\t\t\tcompare(oldObj[i], newObj[i], `${path}[${i}]`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle objects\n\t\tconst oldRecord = oldObj as Record<string, unknown>;\n\t\tconst newRecord = newObj as Record<string, unknown>;\n\t\tconst allKeys = new Set([...Object.keys(oldRecord), ...Object.keys(newRecord)]);\n\n\t\tfor (const key of allKeys) {\n\t\t\tconst childPath = path ? `${path}.${key}` : key;\n\t\t\tif (!(key in oldRecord)) {\n\t\t\t\tchanges.push({ path: childPath, oldValue: undefined, newValue: newRecord[key], type: \"added\" });\n\t\t\t} else if (!(key in newRecord)) {\n\t\t\t\tchanges.push({ path: childPath, oldValue: oldRecord[key], newValue: undefined, type: \"removed\" });\n\t\t\t} else {\n\t\t\t\tcompare(oldRecord[key], newRecord[key], childPath);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Compare data\n\tcompare(oldSnapshot.data, newSnapshot.data, \"\");\n\n\t// Check version change\n\tconst versionChanged = oldSnapshot.version !== newSnapshot.version &&\n\t\t(oldSnapshot.version !== undefined || newSnapshot.version !== undefined);\n\n\treturn {\n\t\tidentical: changes.length === 0,\n\t\tchanges,\n\t\tversionChanged,\n\t\toldVersion: oldSnapshot.version,\n\t\tnewVersion: newSnapshot.version,\n\t};\n}\n\n// ============================================================================\n// Snapshot Signing (HMAC)\n// ============================================================================\n\n/**\n * A signed distributable snapshot.\n * Contains the original snapshot plus a cryptographic signature.\n */\nexport interface SignedSnapshot<T = Record<string, unknown>>\n\textends DistributableSnapshotLike<T> {\n\t/** HMAC-SHA256 signature in hex format */\n\tsignature: string;\n\t/** Signing algorithm used */\n\talgorithm: \"hmac-sha256\";\n}\n\n/**\n * Check if a snapshot is signed.\n *\n * @param snapshot - The snapshot to check\n * @returns True if the snapshot has a signature\n */\nexport function isSignedSnapshot<T>(\n\tsnapshot: DistributableSnapshotLike<T> | SignedSnapshot<T>,\n): snapshot is SignedSnapshot<T> {\n\treturn \"signature\" in snapshot && typeof snapshot.signature === \"string\";\n}\n\n/**\n * Sign a distributable snapshot using HMAC-SHA256.\n * Creates a tamper-proof signature that can be verified later.\n *\n * **Security Notes:**\n * - Use a cryptographically random secret of at least 32 bytes\n * - Store the secret securely (environment variable, secrets manager)\n * - Never expose the secret to clients\n * - The signature covers all snapshot fields for integrity\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({\n * includeDerivations: ['canUseFeature', 'limits'],\n * ttlSeconds: 3600,\n * });\n *\n * // Sign the snapshot (server-side only)\n * const signed = await signSnapshot(snapshot, process.env.SNAPSHOT_SECRET);\n *\n * // Store in JWT, Redis, or send to client\n * const jwt = createJWT({ snapshot: signed });\n *\n * // Later, verify the signature\n * const isValid = await verifySnapshotSignature(signed, process.env.SNAPSHOT_SECRET);\n * if (!isValid) {\n * throw new Error('Snapshot has been tampered with');\n * }\n * ```\n *\n * @param snapshot - The snapshot to sign\n * @param secret - The HMAC secret (string or Uint8Array)\n * @returns A signed snapshot with the signature attached\n */\nexport async function signSnapshot<T>(\n\tsnapshot: DistributableSnapshotLike<T>,\n\tsecret: string | Uint8Array,\n): Promise<SignedSnapshot<T>> {\n\t// Create a canonical representation for signing\n\tconst payload = stableStringify({\n\t\tdata: snapshot.data,\n\t\tcreatedAt: snapshot.createdAt,\n\t\texpiresAt: snapshot.expiresAt,\n\t\tversion: snapshot.version,\n\t\tmetadata: snapshot.metadata,\n\t});\n\n\tconst signature = await hmacSha256(payload, secret);\n\n\treturn {\n\t\t...snapshot,\n\t\tsignature,\n\t\talgorithm: \"hmac-sha256\",\n\t};\n}\n\n/**\n * Verify the signature of a signed snapshot.\n * Returns true if the signature is valid, false otherwise.\n *\n * **Important:** Always verify signatures before trusting snapshot data,\n * especially if the snapshot was received from an untrusted source (client, cache).\n *\n * @example\n * ```typescript\n * // Receive signed snapshot from client or cache\n * const snapshot = JSON.parse(cachedData);\n *\n * // Verify before using\n * const isValid = await verifySnapshotSignature(snapshot, process.env.SNAPSHOT_SECRET);\n * if (!isValid) {\n * throw new Error('Invalid snapshot signature - possible tampering');\n * }\n *\n * // Now safe to use snapshot.data\n * if (snapshot.data.canUseFeature.api) {\n * // Grant access\n * }\n * ```\n *\n * @param signedSnapshot - The signed snapshot to verify\n * @param secret - The HMAC secret (must match the signing secret)\n * @returns True if signature is valid, false otherwise\n */\nexport async function verifySnapshotSignature<T>(\n\tsignedSnapshot: SignedSnapshot<T>,\n\tsecret: string | Uint8Array,\n): Promise<boolean> {\n\tif (!signedSnapshot.signature || signedSnapshot.algorithm !== \"hmac-sha256\") {\n\t\treturn false;\n\t}\n\n\t// Recreate the canonical payload (same as signing)\n\tconst payload = stableStringify({\n\t\tdata: signedSnapshot.data,\n\t\tcreatedAt: signedSnapshot.createdAt,\n\t\texpiresAt: signedSnapshot.expiresAt,\n\t\tversion: signedSnapshot.version,\n\t\tmetadata: signedSnapshot.metadata,\n\t});\n\n\tconst expectedSignature = await hmacSha256(payload, secret);\n\n\t// Use timing-safe comparison\n\treturn timingSafeEqual(signedSnapshot.signature, expectedSignature);\n}\n\n/**\n * Create HMAC-SHA256 signature of a message.\n * Uses Web Crypto API for cross-platform support (Node.js, browsers, Deno, Bun).\n */\nasync function hmacSha256(\n\tmessage: string,\n\tsecret: string | Uint8Array,\n): Promise<string> {\n\t// Convert secret to Uint8Array if string\n\tconst secretBytes: Uint8Array =\n\t\ttypeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\n\t// Import key for HMAC\n\tconst algorithm: HmacImportParams = { name: \"HMAC\", hash: { name: \"SHA-256\" } };\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tsecretBytes as unknown as ArrayBuffer,\n\t\talgorithm,\n\t\tfalse,\n\t\t[\"sign\"],\n\t);\n\n\t// Sign the message\n\tconst messageBytes = new TextEncoder().encode(message);\n\tconst signature = await crypto.subtle.sign(\"HMAC\", key, messageBytes);\n\n\t// Convert to hex string\n\treturn Array.from(new Uint8Array(signature))\n\t\t.map((b) => b.toString(16).padStart(2, \"0\"))\n\t\t.join(\"\");\n}\n\n/**\n * Timing-safe string comparison to prevent timing attacks.\n * Both strings should be the same length (hex signatures from same algorithm).\n */\nfunction timingSafeEqual(a: string, b: string): boolean {\n\tif (a.length !== b.length) {\n\t\treturn false;\n\t}\n\n\tlet result = 0;\n\tfor (let i = 0; i < a.length; i++) {\n\t\tresult |= a.charCodeAt(i) ^ b.charCodeAt(i);\n\t}\n\treturn result === 0;\n}\n","/**\n * Requirements - Typed requirement identity with custom dedupe keys\n *\n * Features:\n * - Type-safe requirement definitions\n * - Stable identity generation\n * - Custom key functions for deduplication control\n * - Requirement comparison and hashing\n */\n\nimport type { Requirement, RequirementKeyFn, RequirementWithId } from \"./types.js\";\nimport { stableStringify } from \"../utils/utils.js\";\n\n// ============================================================================\n// Requirement Identity\n// ============================================================================\n\n/**\n * Generate a stable ID for a requirement.\n * Uses type + sorted properties by default.\n */\nexport function generateRequirementId(\n\treq: Requirement,\n\tkeyFn?: RequirementKeyFn,\n): string {\n\t// Use custom key function if provided\n\tif (keyFn) {\n\t\treturn keyFn(req);\n\t}\n\n\t// Default: type + stable JSON of other properties\n\tconst { type, ...rest } = req;\n\tconst sortedRest = stableStringify(rest);\n\treturn `${type}:${sortedRest}`;\n}\n\n/**\n * Check if two requirements are equal by their IDs.\n */\nexport function requirementsEqual(\n\ta: RequirementWithId,\n\tb: RequirementWithId,\n): boolean {\n\treturn a.id === b.id;\n}\n\n/**\n * Create a requirement with its computed ID.\n */\nexport function createRequirementWithId(\n\trequirement: Requirement,\n\tfromConstraint: string,\n\tkeyFn?: RequirementKeyFn,\n): RequirementWithId {\n\treturn {\n\t\trequirement,\n\t\tid: generateRequirementId(requirement, keyFn),\n\t\tfromConstraint,\n\t};\n}\n\n// ============================================================================\n// Requirement Helpers\n// ============================================================================\n\n/**\n * Helper to create typed requirements with a fluent API.\n *\n * Creates a factory function that produces requirements with a specific type.\n * Useful for creating requirements in constraint definitions.\n *\n * @param type - The requirement type string\n * @returns A factory function that creates requirements with the given type\n *\n * @example\n * ```typescript\n * // Create a requirement factory\n * const fetchUser = req(\"FETCH_USER\");\n *\n * // Use in constraint definition\n * constraints: {\n * needsUser: {\n * when: (facts) => facts.userId && !facts.user,\n * require: fetchUser({ userId: 123, priority: \"high\" }),\n * },\n * }\n *\n * // Results in: { type: \"FETCH_USER\", userId: 123, priority: \"high\" }\n * ```\n */\nexport function req<T extends string>(type: T) {\n\treturn <P extends Record<string, unknown>>(props: P) => ({\n\t\ttype,\n\t\t...props,\n\t}) as Requirement & { type: T } & P;\n}\n\n/**\n * Check if a requirement matches a type.\n */\nexport function isRequirementType<T extends string>(\n\treq: Requirement,\n\ttype: T,\n): req is Requirement & { type: T } {\n\treturn req.type === type;\n}\n\n/**\n * Create a type guard for resolver `requirement` predicate.\n * Cleaner alternative to writing verbose type guards.\n *\n * @example\n * ```typescript\n * // With explicit requirement type (recommended for complex types)\n * interface FetchUserRequirement { type: \"FETCH_USER\"; userId: string }\n * requirement: forType<FetchUserRequirement>(\"FETCH_USER\"),\n * key: (req) => req.userId, // req is FetchUserRequirement\n *\n * // Or simple string literal (for basic types)\n * requirement: forType(\"FETCH_USER\"),\n * key: (req) => req.type, // req is Requirement & { type: \"FETCH_USER\" }\n * ```\n */\nexport function forType<R extends Requirement>(\n\ttype: R[\"type\"],\n): (req: Requirement) => req is R;\nexport function forType<T extends string>(\n\ttype: T,\n): (req: Requirement) => req is Requirement & { type: T };\nexport function forType<T extends string>(\n\ttype: T,\n): (req: Requirement) => req is Requirement & { type: T } {\n\treturn (req): req is Requirement & { type: T } => req.type === type;\n}\n\n// ============================================================================\n// Requirement Set Management\n// ============================================================================\n\n/**\n * A set of requirements with automatic deduplication by ID.\n *\n * Requirements are uniquely identified by their ID (generated from type + properties).\n * When adding a requirement with a duplicate ID, the first one wins.\n *\n * @example\n * ```typescript\n * const set = new RequirementSet();\n *\n * // Add requirements\n * set.add(createRequirementWithId({ type: \"FETCH_USER\", userId: 1 }, \"constraint1\"));\n * set.add(createRequirementWithId({ type: \"FETCH_USER\", userId: 1 }, \"constraint2\")); // Ignored (duplicate)\n *\n * // Check and retrieve\n * console.log(set.size); // 1\n * console.log(set.has(\"FETCH_USER:{\\\"userId\\\":1}\")); // true\n *\n * // Diff with another set\n * const newSet = new RequirementSet();\n * newSet.add(createRequirementWithId({ type: \"FETCH_USER\", userId: 2 }, \"constraint1\"));\n * const { added, removed } = newSet.diff(set);\n * // added: [{ type: \"FETCH_USER\", userId: 2 }]\n * // removed: [{ type: \"FETCH_USER\", userId: 1 }]\n * ```\n */\nexport class RequirementSet {\n\tprivate map = new Map<string, RequirementWithId>();\n\n\t/**\n\t * Add a requirement to the set.\n\t * If a requirement with the same ID already exists, it is ignored (first wins).\n\t * @param req - The requirement with its computed ID\n\t */\n\tadd(req: RequirementWithId): void {\n\t\t// If already exists, keep the existing one (first wins)\n\t\tif (!this.map.has(req.id)) {\n\t\t\tthis.map.set(req.id, req);\n\t\t}\n\t}\n\n\t/** Remove a requirement by ID */\n\tremove(id: string): boolean {\n\t\treturn this.map.delete(id);\n\t}\n\n\t/** Check if a requirement exists */\n\thas(id: string): boolean {\n\t\treturn this.map.has(id);\n\t}\n\n\t/** Get a requirement by ID */\n\tget(id: string): RequirementWithId | undefined {\n\t\treturn this.map.get(id);\n\t}\n\n\t/** Get all requirements */\n\tall(): RequirementWithId[] {\n\t\treturn [...this.map.values()];\n\t}\n\n\t/** Get all requirement IDs */\n\tids(): string[] {\n\t\treturn [...this.map.keys()];\n\t}\n\n\t/** Get the count of requirements */\n\tget size(): number {\n\t\treturn this.map.size;\n\t}\n\n\t/** Clear all requirements */\n\tclear(): void {\n\t\tthis.map.clear();\n\t}\n\n\t/** Create a copy */\n\tclone(): RequirementSet {\n\t\tconst copy = new RequirementSet();\n\t\tfor (const req of this.map.values()) {\n\t\t\tcopy.add(req);\n\t\t}\n\t\treturn copy;\n\t}\n\n\t/** Diff with another set - returns added and removed */\n\tdiff(other: RequirementSet): {\n\t\tadded: RequirementWithId[];\n\t\tremoved: RequirementWithId[];\n\t\tunchanged: RequirementWithId[];\n\t} {\n\t\tconst added: RequirementWithId[] = [];\n\t\tconst removed: RequirementWithId[] = [];\n\t\tconst unchanged: RequirementWithId[] = [];\n\n\t\t// Find added (in this but not in other)\n\t\tfor (const req of this.map.values()) {\n\t\t\tif (!other.has(req.id)) {\n\t\t\t\tadded.push(req);\n\t\t\t} else {\n\t\t\t\tunchanged.push(req);\n\t\t\t}\n\t\t}\n\n\t\t// Find removed (in other but not in this)\n\t\tfor (const req of other.map.values()) {\n\t\t\tif (!this.map.has(req.id)) {\n\t\t\t\tremoved.push(req);\n\t\t\t}\n\t\t}\n\n\t\treturn { added, removed, unchanged };\n\t}\n}\n","/**\n * Constraints - Rules that produce requirements when conditions aren't met\n *\n * Features:\n * - Sync and async constraint evaluation\n * - Priority ordering (higher runs first)\n * - Timeout handling for async constraints\n * - Error isolation\n */\n\nimport { createRequirementWithId, RequirementSet } from \"./requirements.js\";\nimport { withTracking } from \"./tracking.js\";\nimport type {\n\tConstraintsDef,\n\tConstraintState,\n\tFacts,\n\tRequirement,\n\tRequirementKeyFn,\n\tRequirementWithId,\n\tSchema,\n} from \"./types.js\";\nimport { withTimeout } from \"../utils/utils.js\";\n\n// Local type alias for requirement output (avoid type arg issues)\ntype RequirementOutput = Requirement | Requirement[] | null;\n\n// ============================================================================\n// Constraints Manager\n// ============================================================================\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ConstraintsManager<_S extends Schema> {\n\t/** Evaluate all constraints and return unmet requirements */\n\tevaluate(changedKeys?: Set<string>): Promise<RequirementWithId[]>;\n\t/** Get the current state of a constraint */\n\tgetState(id: string): ConstraintState | undefined;\n\t/** Get all constraint states */\n\tgetAllStates(): ConstraintState[];\n\t/** Disable a constraint */\n\tdisable(id: string): void;\n\t/** Enable a constraint */\n\tenable(id: string): void;\n\t/** Invalidate constraints that depend on the given fact key */\n\tinvalidate(factKey: string): void;\n\t/** Mark a constraint's resolver as completed (for `after` ordering) */\n\tmarkResolved(constraintId: string): void;\n\t/** Check if a constraint has been resolved (for `after` ordering) */\n\tisResolved(constraintId: string): boolean;\n\t/** Register new constraint definitions (for dynamic module registration) */\n\tregisterDefinitions(newDefs: ConstraintsDef<Schema>): void;\n}\n\n/** Options for creating a constraints manager */\nexport interface CreateConstraintsOptions<S extends Schema> {\n\tdefinitions: ConstraintsDef<S>;\n\tfacts: Facts<S>;\n\t/** Custom key functions for requirements (by constraint ID) */\n\trequirementKeys?: Record<string, RequirementKeyFn>;\n\t/** Default timeout for async constraints (ms) */\n\tdefaultTimeout?: number;\n\t/** Callback when a constraint is evaluated */\n\tonEvaluate?: (id: string, active: boolean) => void;\n\t/** Callback when a constraint errors */\n\tonError?: (id: string, error: unknown) => void;\n}\n\n/** Default async constraint timeout (5 seconds) */\nconst DEFAULT_TIMEOUT = 5000;\n\n/**\n * Create a manager that evaluates constraint rules and produces unmet\n * requirements.\n *\n * Constraints are evaluated in priority order (higher first), with\n * topological ordering for same-priority constraints connected by `after`\n * dependencies. Supports sync and async `when()` predicates, incremental\n * evaluation based on changed fact keys, and per-constraint enable/disable.\n *\n * @param options - Constraint definitions, facts proxy, custom requirement key functions, and lifecycle callbacks\n * @returns A `ConstraintsManager` with evaluate/invalidate/enable/disable/markResolved methods\n */\nexport function createConstraintsManager<S extends Schema>(\n\toptions: CreateConstraintsOptions<S>,\n): ConstraintsManager<S> {\n\tconst {\n\t\tdefinitions,\n\t\tfacts,\n\t\trequirementKeys = {},\n\t\tdefaultTimeout = DEFAULT_TIMEOUT,\n\t\tonEvaluate,\n\t\tonError,\n\t} = options;\n\n\t// Internal state for each constraint\n\tconst states = new Map<string, ConstraintState>();\n\tconst disabled = new Set<string>();\n\n\t// Track which constraints are async\n\tconst asyncConstraintIds = new Set<string>();\n\n\t// Dependency tracking: which facts each constraint depends on\n\tconst constraintDeps = new Map<string, Set<string>>();\n\t// Reverse mapping: which constraints depend on each fact\n\tconst factToConstraints = new Map<string, Set<string>>();\n\t// Track which constraints need re-evaluation\n\tconst dirtyConstraints = new Set<string>();\n\t// Cache latest when() deps so they can be combined with require() deps atomically\n\tconst latestWhenDeps = new Map<string, Set<string>>();\n\t// Track last requirements for each constraint (for incremental updates)\n\tconst lastRequirements = new Map<string, RequirementWithId[]>();\n\t// First evaluation flag\n\tlet hasEvaluated = false;\n\t// Track resolved constraints (for `after` ordering)\n\tconst resolvedConstraints = new Set<string>();\n\t// Track constraints that didn't fire (when() returned false) - they don't block\n\tconst noFireConstraints = new Set<string>();\n\t// Reverse dependency map: which constraints depend on this one (for O(1) markResolved)\n\tconst dependsOnMe = new Map<string, Set<string>>();\n\t// Topological order of constraints (dependencies before dependents)\n\tlet topologicalOrder: string[] = [];\n\t// Cached topological index map for O(1) lookups during sorting\n\tlet topologicalIndex: Map<string, number> = new Map();\n\n\t/**\n\t * Build reverse dependency map for O(1) lookups in markResolved.\n\t * Maps each constraint ID to the set of constraints that depend on it via `after`.\n\t */\n\tfunction buildReverseDependencyMap(): void {\n\t\tfor (const [id, def] of Object.entries(definitions)) {\n\t\t\tif (def.after) {\n\t\t\t\tfor (const depId of def.after) {\n\t\t\t\t\tif (definitions[depId]) {\n\t\t\t\t\t\tif (!dependsOnMe.has(depId)) {\n\t\t\t\t\t\t\tdependsOnMe.set(depId, new Set());\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdependsOnMe.get(depId)!.add(id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Detect cycles in the constraint dependency graph and compute topological order.\n\t * Uses DFS to find back edges and post-order for topological sort.\n\t *\n\t * The DFS visits dependencies first (via `after`), so post-order naturally gives us\n\t * topological order where dependencies appear before their dependents.\n\t */\n\tfunction detectCyclesAndComputeTopoOrder(): void {\n\t\tconst visited = new Set<string>();\n\t\tconst visiting = new Set<string>();\n\t\tconst postOrder: string[] = [];\n\n\t\tfunction visit(id: string, path: string[]): void {\n\t\t\tif (visited.has(id)) return;\n\n\t\t\tif (visiting.has(id)) {\n\t\t\t\tconst cycleStart = path.indexOf(id);\n\t\t\t\tconst cycle = [...path.slice(cycleStart), id].join(\" → \");\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Constraint cycle detected: ${cycle}. ` +\n\t\t\t\t\t`Remove one of the \\`after\\` dependencies to break the cycle.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tvisiting.add(id);\n\t\t\tpath.push(id);\n\n\t\t\tconst def = definitions[id];\n\t\t\tif (def?.after) {\n\t\t\t\tfor (const depId of def.after) {\n\t\t\t\t\t// Only check deps that exist in this manager\n\t\t\t\t\tif (definitions[depId]) {\n\t\t\t\t\t\tvisit(depId, path);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpath.pop();\n\t\t\tvisiting.delete(id);\n\t\t\tvisited.add(id);\n\t\t\tpostOrder.push(id);\n\t\t}\n\n\t\tfor (const id of Object.keys(definitions)) {\n\t\t\tvisit(id, []);\n\t\t}\n\n\t\t// Post-order with dependency-first traversal gives us topological order\n\t\t// (dependencies are added before dependents)\n\t\ttopologicalOrder = postOrder;\n\n\t\t// Build index map for O(1) lookups during sorting\n\t\ttopologicalIndex = new Map(topologicalOrder.map((id, index) => [id, index]));\n\t}\n\n\t// Validate constraint graph (always run - cycle in production would cause deadlock)\n\t// Also computes topological order for O(n) evaluation\n\tdetectCyclesAndComputeTopoOrder();\n\n\t// Build reverse dependency map for O(1) markResolved lookups\n\tbuildReverseDependencyMap();\n\n\t// Validate `after` references in dev mode (catch typos early)\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tfor (const [id, def] of Object.entries(definitions)) {\n\t\t\tif (def.after) {\n\t\t\t\tfor (const depId of def.after) {\n\t\t\t\t\tif (!definitions[depId]) {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[Directive] Constraint \"${id}\" references unknown constraint \"${depId}\" in \\`after\\`. ` +\n\t\t\t\t\t\t\t\t`This dependency will be ignored. Check for typos or ensure the constraint exists.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Determine if a constraint is async.\n\t * Uses the explicit `async` flag if provided, otherwise falls back to runtime detection.\n\t * Runtime detection is only used on first evaluation and logs a dev warning.\n\t */\n\tfunction isAsyncConstraint(id: string, def: ConstraintsDef<S>[string]): boolean {\n\t\t// Prefer explicit flag to avoid runtime detection side effects\n\t\tif (def.async !== undefined) {\n\t\t\treturn def.async;\n\t\t}\n\n\t\t// Check if we've already detected this constraint as async\n\t\tif (asyncConstraintIds.has(id)) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Runtime detection is deferred to first evaluation\n\t\t// We'll detect it in evaluateSync if it returns a Promise\n\t\treturn false;\n\t}\n\n\t/** Initialize state for a constraint */\n\tfunction initState(id: string): ConstraintState {\n\t\tconst def = definitions[id];\n\t\tif (!def) {\n\t\t\tthrow new Error(`[Directive] Unknown constraint: ${id}`);\n\t\t}\n\n\t\tconst isAsync = isAsyncConstraint(id, def);\n\t\tif (isAsync) {\n\t\t\tasyncConstraintIds.add(id);\n\t\t}\n\n\t\tconst state: ConstraintState = {\n\t\t\tid,\n\t\t\tpriority: def.priority ?? 0,\n\t\t\tisAsync,\n\t\t\tlastResult: null,\n\t\t\tisEvaluating: false,\n\t\t\terror: null,\n\t\t\tlastResolvedAt: null,\n\t\t\tafter: def.after ?? [],\n\t\t};\n\n\t\tstates.set(id, state);\n\t\treturn state;\n\t}\n\n\t/** Get or create state for a constraint */\n\tfunction getState(id: string): ConstraintState {\n\t\treturn states.get(id) ?? initState(id);\n\t}\n\n\t/** Update dependency tracking for a constraint */\n\tfunction updateDependencies(id: string, newDeps: Set<string>): void {\n\t\tconst oldDeps = constraintDeps.get(id) ?? new Set();\n\n\t\t// Remove old dependencies\n\t\tfor (const dep of oldDeps) {\n\t\t\tconst constraints = factToConstraints.get(dep);\n\t\t\tconstraints?.delete(id);\n\t\t\tif (constraints && constraints.size === 0) {\n\t\t\t\tfactToConstraints.delete(dep);\n\t\t\t}\n\t\t}\n\n\t\t// Add new dependencies\n\t\tfor (const dep of newDeps) {\n\t\t\tif (!factToConstraints.has(dep)) {\n\t\t\t\tfactToConstraints.set(dep, new Set());\n\t\t\t}\n\t\t\tfactToConstraints.get(dep)!.add(id);\n\t\t}\n\n\t\tconstraintDeps.set(id, newDeps);\n\t}\n\n\t/** Evaluate a single sync constraint */\n\tfunction evaluateSync(id: string): boolean | Promise<boolean> {\n\t\tconst def = definitions[id];\n\t\tif (!def) return false;\n\n\t\tconst state = getState(id);\n\n\t\tstate.isEvaluating = true;\n\t\tstate.error = null;\n\n\t\ttry {\n\t\t\t// If explicit deps are provided, skip auto-tracking overhead\n\t\t\tlet result: boolean | Promise<boolean>;\n\t\t\tif (def.deps) {\n\t\t\t\tresult = def.when(facts);\n\t\t\t\tlatestWhenDeps.set(id, new Set(def.deps));\n\t\t\t} else {\n\t\t\t\t// Track dependencies during evaluation\n\t\t\t\tconst tracked = withTracking(() => def.when(facts));\n\t\t\t\tresult = tracked.value;\n\t\t\t\t// Save when deps — combined with require deps in processConstraintResult\n\t\t\t\tlatestWhenDeps.set(id, tracked.deps);\n\t\t\t}\n\n\t\t\t// Runtime async detection: if this was thought to be sync but returns a Promise\n\t\t\tif (result instanceof Promise) {\n\t\t\t\t// Mark as async for future evaluations\n\t\t\t\tasyncConstraintIds.add(id);\n\t\t\t\tstate.isAsync = true;\n\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] Constraint \"${id}\" returned a Promise but was not marked as async. ` +\n\t\t\t\t\t\t\t`Add \\`async: true\\` to the constraint definition to avoid this warning and improve performance.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Return the promise to be handled as async\n\t\t\t\treturn result.then((asyncResult) => {\n\t\t\t\t\tstate.lastResult = asyncResult;\n\t\t\t\t\tstate.isEvaluating = false;\n\t\t\t\t\tonEvaluate?.(id, asyncResult);\n\t\t\t\t\treturn asyncResult;\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tstate.error = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\tstate.lastResult = false;\n\t\t\t\t\tstate.isEvaluating = false;\n\t\t\t\t\tonError?.(id, error);\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tstate.lastResult = result;\n\t\t\tstate.isEvaluating = false;\n\t\t\tonEvaluate?.(id, result);\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tstate.error = error instanceof Error ? error : new Error(String(error));\n\t\t\tstate.lastResult = false;\n\t\t\tstate.isEvaluating = false;\n\t\t\tonError?.(id, error);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** Evaluate a single async constraint with timeout */\n\tasync function evaluateAsync(id: string): Promise<boolean> {\n\t\tconst def = definitions[id];\n\t\tif (!def) return false;\n\n\t\tconst state = getState(id);\n\t\tconst timeout = def.timeout ?? defaultTimeout;\n\n\t\tstate.isEvaluating = true;\n\t\tstate.error = null;\n\n\t\t// Register explicit deps before await (auto-tracking can't work across async boundaries)\n\t\tif (def.deps?.length) {\n\t\t\tconst depsSet = new Set(def.deps);\n\t\t\tupdateDependencies(id, depsSet);\n\t\t\tlatestWhenDeps.set(id, depsSet);\n\t\t}\n\n\t\ttry {\n\t\t\tconst resultPromise = def.when(facts) as Promise<boolean>;\n\n\t\t\t// Race against timeout (with proper cleanup)\n\t\t\tconst result = await withTimeout(\n\t\t\t\tresultPromise,\n\t\t\t\ttimeout,\n\t\t\t\t`Constraint \"${id}\" timed out after ${timeout}ms`,\n\t\t\t);\n\n\t\t\tstate.lastResult = result;\n\t\t\tstate.isEvaluating = false;\n\t\t\tonEvaluate?.(id, result);\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tstate.error = error instanceof Error ? error : new Error(String(error));\n\t\t\tstate.lastResult = false;\n\t\t\tstate.isEvaluating = false;\n\t\t\tonError?.(id, error);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** Max requirements per constraint before warning in dev mode */\n\tconst MAX_REQUIREMENTS_WARNING_THRESHOLD = 10;\n\n\t/**\n\t * Normalize a requirement output to an array of requirements.\n\t * - null/undefined → []\n\t * - single requirement → [requirement]\n\t * - array → filtered to remove null/undefined\n\t */\n\tfunction normalizeRequirements(output: RequirementOutput, constraintId?: string): Requirement[] {\n\t\tif (output === null || output === undefined) {\n\t\t\treturn [];\n\t\t}\n\t\tif (Array.isArray(output)) {\n\t\t\t// Filter out null/undefined from arrays\n\t\t\tconst filtered = output.filter((r): r is Requirement => r !== null && r !== undefined);\n\n\t\t\t// Warn in dev mode if constraint produces many requirements\n\t\t\tif (\n\t\t\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\t\t\tfiltered.length > MAX_REQUIREMENTS_WARNING_THRESHOLD &&\n\t\t\t\tconstraintId\n\t\t\t) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] Constraint \"${constraintId}\" produced ${filtered.length} requirements. ` +\n\t\t\t\t\t\t`Consider splitting into multiple constraints for better performance.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn filtered;\n\t\t}\n\t\treturn [output];\n\t}\n\n\t/** Get the requirements for a constraint, tracking dependencies if require is a function */\n\tfunction getRequirements(id: string): { requirements: Requirement[]; deps: Set<string> } {\n\t\tconst def = definitions[id];\n\t\tif (!def) return { requirements: [], deps: new Set() };\n\n\t\tconst requireDef = def.require;\n\t\tif (typeof requireDef === \"function\") {\n\t\t\t// Track dependencies when require is a function\n\t\t\tconst { value: output, deps } = withTracking(() => requireDef(facts));\n\t\t\tconst requirements = normalizeRequirements(output as RequirementOutput, id);\n\t\t\treturn { requirements, deps };\n\t\t}\n\n\t\tconst requirements = normalizeRequirements(requireDef as RequirementOutput, id);\n\t\treturn { requirements, deps: new Set() };\n\t}\n\n\t/** Merge additional dependencies into existing constraint deps */\n\tfunction mergeDependencies(id: string, additionalDeps: Set<string>): void {\n\t\tif (additionalDeps.size === 0) return;\n\n\t\tconst existingDeps = constraintDeps.get(id) ?? new Set();\n\t\tfor (const dep of additionalDeps) {\n\t\t\texistingDeps.add(dep);\n\t\t\t// Update reverse mapping\n\t\t\tif (!factToConstraints.has(dep)) {\n\t\t\t\tfactToConstraints.set(dep, new Set());\n\t\t\t}\n\t\t\tfactToConstraints.get(dep)!.add(id);\n\t\t}\n\t\tconstraintDeps.set(id, existingDeps);\n\t}\n\n\t// Initialize all constraint states and cache sorted order\n\tlet sortedConstraintIds: string[] | null = null;\n\n\t/**\n\t * Get constraint IDs sorted by:\n\t * 1. Priority (higher first)\n\t * 2. Topological order (dependencies before dependents) for same priority\n\t * This enables O(n) evaluation in the best case when priorities align with dependencies.\n\t *\n\t * Uses cached topologicalIndex for O(1) lookups during comparison.\n\t */\n\tfunction getSortedConstraintIds(): string[] {\n\t\tif (!sortedConstraintIds) {\n\t\t\tsortedConstraintIds = Object.keys(definitions).sort((a, b) => {\n\t\t\t\tconst stateA = getState(a);\n\t\t\t\tconst stateB = getState(b);\n\n\t\t\t\t// Primary sort: priority (higher first)\n\t\t\t\tconst priorityDiff = stateB.priority - stateA.priority;\n\t\t\t\tif (priorityDiff !== 0) return priorityDiff;\n\n\t\t\t\t// Secondary sort: topological order (dependencies first)\n\t\t\t\t// Uses cached topologicalIndex for O(1) lookups\n\t\t\t\tconst topoA = topologicalIndex.get(a) ?? 0;\n\t\t\t\tconst topoB = topologicalIndex.get(b) ?? 0;\n\t\t\t\treturn topoA - topoB;\n\t\t\t});\n\t\t}\n\t\treturn sortedConstraintIds;\n\t}\n\n\tfor (const id of Object.keys(definitions)) {\n\t\tinitState(id);\n\t}\n\n\t// Dev-mode: warn about async constraints without explicit deps\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tfor (const [id, def] of Object.entries(definitions)) {\n\t\t\tif (def.async && !def.deps) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] Async constraint \"${id}\" has no \\`deps\\` declared. ` +\n\t\t\t\t\t`Auto-tracking cannot work across async boundaries. ` +\n\t\t\t\t\t`Add \\`deps: [\"key1\", \"key2\"]\\` to enable dependency tracking.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Check if a constraint's `after` dependencies are satisfied.\n\t * A dependency is satisfied if:\n\t * - It has been resolved (resolver completed successfully)\n\t * - It didn't fire (when() returned false) - nothing to wait for\n\t * - It is disabled - can't fire\n\t * - It doesn't exist in this manager (cross-module, handled externally)\n\t */\n\tfunction areAfterDependenciesSatisfied(id: string): boolean {\n\t\tconst state = states.get(id);\n\t\tif (!state || state.after.length === 0) return true;\n\n\t\tfor (const depId of state.after) {\n\t\t\t// Skip deps that don't exist (cross-module, handled externally)\n\t\t\tif (!definitions[depId]) continue;\n\n\t\t\t// Skip disabled deps - they can't fire\n\t\t\tif (disabled.has(depId)) continue;\n\n\t\t\t// If dep didn't fire (when returned false), no need to wait\n\t\t\tif (noFireConstraints.has(depId)) continue;\n\n\t\t\t// If dep hasn't been resolved yet, we're blocked\n\t\t\tif (!resolvedConstraints.has(depId)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tconst manager: ConstraintsManager<S> = {\n\t\tasync evaluate(changedKeys?: Set<string>): Promise<RequirementWithId[]> {\n\t\t\tconst requirements = new RequirementSet();\n\n\t\t\t// Note: resolvedConstraints persists across reconcile cycles intentionally.\n\t\t\t// `after` ordering means \"wait until dependency's resolver has completed\",\n\t\t\t// and that completion happens in a different cycle than the evaluation.\n\t\t\t// noFireConstraints is re-populated during each evaluation pass.\n\t\t\tnoFireConstraints.clear();\n\n\t\t\t// Get all enabled constraints (use cached sort order)\n\t\t\tconst allConstraintIds = getSortedConstraintIds().filter((id) => !disabled.has(id));\n\n\t\t\t// Determine which constraints to evaluate\n\t\t\tlet constraintsToEvaluate: string[];\n\n\t\t\tif (!hasEvaluated || !changedKeys || changedKeys.size === 0) {\n\t\t\t\t// First evaluation or no specific changes: evaluate all\n\t\t\t\tconstraintsToEvaluate = allConstraintIds;\n\t\t\t\thasEvaluated = true;\n\t\t\t} else {\n\t\t\t\t// Incremental: only evaluate constraints affected by changed keys\n\t\t\t\tconst affected = new Set<string>();\n\t\t\t\tfor (const key of changedKeys) {\n\t\t\t\t\tconst dependentConstraints = factToConstraints.get(key);\n\t\t\t\t\tif (dependentConstraints) {\n\t\t\t\t\t\tfor (const id of dependentConstraints) {\n\t\t\t\t\t\t\tif (!disabled.has(id)) {\n\t\t\t\t\t\t\t\taffected.add(id);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Also include any dirty constraints\n\t\t\t\tfor (const id of dirtyConstraints) {\n\t\t\t\t\tif (!disabled.has(id)) {\n\t\t\t\t\t\taffected.add(id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdirtyConstraints.clear();\n\t\t\t\tconstraintsToEvaluate = [...affected];\n\n\t\t\t\t// For constraints NOT being re-evaluated, add their last requirements\n\t\t\t\tfor (const id of allConstraintIds) {\n\t\t\t\t\tif (!affected.has(id)) {\n\t\t\t\t\t\tconst lastReqs = lastRequirements.get(id);\n\t\t\t\t\t\tif (lastReqs) {\n\t\t\t\t\t\t\tfor (const req of lastReqs) {\n\t\t\t\t\t\t\t\trequirements.add(req);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Process a constraint result: handle requirements and track no-fire state\n\t\t\t */\n\t\t\tfunction processConstraintResult(id: string, active: boolean): void {\n\t\t\t\tif (disabled.has(id)) return;\n\n\t\t\t\tconst whenDeps = latestWhenDeps.get(id);\n\n\t\t\t\tif (!active) {\n\t\t\t\t\t// when() returned false — update with just when deps (no require deps needed)\n\t\t\t\t\tif (whenDeps !== undefined) {\n\t\t\t\t\t\tupdateDependencies(id, whenDeps);\n\t\t\t\t\t}\n\t\t\t\t\tnoFireConstraints.add(id);\n\t\t\t\t\tlastRequirements.set(id, []);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Remove from no-fire tracking since it fired\n\t\t\t\tnoFireConstraints.delete(id);\n\n\t\t\t\tlet reqs: Requirement[];\n\t\t\t\tlet requireDeps: Set<string>;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = getRequirements(id);\n\t\t\t\t\treqs = result.requirements;\n\t\t\t\t\trequireDeps = result.deps;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tonError?.(id, error);\n\t\t\t\t\tif (whenDeps !== undefined) {\n\t\t\t\t\t\tupdateDependencies(id, whenDeps);\n\t\t\t\t\t}\n\t\t\t\t\tlastRequirements.set(id, []);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// Combine when() + require() deps atomically to prevent\n\t\t\t\t// require deps from being temporarily lost between updates\n\t\t\t\tif (whenDeps !== undefined) {\n\t\t\t\t\tconst combinedDeps = new Set(whenDeps);\n\t\t\t\t\tfor (const dep of requireDeps) {\n\t\t\t\t\t\tcombinedDeps.add(dep);\n\t\t\t\t\t}\n\t\t\t\t\tupdateDependencies(id, combinedDeps);\n\t\t\t\t} else {\n\t\t\t\t\t// Async constraint (no when deps tracked) — merge additively\n\t\t\t\t\tmergeDependencies(id, requireDeps);\n\t\t\t\t}\n\t\t\t\tif (reqs.length > 0) {\n\t\t\t\t\tconst keyFn = requirementKeys[id];\n\t\t\t\t\tconst reqsWithId = reqs.map((req) => createRequirementWithId(req, id, keyFn));\n\t\t\t\t\tfor (const reqWithId of reqsWithId) {\n\t\t\t\t\t\trequirements.add(reqWithId);\n\t\t\t\t\t}\n\t\t\t\t\tlastRequirements.set(id, reqsWithId);\n\t\t\t\t} else {\n\t\t\t\t\tlastRequirements.set(id, []);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Evaluate constraints, respecting `after` dependencies.\n\t\t\t * Returns list of constraints that are still blocked after this pass.\n\t\t\t */\n\t\t\tasync function evaluateConstraintBatch(constraintIds: string[]): Promise<string[]> {\n\t\t\t\t// Filter out constraints blocked by `after` dependencies\n\t\t\t\tconst blockedConstraints: string[] = [];\n\t\t\t\tconst readyToEvaluate: string[] = [];\n\n\t\t\t\tfor (const id of constraintIds) {\n\t\t\t\t\tif (areAfterDependenciesSatisfied(id)) {\n\t\t\t\t\t\treadyToEvaluate.push(id);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblockedConstraints.push(id);\n\t\t\t\t\t\t// Keep last requirements for blocked constraints\n\t\t\t\t\t\tconst lastReqs = lastRequirements.get(id);\n\t\t\t\t\t\tif (lastReqs) {\n\t\t\t\t\t\t\tfor (const req of lastReqs) {\n\t\t\t\t\t\t\t\trequirements.add(req);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (readyToEvaluate.length === 0) {\n\t\t\t\t\treturn blockedConstraints;\n\t\t\t\t}\n\n\t\t\t\t// Separate sync and async constraints from ready-to-evaluate\n\t\t\t\tconst syncConstraints: string[] = [];\n\t\t\t\tconst asyncConstraints: string[] = [];\n\n\t\t\t\tfor (const id of readyToEvaluate) {\n\t\t\t\t\tconst state = getState(id);\n\t\t\t\t\tif (state.isAsync) {\n\t\t\t\t\t\tasyncConstraints.push(id);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsyncConstraints.push(id);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Evaluate sync constraints first (they're fast)\n\t\t\t\t// Some may turn out to be async at runtime - collect those for async evaluation\n\t\t\t\tconst unexpectedAsync: Array<{ id: string; promise: Promise<boolean> }> = [];\n\n\t\t\t\tfor (const id of syncConstraints) {\n\t\t\t\t\tconst result = evaluateSync(id);\n\n\t\t\t\t\t// Handle runtime-detected async constraints\n\t\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\t\tunexpectedAsync.push({ id, promise: result });\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tprocessConstraintResult(id, result);\n\t\t\t\t}\n\n\t\t\t\t// Handle any sync constraints that turned out to be async\n\t\t\t\tif (unexpectedAsync.length > 0) {\n\t\t\t\t\tconst asyncResults = await Promise.all(\n\t\t\t\t\t\tunexpectedAsync.map(async ({ id, promise }) => ({\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tactive: await promise,\n\t\t\t\t\t\t})),\n\t\t\t\t\t);\n\n\t\t\t\t\tfor (const { id, active } of asyncResults) {\n\t\t\t\t\t\tprocessConstraintResult(id, active);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Evaluate async constraints in parallel\n\t\t\t\tif (asyncConstraints.length > 0) {\n\t\t\t\t\tconst asyncResults = await Promise.all(\n\t\t\t\t\t\tasyncConstraints.map(async (id) => ({\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tactive: await evaluateAsync(id),\n\t\t\t\t\t\t})),\n\t\t\t\t\t);\n\n\t\t\t\t\tfor (const { id, active } of asyncResults) {\n\t\t\t\t\t\tprocessConstraintResult(id, active);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn blockedConstraints;\n\t\t\t}\n\n\t\t\t// Evaluate constraints in passes until no blocked constraints become unblocked\n\t\t\tlet remainingToEvaluate = constraintsToEvaluate;\n\t\t\tlet maxPasses = constraintsToEvaluate.length + 1; // Prevent infinite loops\n\n\t\t\twhile (remainingToEvaluate.length > 0 && maxPasses > 0) {\n\t\t\t\tconst previousRemaining = remainingToEvaluate.length;\n\t\t\t\tremainingToEvaluate = await evaluateConstraintBatch(remainingToEvaluate);\n\n\t\t\t\t// If no progress was made (all still blocked), break\n\t\t\t\tif (remainingToEvaluate.length === previousRemaining) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tmaxPasses--;\n\t\t\t}\n\n\t\t\treturn requirements.all();\n\t\t},\n\n\t\tgetState(id: string): ConstraintState | undefined {\n\t\t\treturn states.get(id);\n\t\t},\n\n\t\tgetAllStates(): ConstraintState[] {\n\t\t\treturn [...states.values()];\n\t\t},\n\n\t\tdisable(id: string): void {\n\t\t\tdisabled.add(id);\n\t\t\t// Invalidate cache when constraints change\n\t\t\tsortedConstraintIds = null;\n\t\t\t// Mark as dirty so it gets removed from requirements on next evaluate\n\t\t\tlastRequirements.delete(id);\n\n\t\t\t// Clean up dependency maps for disabled constraint\n\t\t\tconst deps = constraintDeps.get(id);\n\t\t\tif (deps) {\n\t\t\t\tfor (const dep of deps) {\n\t\t\t\t\tconst constraints = factToConstraints.get(dep);\n\t\t\t\t\tif (constraints) {\n\t\t\t\t\t\tconstraints.delete(id);\n\t\t\t\t\t\tif (constraints.size === 0) {\n\t\t\t\t\t\t\tfactToConstraints.delete(dep);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconstraintDeps.delete(id);\n\t\t\t}\n\t\t\tlatestWhenDeps.delete(id);\n\t\t},\n\n\t\tenable(id: string): void {\n\t\t\tdisabled.delete(id);\n\t\t\t// Invalidate cache when constraints change\n\t\t\tsortedConstraintIds = null;\n\t\t\t// Mark as dirty so it gets evaluated on next cycle\n\t\t\tdirtyConstraints.add(id);\n\t\t},\n\n\t\tinvalidate(factKey: string): void {\n\t\t\t// Mark all constraints that depend on this fact as dirty\n\t\t\tconst dependentConstraints = factToConstraints.get(factKey);\n\t\t\tif (dependentConstraints) {\n\t\t\t\tfor (const id of dependentConstraints) {\n\t\t\t\t\tdirtyConstraints.add(id);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tmarkResolved(constraintId: string): void {\n\t\t\tresolvedConstraints.add(constraintId);\n\t\t\tconst state = states.get(constraintId);\n\t\t\tif (state) {\n\t\t\t\tstate.lastResolvedAt = Date.now();\n\t\t\t}\n\n\t\t\t// Mark all constraints that depend on this one (via `after`) as dirty\n\t\t\t// so they get re-evaluated on the next reconcile\n\t\t\t// Uses reverse dependency map for O(1) lookup instead of O(n*m) iteration\n\t\t\tconst dependents = dependsOnMe.get(constraintId);\n\t\t\tif (dependents) {\n\t\t\t\tfor (const id of dependents) {\n\t\t\t\t\tdirtyConstraints.add(id);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tisResolved(constraintId: string): boolean {\n\t\t\treturn resolvedConstraints.has(constraintId);\n\t\t},\n\n\t\tregisterDefinitions(newDefs: ConstraintsDef<Schema>): void {\n\t\t\tfor (const [key, def] of Object.entries(newDefs)) {\n\t\t\t\t(definitions as Record<string, unknown>)[key] = def;\n\t\t\t\tinitState(key);\n\t\t\t\tdirtyConstraints.add(key);\n\t\t\t}\n\t\t\t// Invalidate cached sort order\n\t\t\tsortedConstraintIds = null;\n\t\t\t// Rebuild topological order and reverse dependency map\n\t\t\t// so new `after` deps are validated for cycles and indexed\n\t\t\tdetectCyclesAndComputeTopoOrder();\n\t\t\tbuildReverseDependencyMap();\n\t\t},\n\t};\n\n\treturn manager;\n}\n","/**\n * Derivations - Auto-tracked computed values with composition\n *\n * Features:\n * - Automatic dependency tracking (no manual deps arrays)\n * - Memoization with smart invalidation\n * - Derivation composition (derivations can depend on other derivations)\n * - Circular dependency detection\n * - Lazy evaluation\n */\n\nimport { trackAccess, withTracking } from \"./tracking.js\";\nimport type {\n\tDerivationsDef,\n\tDerivationState,\n\tDerivedValues,\n\tFacts,\n\tFactsStore,\n\tSchema,\n} from \"./types.js\";\n\n// ============================================================================\n// Derivations Manager\n// ============================================================================\n\nexport interface DerivationsManager<S extends Schema, D extends DerivationsDef<S>> {\n\t/** Get a derived value (computes if stale) */\n\tget<K extends keyof D>(id: K): ReturnType<D[K]>;\n\t/** Check if a derivation is stale */\n\tisStale(id: keyof D): boolean;\n\t/** Invalidate derivations that depend on a fact key */\n\tinvalidate(factKey: string): void;\n\t/** Invalidate derivations for multiple fact keys, notifying listeners once at the end */\n\tinvalidateMany(factKeys: Iterable<string>): void;\n\t/** Invalidate all derivations */\n\tinvalidateAll(): void;\n\t/** Subscribe to derivation changes */\n\tsubscribe(ids: Array<keyof D>, listener: () => void): () => void;\n\t/** Get the proxy for composition */\n\tgetProxy(): DerivedValues<S, D>;\n\t/** Get dependencies for a derivation */\n\tgetDependencies(id: keyof D): Set<string>;\n\t/** Register new derivation definitions (for dynamic module registration) */\n\tregisterDefinitions(newDefs: DerivationsDef<S>): void;\n}\n\n/** Options for creating a derivations manager */\nexport interface CreateDerivationsOptions<S extends Schema, D extends DerivationsDef<S>> {\n\tdefinitions: D;\n\tfacts: Facts<S>;\n\tstore: FactsStore<S>;\n\t/** Callback when a derivation is computed */\n\tonCompute?: (id: string, value: unknown, deps: string[]) => void;\n\t/** Callback when a derivation is invalidated */\n\tonInvalidate?: (id: string) => void;\n\t/** Callback when a derivation errors */\n\tonError?: (id: string, error: unknown) => void;\n}\n\n/**\n * Create a manager for lazily-evaluated, auto-tracked derived values.\n *\n * Derivations are memoized computations that automatically track which facts\n * they read. When a tracked fact changes, the derivation is invalidated and\n * recomputed on next access. Derivations can depend on other derivations\n * (composition), and circular dependencies are detected at compute time.\n *\n * Notifications are deferred during invalidation so listeners always see\n * consistent state across multiple simultaneous fact changes.\n *\n * @param options - Derivation definitions, facts proxy, store, and optional lifecycle callbacks\n * @returns A `DerivationsManager` with get/invalidate/subscribe/getProxy methods\n */\nexport function createDerivationsManager<S extends Schema, D extends DerivationsDef<S>>(\n\toptions: CreateDerivationsOptions<S, D>,\n): DerivationsManager<S, D> {\n\tconst { definitions, facts, store: _store, onCompute, onInvalidate, onError } = options;\n\t// Note: _store is kept for API compatibility but invalidation is handled by the engine calling invalidate()\n\n\t// Internal state for each derivation\n\tconst states = new Map<string, DerivationState<unknown>>();\n\tconst listeners = new Map<string, Set<() => void>>();\n\n\t// Track which derivations depend on which fact keys\n\tconst factToDerivedDeps = new Map<string, Set<string>>();\n\t// Track which derivations depend on which other derivations\n\tconst derivedToDerivedDeps = new Map<string, Set<string>>();\n\n\t// Prototype pollution guard (same pattern as engine.ts, facts.ts, system.ts)\n\tconst BLOCKED_PROPS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n\t// Deferred notification: during invalidation, collect IDs to notify.\n\t// Listeners fire AFTER all invalidations complete so they see consistent state.\n\tlet invalidationDepth = 0;\n\tconst pendingNotifications = new Set<string>();\n\tlet isFlushing = false;\n\tconst MAX_FLUSH_ITERATIONS = 100;\n\n\t// The proxy for composition (derivations accessing other derivations)\n\tlet derivedProxy: DerivedValues<S, D>;\n\n\t/** Initialize state for a derivation */\n\tfunction initState(id: string): DerivationState<unknown> {\n\t\tconst def = definitions[id as keyof D];\n\t\tif (!def) {\n\t\t\tthrow new Error(`[Directive] Unknown derivation: ${id}`);\n\t\t}\n\n\t\tconst state: DerivationState<unknown> = {\n\t\t\tid,\n\t\t\tcompute: () => computeDerivation(id),\n\t\t\tcachedValue: undefined,\n\t\t\tdependencies: new Set(),\n\t\t\tisStale: true,\n\t\t\tisComputing: false,\n\t\t};\n\n\t\tstates.set(id, state);\n\t\treturn state;\n\t}\n\n\t/** Get or create state for a derivation */\n\tfunction getState(id: string): DerivationState<unknown> {\n\t\treturn states.get(id) ?? initState(id);\n\t}\n\n\t/** Compute a derivation and track its dependencies */\n\tfunction computeDerivation(id: string): unknown {\n\t\tconst state = getState(id);\n\t\tconst def = definitions[id as keyof D];\n\n\t\tif (!def) {\n\t\t\tthrow new Error(`[Directive] Unknown derivation: ${id}`);\n\t\t}\n\n\t\t// Circular dependency detection\n\t\tif (state.isComputing) {\n\t\t\tthrow new Error(`[Directive] Circular dependency detected in derivation: ${id}`);\n\t\t}\n\n\t\tstate.isComputing = true;\n\n\t\ttry {\n\t\t\t// Compute with tracking\n\t\t\tconst { value, deps } = withTracking(() => def(facts, derivedProxy));\n\n\t\t\t// Update state\n\t\t\tstate.cachedValue = value;\n\t\t\tstate.isStale = false;\n\n\t\t\t// Update dependency tracking\n\t\t\tupdateDependencies(id, deps);\n\n\t\t\t// Notify callback\n\t\t\tonCompute?.(id, value, [...deps]);\n\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tonError?.(id, error);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tstate.isComputing = false;\n\t\t}\n\t}\n\n\t/** Update dependency tracking for a derivation */\n\tfunction updateDependencies(id: string, newDeps: Set<string>): void {\n\t\tconst state = getState(id);\n\t\tconst oldDeps = state.dependencies;\n\n\t\t// Remove old fact dependencies\n\t\tfor (const dep of oldDeps) {\n\t\t\t// Check if it's a fact key or a derived key\n\t\t\tif (states.has(dep)) {\n\t\t\t\tconst depSet = derivedToDerivedDeps.get(dep);\n\t\t\t\tdepSet?.delete(id);\n\t\t\t\t// Clean up empty Sets to prevent memory leaks\n\t\t\t\tif (depSet && depSet.size === 0) {\n\t\t\t\t\tderivedToDerivedDeps.delete(dep);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst depSet = factToDerivedDeps.get(dep);\n\t\t\t\tdepSet?.delete(id);\n\t\t\t\t// Clean up empty Sets to prevent memory leaks\n\t\t\t\tif (depSet && depSet.size === 0) {\n\t\t\t\t\tfactToDerivedDeps.delete(dep);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Add new dependencies\n\t\tfor (const dep of newDeps) {\n\t\t\t// Check if it's a derivation or a fact\n\t\t\tif (definitions[dep as keyof D]) {\n\t\t\t\t// It's a derivation-to-derivation dependency\n\t\t\t\tif (!derivedToDerivedDeps.has(dep)) {\n\t\t\t\t\tderivedToDerivedDeps.set(dep, new Set());\n\t\t\t\t}\n\t\t\t\tderivedToDerivedDeps.get(dep)!.add(id);\n\t\t\t} else {\n\t\t\t\t// It's a fact dependency\n\t\t\t\tif (!factToDerivedDeps.has(dep)) {\n\t\t\t\t\tfactToDerivedDeps.set(dep, new Set());\n\t\t\t\t}\n\t\t\t\tfactToDerivedDeps.get(dep)!.add(id);\n\t\t\t}\n\t\t}\n\n\t\tstate.dependencies = newDeps;\n\t}\n\n\t/** Flush deferred notifications after all invalidations complete */\n\tfunction flushNotifications(): void {\n\t\tif (invalidationDepth > 0 || isFlushing) return;\n\n\t\tisFlushing = true;\n\t\ttry {\n\t\t\t// Loop until no more pending — listeners may trigger new invalidations\n\t\t\t// that add to pendingNotifications via re-entrant invalidate() calls.\n\t\t\tlet iterations = 0;\n\t\t\twhile (pendingNotifications.size > 0) {\n\t\t\t\tif (++iterations > MAX_FLUSH_ITERATIONS) {\n\t\t\t\t\tconst remaining = [...pendingNotifications];\n\t\t\t\t\tpendingNotifications.clear();\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Infinite derivation notification loop detected after ${MAX_FLUSH_ITERATIONS} iterations. ` +\n\t\t\t\t\t\t\t`Remaining: ${remaining.join(\", \")}. ` +\n\t\t\t\t\t\t\t`This usually means a derivation listener is mutating facts that re-trigger the same derivation.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst ids = [...pendingNotifications];\n\t\t\t\tpendingNotifications.clear();\n\n\t\t\t\tfor (const id of ids) {\n\t\t\t\t\tlisteners.get(id)?.forEach((listener) => listener());\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tisFlushing = false;\n\t\t}\n\t}\n\n\t/** Invalidate a derivation and its dependents */\n\tfunction invalidateDerivation(id: string, visited = new Set<string>()): void {\n\t\tif (visited.has(id)) return;\n\t\tvisited.add(id);\n\n\t\tconst state = states.get(id);\n\t\tif (!state || state.isStale) return;\n\n\t\tstate.isStale = true;\n\t\tonInvalidate?.(id);\n\n\t\t// Defer listener notification until all invalidations complete.\n\t\t// This prevents listeners from observing partially-stale state and\n\t\t// avoids infinite loops from Set mutation during iteration (listeners\n\t\t// recompute derivations → updateDependencies → modify dep Sets).\n\t\tpendingNotifications.add(id);\n\n\t\t// Invalidate derivations that depend on this one\n\t\tconst dependents = derivedToDerivedDeps.get(id);\n\t\tif (dependents) {\n\t\t\tfor (const dependent of dependents) {\n\t\t\t\tinvalidateDerivation(dependent, visited);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create the proxy for composition\n\tderivedProxy = new Proxy({} as DerivedValues<S, D>, {\n\t\tget(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\n\t\t\t// Track this derivation access so the consuming derivation\n\t\t\t// records a dependency on it (enables composition invalidation)\n\t\t\ttrackAccess(prop);\n\n\t\t\tconst state = getState(prop);\n\n\t\t\t// Recompute if stale\n\t\t\tif (state.isStale) {\n\t\t\t\tcomputeDerivation(prop);\n\t\t\t}\n\n\t\t\treturn state.cachedValue;\n\t\t},\n\t});\n\n\t// Note: Fact change invalidation is handled by the engine calling invalidate()\n\n\tconst manager: DerivationsManager<S, D> = {\n\t\tget<K extends keyof D>(id: K): ReturnType<D[K]> {\n\t\t\tconst state = getState(id as string);\n\n\t\t\tif (state.isStale) {\n\t\t\t\tcomputeDerivation(id as string);\n\t\t\t}\n\n\t\t\treturn state.cachedValue as ReturnType<D[K]>;\n\t\t},\n\n\t\tisStale(id: keyof D): boolean {\n\t\t\tconst state = states.get(id as string);\n\t\t\treturn state?.isStale ?? true;\n\t\t},\n\n\t\tinvalidate(factKey: string): void {\n\t\t\tconst dependents = factToDerivedDeps.get(factKey);\n\t\t\tif (!dependents) return;\n\n\t\t\tinvalidationDepth++;\n\t\t\ttry {\n\t\t\t\tfor (const id of dependents) {\n\t\t\t\t\tinvalidateDerivation(id);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tinvalidationDepth--;\n\t\t\t\tflushNotifications();\n\t\t\t}\n\t\t},\n\n\t\tinvalidateMany(factKeys: Iterable<string>): void {\n\t\t\tinvalidationDepth++;\n\t\t\ttry {\n\t\t\t\tfor (const factKey of factKeys) {\n\t\t\t\t\tconst dependents = factToDerivedDeps.get(factKey);\n\t\t\t\t\tif (!dependents) continue;\n\t\t\t\t\tfor (const id of dependents) {\n\t\t\t\t\t\tinvalidateDerivation(id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tinvalidationDepth--;\n\t\t\t\tflushNotifications();\n\t\t\t}\n\t\t},\n\n\t\tinvalidateAll(): void {\n\t\t\tinvalidationDepth++;\n\t\t\ttry {\n\t\t\t\tfor (const state of states.values()) {\n\t\t\t\t\tif (!state.isStale) {\n\t\t\t\t\t\tstate.isStale = true;\n\t\t\t\t\t\tpendingNotifications.add(state.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tinvalidationDepth--;\n\t\t\t\tflushNotifications();\n\t\t\t}\n\t\t},\n\n\t\tsubscribe(ids: Array<keyof D>, listener: () => void): () => void {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst idStr = id as string;\n\t\t\t\tif (!listeners.has(idStr)) {\n\t\t\t\t\tlisteners.set(idStr, new Set());\n\t\t\t\t}\n\t\t\t\tlisteners.get(idStr)!.add(listener);\n\t\t\t}\n\n\t\t\treturn () => {\n\t\t\t\tfor (const id of ids) {\n\t\t\t\t\tconst idStr = id as string;\n\t\t\t\t\tconst listenerSet = listeners.get(idStr);\n\t\t\t\t\tlistenerSet?.delete(listener);\n\t\t\t\t\t// Clean up empty Sets to prevent memory leaks\n\t\t\t\t\tif (listenerSet && listenerSet.size === 0) {\n\t\t\t\t\t\tlisteners.delete(idStr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\n\t\tgetProxy(): DerivedValues<S, D> {\n\t\t\treturn derivedProxy;\n\t\t},\n\n\t\tgetDependencies(id: keyof D): Set<string> {\n\t\t\treturn getState(id as string).dependencies;\n\t\t},\n\n\t\tregisterDefinitions(newDefs: DerivationsDef<S>): void {\n\t\t\tfor (const [key, fn] of Object.entries(newDefs)) {\n\t\t\t\t(definitions as Record<string, unknown>)[key] = fn;\n\t\t\t\tinitState(key);\n\t\t\t}\n\t\t},\n\t};\n\n\treturn manager;\n}\n","/**\n * Effects - Fire-and-forget side effects\n *\n * Features:\n * - Separate from requirement resolution\n * - Error isolation (never breaks reconciliation)\n * - Optional explicit dependencies for optimization\n * - Runs after facts stabilize\n *\n * IMPORTANT: Auto-tracking limitations\n * ------------------------------------\n * When using auto-tracking (no explicit `deps`), only SYNCHRONOUS fact accesses\n * are tracked. If your effect reads facts after an `await`, those reads are NOT\n * tracked and won't trigger the effect on future changes.\n *\n * For async effects, always use explicit `deps`:\n * @example\n * ```typescript\n * effects: {\n * // BAD: fetchData is async, facts.userId read after await won't be tracked\n * badEffect: {\n * run: async (facts) => {\n * await someAsyncOp();\n * console.log(facts.userId); // NOT tracked!\n * },\n * },\n * // GOOD: explicit deps for async effects\n * goodEffect: {\n * deps: [\"userId\"],\n * run: async (facts) => {\n * await someAsyncOp();\n * console.log(facts.userId); // Works because we declared the dep\n * },\n * },\n * }\n * ```\n */\n\nimport { withTracking } from \"./tracking.js\";\nimport type {\n\tEffectsDef,\n\tFacts,\n\tFactsSnapshot,\n\tFactsStore,\n\tSchema,\n} from \"./types.js\";\n\n// ============================================================================\n// Effects Manager\n// ============================================================================\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface EffectsManager<_S extends Schema = Schema> {\n\t/** Run all effects that should trigger based on changes */\n\trunEffects(changedKeys: Set<string>): Promise<void>;\n\t/** Run all effects unconditionally */\n\trunAll(): Promise<void>;\n\t/** Disable an effect */\n\tdisable(id: string): void;\n\t/** Enable an effect */\n\tenable(id: string): void;\n\t/** Check if an effect is enabled */\n\tisEnabled(id: string): boolean;\n\t/** Run all stored cleanup functions (called on system stop/destroy) */\n\tcleanupAll(): void;\n\t/** Register new effect definitions (for dynamic module registration) */\n\tregisterDefinitions(newDefs: EffectsDef<Schema>): void;\n}\n\n/** Internal effect state */\ninterface EffectState {\n\tid: string;\n\tenabled: boolean;\n\thasExplicitDeps: boolean; // true = user-provided deps (fixed), false = auto-tracked (re-track every run)\n\tdependencies: Set<string> | null; // null = not yet tracked\n\tlastSnapshot: FactsSnapshot<Schema> | null;\n\tcleanup: (() => void) | null; // cleanup function returned by last run()\n}\n\n/** Options for creating an effects manager */\nexport interface CreateEffectsOptions<S extends Schema> {\n\tdefinitions: EffectsDef<S>;\n\tfacts: Facts<S>;\n\tstore: FactsStore<S>;\n\t/** Callback when an effect runs */\n\tonRun?: (id: string) => void;\n\t/** Callback when an effect errors */\n\tonError?: (id: string, error: unknown) => void;\n}\n\n/**\n * Create a manager for fire-and-forget side effects that run after facts\n * stabilize.\n *\n * Effects support auto-tracked dependencies (re-tracked on every run to\n * capture conditional reads) or explicit `deps` arrays. Each effect can\n * return a cleanup function that runs before the next execution or on\n * system stop. Errors in effects are isolated and never break the\n * reconciliation loop.\n *\n * @param options - Effect definitions, facts proxy, store, and optional lifecycle callbacks\n * @returns An `EffectsManager` with runEffects/runAll/enable/disable/cleanupAll methods\n */\nexport function createEffectsManager<S extends Schema>(\n\toptions: CreateEffectsOptions<S>,\n): EffectsManager<S> {\n\tconst { definitions, facts, store, onRun, onError } = options;\n\n\t// Internal state for each effect\n\tconst states = new Map<string, EffectState>();\n\n\t// Previous facts snapshot for comparison\n\tlet previousSnapshot: FactsSnapshot<Schema> | null = null;\n\n\t// Track whether cleanupAll has been called (system stopped/destroyed).\n\t// If an async effect resolves after stop, its cleanup is invoked immediately.\n\tlet stopped = false;\n\n\t/** Initialize state for an effect */\n\tfunction initState(id: string): EffectState {\n\t\tconst def = definitions[id];\n\t\tif (!def) {\n\t\t\tthrow new Error(`[Directive] Unknown effect: ${id}`);\n\t\t}\n\n\t\tconst state: EffectState = {\n\t\t\tid,\n\t\t\tenabled: true,\n\t\t\thasExplicitDeps: !!def.deps,\n\t\t\tdependencies: def.deps ? new Set(def.deps as string[]) : null,\n\t\t\tlastSnapshot: null,\n\t\t\tcleanup: null,\n\t\t};\n\n\t\tstates.set(id, state);\n\t\treturn state;\n\t}\n\n\t/** Get or create state for an effect */\n\tfunction getState(id: string): EffectState {\n\t\treturn states.get(id) ?? initState(id);\n\t}\n\n\t/** Create a snapshot of current facts */\n\tfunction createSnapshot(): FactsSnapshot<Schema> {\n\t\treturn facts.$snapshot() as FactsSnapshot<Schema>;\n\t}\n\n\t/** Check if an effect should run based on changed keys */\n\tfunction shouldRun(id: string, changedKeys: Set<string>): boolean {\n\t\tconst state = getState(id);\n\t\tif (!state.enabled) return false;\n\n\t\t// If effect has tracked deps (explicit or auto-tracked), check if any changed\n\t\tif (state.dependencies) {\n\t\t\tfor (const dep of state.dependencies) {\n\t\t\t\tif (changedKeys.has(dep)) return true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\t// No deps yet (first run or auto-tracked with no reads) = run on any change\n\t\treturn true;\n\t}\n\n\t/** Run cleanup for a single effect (safe — catches errors) */\n\tfunction runCleanup(state: EffectState): void {\n\t\tif (state.cleanup) {\n\t\t\ttry {\n\t\t\t\tstate.cleanup();\n\t\t\t} catch (error) {\n\t\t\t\tonError?.(state.id, error);\n\t\t\t\tconsole.error(`[Directive] Effect \"${state.id}\" cleanup threw an error:`, error);\n\t\t\t}\n\t\t\tstate.cleanup = null;\n\t\t}\n\t}\n\n\t/** Store a cleanup function if the effect returned one */\n\tfunction storeCleanup(state: EffectState, result: unknown): void {\n\t\tif (typeof result === \"function\") {\n\t\t\tif (stopped) {\n\t\t\t\t// System already stopped — invoke cleanup immediately so it's not lost\n\t\t\t\ttry {\n\t\t\t\t\t(result as () => void)();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tonError?.(state.id, error);\n\t\t\t\t\tconsole.error(`[Directive] Effect \"${state.id}\" cleanup threw an error:`, error);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstate.cleanup = result as () => void;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Run a single effect */\n\tasync function runEffect(id: string): Promise<void> {\n\t\tconst state = getState(id);\n\t\tconst def = definitions[id];\n\n\t\tif (!state.enabled || !def) return;\n\n\t\t// Run previous cleanup before re-running\n\t\trunCleanup(state);\n\n\t\tonRun?.(id);\n\n\t\ttry {\n\t\t\tif (!state.hasExplicitDeps) {\n\t\t\t\t// Auto-tracked: re-track dependencies on EVERY run so conditional\n\t\t\t\t// reads are picked up (fixes frozen deps after first run)\n\t\t\t\tlet trackedDeps: Set<string> | null = null;\n\t\t\t\tlet effectPromise: unknown;\n\t\t\t\tconst trackingResult = withTracking(() => {\n\t\t\t\t\tstore.batch(() => {\n\t\t\t\t\t\teffectPromise = def.run(facts, previousSnapshot as FactsSnapshot<S> | null);\n\t\t\t\t\t});\n\t\t\t\t\treturn effectPromise;\n\t\t\t\t});\n\t\t\t\ttrackedDeps = trackingResult.deps;\n\n\t\t\t\t// If the effect is async, wait for it and capture cleanup\n\t\t\t\tlet result = trackingResult.value;\n\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\tresult = await result;\n\t\t\t\t}\n\t\t\t\tstoreCleanup(state, result);\n\n\t\t\t\t// Update tracked dependencies (always replace to catch new conditional reads)\n\t\t\t\tstate.dependencies = trackedDeps.size > 0 ? trackedDeps : null;\n\t\t\t} else {\n\t\t\t\t// Has explicit deps, batch synchronous mutations and run\n\t\t\t\tlet effectPromise: unknown;\n\t\t\t\tstore.batch(() => {\n\t\t\t\t\teffectPromise = def.run(facts, previousSnapshot as FactsSnapshot<S> | null);\n\t\t\t\t});\n\t\t\t\tif (effectPromise instanceof Promise) {\n\t\t\t\t\tconst result = await effectPromise;\n\t\t\t\t\tstoreCleanup(state, result);\n\t\t\t\t} else {\n\t\t\t\t\tstoreCleanup(state, effectPromise);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Effects are fire-and-forget - errors are reported but don't propagate\n\t\t\tonError?.(id, error);\n\t\t\tconsole.error(`[Directive] Effect \"${id}\" threw an error:`, error);\n\t\t}\n\t}\n\n\t// Initialize all effect states\n\tfor (const id of Object.keys(definitions)) {\n\t\tinitState(id);\n\t}\n\n\tconst manager: EffectsManager<S> = {\n\t\tasync runEffects(changedKeys: Set<string>): Promise<void> {\n\t\t\tconst effectsToRun: string[] = [];\n\n\t\t\tfor (const id of Object.keys(definitions)) {\n\t\t\t\tif (shouldRun(id, changedKeys)) {\n\t\t\t\t\teffectsToRun.push(id);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Run effects in parallel (they're independent)\n\t\t\tawait Promise.all(effectsToRun.map(runEffect));\n\n\t\t\t// Update previous snapshot\n\t\t\tpreviousSnapshot = createSnapshot();\n\t\t},\n\n\t\tasync runAll(): Promise<void> {\n\t\t\tconst effectIds = Object.keys(definitions);\n\t\t\tawait Promise.all(\n\t\t\t\teffectIds.map((id) => {\n\t\t\t\t\tconst state = getState(id);\n\t\t\t\t\tif (state.enabled) {\n\t\t\t\t\t\treturn runEffect(id);\n\t\t\t\t\t}\n\t\t\t\t\treturn Promise.resolve();\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\t// Update previous snapshot\n\t\t\tpreviousSnapshot = createSnapshot();\n\t\t},\n\n\t\tdisable(id: string): void {\n\t\t\tconst state = getState(id);\n\t\t\tstate.enabled = false;\n\t\t},\n\n\t\tenable(id: string): void {\n\t\t\tconst state = getState(id);\n\t\t\tstate.enabled = true;\n\t\t},\n\n\t\tisEnabled(id: string): boolean {\n\t\t\treturn getState(id).enabled;\n\t\t},\n\n\t\tcleanupAll(): void {\n\t\t\tstopped = true;\n\t\t\tfor (const state of states.values()) {\n\t\t\t\trunCleanup(state);\n\t\t\t}\n\t\t},\n\n\t\tregisterDefinitions(newDefs: EffectsDef<S>): void {\n\t\t\tfor (const [key, def] of Object.entries(newDefs)) {\n\t\t\t\t(definitions as Record<string, unknown>)[key] = def;\n\t\t\t\tinitState(key);\n\t\t\t}\n\t\t},\n\t};\n\n\treturn manager;\n}\n","/**\n * Error Boundaries - Configurable error handling and recovery\n *\n * Features:\n * - Catch errors in constraints/resolvers/effects/derivations\n * - Configurable recovery strategies (skip, retry, retry-later, disable, throw)\n * - Circuit breaker pattern for automatic failure protection\n * - Error reporting to plugins\n */\n\nimport {\n\tDirectiveError,\n\ttype ErrorBoundaryConfig,\n\ttype ErrorSource,\n\ttype RecoveryStrategy,\n\ttype RetryLaterConfig,\n} from \"./types.js\";\n\n// ============================================================================\n// Retry-Later Queue\n// ============================================================================\n\n/**\n * Pending retry entry.\n */\nexport interface PendingRetry {\n\tsource: ErrorSource;\n\tsourceId: string;\n\tcontext: unknown;\n\tattempt: number;\n\tnextRetryTime: number;\n\tcallback?: () => void;\n}\n\n/**\n * Create a manager for deferred retry scheduling with exponential backoff.\n *\n * Retries are stored in a Map keyed by source ID. Each retry tracks its\n * attempt number and next retry time. When `processDueRetries()` is called\n * (typically during reconciliation), entries whose time has elapsed are\n * returned and removed from the queue.\n *\n * @param config - Backoff configuration: `delayMs`, `maxRetries`, `backoffMultiplier`, `maxDelayMs`\n * @returns A manager with `scheduleRetry`, `getPendingRetries`, `processDueRetries`, `cancelRetry`, and `clearAll` methods\n */\nexport function createRetryLaterManager(config: RetryLaterConfig = {}): {\n\t/** Schedule a retry */\n\tscheduleRetry: (\n\t\tsource: ErrorSource,\n\t\tsourceId: string,\n\t\tcontext: unknown,\n\t\tattempt: number,\n\t\tcallback?: () => void,\n\t) => PendingRetry | null;\n\t/** Get pending retries */\n\tgetPendingRetries: () => PendingRetry[];\n\t/** Process due retries */\n\tprocessDueRetries: () => PendingRetry[];\n\t/** Cancel a retry */\n\tcancelRetry: (sourceId: string) => void;\n\t/** Clear all pending retries */\n\tclearAll: () => void;\n} {\n\tconst {\n\t\tdelayMs = 1000,\n\t\tmaxRetries = 3,\n\t\tbackoffMultiplier = 2,\n\t\tmaxDelayMs = 30000,\n\t} = config;\n\n\tconst pendingRetries: Map<string, PendingRetry> = new Map();\n\n\tfunction calculateDelay(attempt: number): number {\n\t\tconst delay = delayMs * Math.pow(backoffMultiplier, attempt - 1);\n\t\treturn Math.min(delay, maxDelayMs);\n\t}\n\n\treturn {\n\t\tscheduleRetry(\n\t\t\tsource: ErrorSource,\n\t\t\tsourceId: string,\n\t\t\tcontext: unknown,\n\t\t\tattempt: number,\n\t\t\tcallback?: () => void,\n\t\t): PendingRetry | null {\n\t\t\t// Check if max retries exceeded\n\t\t\tif (attempt > maxRetries) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst delay = calculateDelay(attempt);\n\t\t\tconst entry: PendingRetry = {\n\t\t\t\tsource,\n\t\t\t\tsourceId,\n\t\t\t\tcontext,\n\t\t\t\tattempt,\n\t\t\t\tnextRetryTime: Date.now() + delay,\n\t\t\t\tcallback,\n\t\t\t};\n\n\t\t\tpendingRetries.set(sourceId, entry);\n\t\t\treturn entry;\n\t\t},\n\n\t\tgetPendingRetries(): PendingRetry[] {\n\t\t\treturn Array.from(pendingRetries.values());\n\t\t},\n\n\t\tprocessDueRetries(): PendingRetry[] {\n\t\t\tconst now = Date.now();\n\t\t\tconst dueRetries: PendingRetry[] = [];\n\n\t\t\tfor (const [sourceId, entry] of pendingRetries) {\n\t\t\t\tif (entry.nextRetryTime <= now) {\n\t\t\t\t\tdueRetries.push(entry);\n\t\t\t\t\tpendingRetries.delete(sourceId);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn dueRetries;\n\t\t},\n\n\t\tcancelRetry(sourceId: string): void {\n\t\t\tpendingRetries.delete(sourceId);\n\t\t},\n\n\t\tclearAll(): void {\n\t\t\tpendingRetries.clear();\n\t\t},\n\t};\n}\n\n// ============================================================================\n// Error Boundary Manager\n// ============================================================================\n\nexport interface ErrorBoundaryManager {\n\t/** Handle an error from a specific source */\n\thandleError(source: ErrorSource, sourceId: string, error: unknown, context?: unknown): RecoveryStrategy;\n\t/** Get the last error */\n\tgetLastError(): DirectiveError | null;\n\t/** Get all errors */\n\tgetAllErrors(): DirectiveError[];\n\t/** Clear all errors */\n\tclearErrors(): void;\n\t/** Get retry-later manager */\n\tgetRetryLaterManager(): ReturnType<typeof createRetryLaterManager>;\n\t/** Process due retries (call periodically or on reconcile) */\n\tprocessDueRetries(): PendingRetry[];\n\t/** Clear retry attempts for a source ID (call on success) */\n\tclearRetryAttempts(sourceId: string): void;\n}\n\n/** Options for creating an error boundary manager */\nexport interface CreateErrorBoundaryOptions {\n\tconfig?: ErrorBoundaryConfig;\n\t/** Callback when an error occurs */\n\tonError?: (error: DirectiveError) => void;\n\t/** Callback when recovery is attempted */\n\tonRecovery?: (error: DirectiveError, strategy: RecoveryStrategy) => void;\n}\n\n/** Default recovery strategies by source */\nconst DEFAULT_STRATEGIES: Record<ErrorSource, RecoveryStrategy> = {\n\tconstraint: \"skip\",\n\tresolver: \"skip\",\n\teffect: \"skip\",\n\tderivation: \"skip\",\n\tsystem: \"throw\",\n};\n\n/**\n * Create a manager that handles errors from constraints, resolvers, effects,\n * and derivations with configurable per-source recovery strategies.\n *\n * Supported strategies: `\"skip\"` (ignore), `\"retry\"` (immediate),\n * `\"retry-later\"` (deferred with backoff), `\"disable\"` (turn off source),\n * and `\"throw\"` (re-throw). Recent errors are kept in a ring buffer\n * (last 100) for inspection. The retry-later strategy delegates to an\n * internal {@link createRetryLaterManager}.\n *\n * @param options - Error boundary configuration, plus `onError` and `onRecovery` callbacks for plugin integration\n * @returns An `ErrorBoundaryManager` with handleError/getLastError/getAllErrors/clearErrors/processDueRetries methods\n *\n * @example\n * ```ts\n * const boundary = createErrorBoundaryManager({\n * config: {\n * onResolverError: \"retry-later\",\n * onEffectError: \"skip\",\n * retryLater: { maxRetries: 5, delayMs: 500 },\n * },\n * onError: (err) => console.error(err.source, err.message),\n * });\n *\n * const strategy = boundary.handleError(\"resolver\", \"fetchUser\", new Error(\"timeout\"));\n * // strategy === \"retry-later\"\n * ```\n */\nexport function createErrorBoundaryManager(\n\toptions: CreateErrorBoundaryOptions = {},\n): ErrorBoundaryManager {\n\tconst { config = {}, onError, onRecovery } = options;\n\n\t// Store errors for inspection\n\tconst errors: DirectiveError[] = [];\n\tconst maxErrors = 100; // Keep last 100 errors\n\n\t// Retry-later manager\n\tconst retryLaterManager = createRetryLaterManager(config.retryLater);\n\n\t// Track retry attempts per source ID\n\tconst retryAttempts = new Map<string, number>();\n\n\t/** Convert unknown error to DirectiveError */\n\tfunction toDirectiveError(\n\t\tsource: ErrorSource,\n\t\tsourceId: string,\n\t\terror: unknown,\n\t\tcontext?: unknown,\n\t): DirectiveError {\n\t\tif (error instanceof DirectiveError) {\n\t\t\treturn error;\n\t\t}\n\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst recoverable = source !== \"system\";\n\n\t\treturn new DirectiveError(message, source, sourceId, context, recoverable);\n\t}\n\n\t/** Get recovery strategy for a source */\n\tfunction getStrategy(source: ErrorSource, sourceId: string, error: Error): RecoveryStrategy {\n\t\t// Get configured handler\n\t\tconst handler = (() => {\n\t\t\tswitch (source) {\n\t\t\t\tcase \"constraint\":\n\t\t\t\t\treturn config.onConstraintError;\n\t\t\t\tcase \"resolver\":\n\t\t\t\t\treturn config.onResolverError;\n\t\t\t\tcase \"effect\":\n\t\t\t\t\treturn config.onEffectError;\n\t\t\t\tcase \"derivation\":\n\t\t\t\t\treturn config.onDerivationError;\n\t\t\t\tdefault:\n\t\t\t\t\treturn undefined;\n\t\t\t}\n\t\t})();\n\n\t\t// If handler is a function, call it and return skip\n\t\tif (typeof handler === \"function\") {\n\t\t\ttry {\n\t\t\t\thandler(error, sourceId);\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(\"[Directive] Error in error handler callback:\", e);\n\t\t\t}\n\t\t\treturn \"skip\";\n\t\t}\n\n\t\t// If handler is a strategy string, return it\n\t\tif (typeof handler === \"string\") {\n\t\t\treturn handler;\n\t\t}\n\n\t\t// Return default strategy\n\t\treturn DEFAULT_STRATEGIES[source];\n\t}\n\n\tconst manager: ErrorBoundaryManager = {\n\t\thandleError(\n\t\t\tsource: ErrorSource,\n\t\t\tsourceId: string,\n\t\t\terror: unknown,\n\t\t\tcontext?: unknown,\n\t\t): RecoveryStrategy {\n\t\t\tconst directiveError = toDirectiveError(source, sourceId, error, context);\n\n\t\t\t// Store error\n\t\t\terrors.push(directiveError);\n\t\t\tif (errors.length > maxErrors) {\n\t\t\t\terrors.shift();\n\t\t\t}\n\n\t\t\t// Notify callbacks (wrapped to prevent bypassing recovery)\n\t\t\ttry { onError?.(directiveError); } catch (e) { console.error(\"[Directive] Error in onError callback:\", e); }\n\t\t\ttry { config.onError?.(directiveError); } catch (e) { console.error(\"[Directive] Error in config.onError callback:\", e); }\n\n\t\t\t// Get recovery strategy\n\t\t\tlet strategy = getStrategy(\n\t\t\t\tsource,\n\t\t\t\tsourceId,\n\t\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t\t);\n\n\t\t\t// Handle retry-later strategy\n\t\t\tif (strategy === \"retry-later\") {\n\t\t\t\tconst attempt = (retryAttempts.get(sourceId) ?? 0) + 1;\n\t\t\t\tretryAttempts.set(sourceId, attempt);\n\n\t\t\t\tconst scheduled = retryLaterManager.scheduleRetry(\n\t\t\t\t\tsource,\n\t\t\t\t\tsourceId,\n\t\t\t\t\tcontext,\n\t\t\t\t\tattempt,\n\t\t\t\t);\n\n\t\t\t\tif (!scheduled) {\n\t\t\t\t\t// Max retries exceeded, fall back to skip\n\t\t\t\t\tstrategy = \"skip\";\n\t\t\t\t\tretryAttempts.delete(sourceId);\n\n\t\t\t\t\tif (typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\") {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[Directive] ${source} \"${sourceId}\" exceeded max retry-later attempts. Skipping.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Notify recovery callback\n\t\t\ttry { onRecovery?.(directiveError, strategy); } catch (e) { console.error(\"[Directive] Error in onRecovery callback:\", e); }\n\n\t\t\t// If strategy is throw, re-throw the error\n\t\t\tif (strategy === \"throw\") {\n\t\t\t\tthrow directiveError;\n\t\t\t}\n\n\t\t\treturn strategy;\n\t\t},\n\n\t\tgetLastError(): DirectiveError | null {\n\t\t\treturn errors[errors.length - 1] ?? null;\n\t\t},\n\n\t\tgetAllErrors(): DirectiveError[] {\n\t\t\treturn [...errors];\n\t\t},\n\n\t\tclearErrors(): void {\n\t\t\terrors.length = 0;\n\t\t},\n\n\t\tgetRetryLaterManager() {\n\t\t\treturn retryLaterManager;\n\t\t},\n\n\t\tprocessDueRetries(): PendingRetry[] {\n\t\t\treturn retryLaterManager.processDueRetries();\n\t\t},\n\n\t\tclearRetryAttempts(sourceId: string): void {\n\t\t\tretryAttempts.delete(sourceId);\n\t\t\tretryLaterManager.cancelRetry(sourceId);\n\t\t},\n\t};\n\n\treturn manager;\n}\n","/**\n * Plugin Architecture - Extensible middleware for Directive\n *\n * Features:\n * - Lifecycle hooks for all engine events\n * - Multiple plugins can be composed\n * - Plugins execute in registration order\n */\n\nimport type {\n\tFactChange,\n\tFactsSnapshot,\n\tPlugin,\n\tReconcileResult,\n\tRecoveryStrategy,\n\tRequirementWithId,\n\tSchema,\n\tSnapshot,\n\tSystem,\n} from \"./types.js\";\nimport { DirectiveError } from \"./types.js\";\n\n// ============================================================================\n// Plugin Manager\n// ============================================================================\n\n// Note: PluginManager uses Schema (flat) internally because the engine works with flat schemas.\n// The public API uses ModuleSchema (consolidated), and the conversion happens in createSystem.\n// biome-ignore lint/suspicious/noExplicitAny: Internal type - plugins are schema-agnostic at runtime\nexport interface PluginManager<_S extends Schema = any> {\n\t/** Register a plugin */\n\t// biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n\tregister(plugin: Plugin<any>): void;\n\t/** Unregister a plugin by name */\n\tunregister(name: string): void;\n\t/** Get all registered plugins */\n\t// biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n\tgetPlugins(): Plugin<any>[];\n\n\t// Lifecycle hooks\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies between internal/public API\n\temitInit(system: System<any>): Promise<void>;\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies between internal/public API\n\temitStart(system: System<any>): void;\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies between internal/public API\n\temitStop(system: System<any>): void;\n\t// biome-ignore lint/suspicious/noExplicitAny: System type varies between internal/public API\n\temitDestroy(system: System<any>): void;\n\n\t// Fact hooks\n\temitFactSet(key: string, value: unknown, prev: unknown): void;\n\temitFactDelete(key: string, prev: unknown): void;\n\temitFactsBatch(changes: FactChange[]): void;\n\n\t// Derivation hooks\n\temitDerivationCompute(id: string, value: unknown, deps: string[]): void;\n\temitDerivationInvalidate(id: string): void;\n\n\t// Reconciliation hooks\n\t// biome-ignore lint/suspicious/noExplicitAny: Schema type varies\n\temitReconcileStart(snapshot: FactsSnapshot<any>): void;\n\temitReconcileEnd(result: ReconcileResult): void;\n\n\t// Constraint hooks\n\temitConstraintEvaluate(id: string, active: boolean): void;\n\temitConstraintError(id: string, error: unknown): void;\n\n\t// Requirement hooks\n\temitRequirementCreated(req: RequirementWithId): void;\n\temitRequirementMet(req: RequirementWithId, byResolver: string): void;\n\temitRequirementCanceled(req: RequirementWithId): void;\n\n\t// Resolver hooks\n\temitResolverStart(resolver: string, req: RequirementWithId): void;\n\temitResolverComplete(resolver: string, req: RequirementWithId, duration: number): void;\n\temitResolverError(resolver: string, req: RequirementWithId, error: unknown): void;\n\temitResolverRetry(resolver: string, req: RequirementWithId, attempt: number): void;\n\temitResolverCancel(resolver: string, req: RequirementWithId): void;\n\n\t// Effect hooks\n\temitEffectRun(id: string): void;\n\temitEffectError(id: string, error: unknown): void;\n\n\t// Time-travel hooks\n\temitSnapshot(snapshot: Snapshot): void;\n\temitTimeTravel(from: number, to: number): void;\n\n\t// Error boundary hooks\n\temitError(error: DirectiveError): void;\n\temitErrorRecovery(error: DirectiveError, strategy: RecoveryStrategy): void;\n}\n\n/**\n * Create a manager that broadcasts lifecycle events to registered plugins.\n *\n * Plugins are called in registration order. All hook invocations are\n * wrapped in try-catch so a misbehaving plugin never breaks the engine.\n * Duplicate plugin names are detected and the older registration is\n * replaced with a warning.\n *\n * @returns A `PluginManager` with register/unregister/getPlugins and emit* methods for every lifecycle event\n */\n// biome-ignore lint/suspicious/noExplicitAny: Internal - schema type varies\nexport function createPluginManager<S extends Schema = any>(): PluginManager<S> {\n\t// biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n\tconst plugins: Plugin<any>[] = [];\n\n\t/** Safe call - wraps plugin hook calls to prevent errors from breaking the system */\n\tfunction safeCall<T>(fn: (() => T) | undefined): T | undefined {\n\t\tif (!fn) return undefined;\n\t\ttry {\n\t\t\treturn fn();\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[Directive] Plugin error:\", error);\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/** Safe async call */\n\tasync function safeCallAsync<T>(fn: (() => Promise<T>) | undefined): Promise<T | undefined> {\n\t\tif (!fn) return undefined;\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[Directive] Plugin error:\", error);\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tconst manager: PluginManager<S> = {\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n\t\tregister(plugin: Plugin<any>): void {\n\t\t\t// Check for duplicate names\n\t\t\tif (plugins.some((p) => p.name === plugin.name)) {\n\t\t\t\tconsole.warn(`[Directive] Plugin \"${plugin.name}\" is already registered, replacing...`);\n\t\t\t\tthis.unregister(plugin.name);\n\t\t\t}\n\t\t\tplugins.push(plugin);\n\t\t},\n\n\t\tunregister(name: string): void {\n\t\t\tconst index = plugins.findIndex((p) => p.name === name);\n\t\t\tif (index !== -1) {\n\t\t\t\tplugins.splice(index, 1);\n\t\t\t}\n\t\t},\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n\t\tgetPlugins(): Plugin<any>[] {\n\t\t\treturn [...plugins];\n\t\t},\n\n\t\t// Lifecycle hooks\n\t\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\t\tasync emitInit(system: System<any>): Promise<void> {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tawait safeCallAsync(() => plugin.onInit?.(system) as Promise<void>);\n\t\t\t}\n\t\t},\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\t\temitStart(system: System<any>): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onStart?.(system));\n\t\t\t}\n\t\t},\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\t\temitStop(system: System<any>): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onStop?.(system));\n\t\t\t}\n\t\t},\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: System type varies\n\t\temitDestroy(system: System<any>): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onDestroy?.(system));\n\t\t\t}\n\t\t},\n\n\t\t// Fact hooks\n\t\temitFactSet(key: string, value: unknown, prev: unknown): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onFactSet?.(key, value, prev));\n\t\t\t}\n\t\t},\n\n\t\temitFactDelete(key: string, prev: unknown): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onFactDelete?.(key, prev));\n\t\t\t}\n\t\t},\n\n\t\temitFactsBatch(changes: FactChange[]): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onFactsBatch?.(changes));\n\t\t\t}\n\t\t},\n\n\t\t// Derivation hooks\n\t\temitDerivationCompute(id: string, value: unknown, deps: string[]): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onDerivationCompute?.(id, value, deps));\n\t\t\t}\n\t\t},\n\n\t\temitDerivationInvalidate(id: string): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onDerivationInvalidate?.(id));\n\t\t\t}\n\t\t},\n\n\t\t// Reconciliation hooks\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Schema type varies\n\t\temitReconcileStart(snapshot: FactsSnapshot<any>): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onReconcileStart?.(snapshot));\n\t\t\t}\n\t\t},\n\n\t\temitReconcileEnd(result: ReconcileResult): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onReconcileEnd?.(result));\n\t\t\t}\n\t\t},\n\n\t\t// Constraint hooks\n\t\temitConstraintEvaluate(id: string, active: boolean): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onConstraintEvaluate?.(id, active));\n\t\t\t}\n\t\t},\n\n\t\temitConstraintError(id: string, error: unknown): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onConstraintError?.(id, error));\n\t\t\t}\n\t\t},\n\n\t\t// Requirement hooks\n\t\temitRequirementCreated(req: RequirementWithId): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onRequirementCreated?.(req));\n\t\t\t}\n\t\t},\n\n\t\temitRequirementMet(req: RequirementWithId, byResolver: string): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onRequirementMet?.(req, byResolver));\n\t\t\t}\n\t\t},\n\n\t\temitRequirementCanceled(req: RequirementWithId): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onRequirementCanceled?.(req));\n\t\t\t}\n\t\t},\n\n\t\t// Resolver hooks\n\t\temitResolverStart(resolver: string, req: RequirementWithId): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onResolverStart?.(resolver, req));\n\t\t\t}\n\t\t},\n\n\t\temitResolverComplete(resolver: string, req: RequirementWithId, duration: number): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onResolverComplete?.(resolver, req, duration));\n\t\t\t}\n\t\t},\n\n\t\temitResolverError(resolver: string, req: RequirementWithId, error: unknown): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onResolverError?.(resolver, req, error));\n\t\t\t}\n\t\t},\n\n\t\temitResolverRetry(resolver: string, req: RequirementWithId, attempt: number): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onResolverRetry?.(resolver, req, attempt));\n\t\t\t}\n\t\t},\n\n\t\temitResolverCancel(resolver: string, req: RequirementWithId): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onResolverCancel?.(resolver, req));\n\t\t\t}\n\t\t},\n\n\t\t// Effect hooks\n\t\temitEffectRun(id: string): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onEffectRun?.(id));\n\t\t\t}\n\t\t},\n\n\t\temitEffectError(id: string, error: unknown): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onEffectError?.(id, error));\n\t\t\t}\n\t\t},\n\n\t\t// Time-travel hooks\n\t\temitSnapshot(snapshot: Snapshot): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onSnapshot?.(snapshot));\n\t\t\t}\n\t\t},\n\n\t\temitTimeTravel(from: number, to: number): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onTimeTravel?.(from, to));\n\t\t\t}\n\t\t},\n\n\t\t// Error boundary hooks\n\t\temitError(error: DirectiveError): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onError?.(error));\n\t\t\t}\n\t\t},\n\n\t\temitErrorRecovery(error: DirectiveError, strategy: RecoveryStrategy): void {\n\t\t\tfor (const plugin of plugins) {\n\t\t\t\tsafeCall(() => plugin.onErrorRecovery?.(error, strategy));\n\t\t\t}\n\t\t},\n\t};\n\n\treturn manager;\n}\n","/**\n * Resolvers - Capability-based handlers for requirements\n *\n * Features:\n * - Capability matching (handles predicate)\n * - Custom dedupe keys\n * - Retry policies with exponential backoff\n * - Batched resolution for similar requirements\n * - Cancellation via AbortController\n */\n\nimport type {\n\tBatchConfig,\n\tBatchResolveResults,\n\tFacts,\n\tFactsSnapshot,\n\tFactsStore,\n\tRequirement,\n\tRequirementWithId,\n\tResolverContext,\n\tResolversDef,\n\tResolverStatus,\n\tRetryPolicy,\n\tSchema,\n} from \"./types.js\";\nimport { withTimeout } from \"../utils/utils.js\";\n\n// ============================================================================\n// Resolvers Manager\n// ============================================================================\n\n/** Inflight resolver info */\nexport interface InflightInfo {\n\tid: string;\n\tresolverId: string;\n\tstartedAt: number;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ResolversManager<_S extends Schema> {\n\t/** Start resolving a requirement */\n\tresolve(req: RequirementWithId): void;\n\t/** Cancel a resolver by requirement ID */\n\tcancel(requirementId: string): void;\n\t/** Cancel all inflight resolvers */\n\tcancelAll(): void;\n\t/** Get status of a resolver by requirement ID */\n\tgetStatus(requirementId: string): ResolverStatus;\n\t/** Get all inflight requirement IDs */\n\tgetInflight(): string[];\n\t/** Get full info for all inflight resolvers */\n\tgetInflightInfo(): InflightInfo[];\n\t/** Check if a requirement is being resolved */\n\tisResolving(requirementId: string): boolean;\n\t/** Process batched requirements (called periodically) */\n\tprocessBatches(): void;\n\t/** Register new resolver definitions (for dynamic module registration) */\n\tregisterDefinitions(newDefs: ResolversDef<Schema>): void;\n}\n\n/** Internal resolver state */\ninterface ResolverState {\n\trequirementId: string;\n\tresolverId: string;\n\tcontroller: AbortController;\n\tstartedAt: number;\n\tattempt: number;\n\tstatus: ResolverStatus;\n\t/** Original requirement for proper cancel callback */\n\toriginalRequirement: RequirementWithId;\n}\n\n/** Batch state for batched resolvers */\ninterface BatchState {\n\tresolverId: string;\n\trequirements: RequirementWithId[];\n\ttimer: ReturnType<typeof setTimeout> | null;\n}\n\n/** Options for creating a resolvers manager */\nexport interface CreateResolversOptions<S extends Schema> {\n\tdefinitions: ResolversDef<S>;\n\tfacts: Facts<S>;\n\tstore: FactsStore<S>;\n\t/** Callback when a resolver starts */\n\tonStart?: (resolver: string, req: RequirementWithId) => void;\n\t/** Callback when a resolver completes */\n\tonComplete?: (resolver: string, req: RequirementWithId, duration: number) => void;\n\t/** Callback when a resolver errors */\n\tonError?: (resolver: string, req: RequirementWithId, error: unknown) => void;\n\t/** Callback when a resolver retries */\n\tonRetry?: (resolver: string, req: RequirementWithId, attempt: number) => void;\n\t/** Callback when a resolver is canceled */\n\tonCancel?: (resolver: string, req: RequirementWithId) => void;\n\t/** Callback when resolution cycle completes (for reconciliation) */\n\tonResolutionComplete?: () => void;\n}\n\n/** Default retry policy */\nconst DEFAULT_RETRY: RetryPolicy = {\n\tattempts: 1,\n\tbackoff: \"none\",\n\tinitialDelay: 100,\n\tmaxDelay: 30000,\n};\n\n/** Default batch config */\nconst DEFAULT_BATCH: BatchConfig = {\n\tenabled: false,\n\twindowMs: 50,\n};\n\n/**\n * Calculate delay for a retry attempt.\n */\nfunction calculateDelay(policy: RetryPolicy, attempt: number): number {\n\tconst { backoff, initialDelay = 100, maxDelay = 30000 } = policy;\n\n\tlet delay: number;\n\n\tswitch (backoff) {\n\t\tcase \"none\":\n\t\t\tdelay = initialDelay;\n\t\t\tbreak;\n\t\tcase \"linear\":\n\t\t\tdelay = initialDelay * attempt;\n\t\t\tbreak;\n\t\tcase \"exponential\":\n\t\t\tdelay = initialDelay * Math.pow(2, attempt - 1);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tdelay = initialDelay;\n\t}\n\n\t// Ensure delay is at least 1ms to prevent busy loops\n\treturn Math.max(1, Math.min(delay, maxDelay));\n}\n\n/**\n * Create a manager that fulfills requirements by matching them to resolver\n * handlers.\n *\n * Resolvers are matched by requirement type (string or predicate). Each\n * resolution runs with an `AbortController` for cancellation, configurable\n * retry policies (none/linear/exponential backoff), and optional batching\n * for grouping similar requirements. Duplicate in-flight requirements are\n * automatically deduplicated.\n *\n * @param options - Resolver definitions, facts proxy, store, and lifecycle callbacks (onStart/onComplete/onError/onRetry/onCancel/onResolutionComplete)\n * @returns A `ResolversManager` with resolve/cancel/cancelAll/getStatus/processBatches methods\n */\nexport function createResolversManager<S extends Schema>(\n\toptions: CreateResolversOptions<S>,\n): ResolversManager<S> {\n\tconst {\n\t\tdefinitions,\n\t\tfacts,\n\t\tstore,\n\t\tonStart,\n\t\tonComplete,\n\t\tonError,\n\t\tonRetry,\n\t\tonCancel,\n\t\tonResolutionComplete,\n\t} = options;\n\n\t// Validate resolver definitions\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tfor (const [id, def] of Object.entries(definitions)) {\n\t\t\tif (!def.resolve && !def.resolveBatch) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Resolver \"${id}\" must define either resolve() or resolveBatch(). ` +\n\t\t\t\t\t\t`Add one of these methods to handle requirements.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (def.batch?.enabled && !def.resolveBatch) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Resolver \"${id}\" has batch.enabled=true but no resolveBatch() method. ` +\n\t\t\t\t\t\t`Add resolveBatch() to handle batched requirements.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Active resolver states by requirement ID\n\tconst inflight = new Map<string, ResolverState>();\n\n\t// Completed/failed statuses (kept for inspection) - LRU cleanup\n\tconst statuses = new Map<string, ResolverStatus>();\n\tconst MAX_STATUSES = 1000; // Limit to prevent memory leak\n\n\t// Batch states by resolver ID\n\tconst batches = new Map<string, BatchState>();\n\n\t// Resolver index by requirement type for O(1) lookup (populated lazily)\n\t// Capped to prevent unbounded growth with dynamic requirement types (e.g., FETCH_USER_${id})\n\tconst resolversByType = new Map<string, string[]>();\n\tconst MAX_RESOLVER_CACHE = 1000;\n\n\t/** Cleanup old statuses to prevent memory leak */\n\tfunction cleanupStatuses(): void {\n\t\tif (statuses.size > MAX_STATUSES) {\n\t\t\t// Remove oldest entries (first inserted = first in iteration)\n\t\t\tconst entriesToRemove = statuses.size - MAX_STATUSES;\n\t\t\tconst iterator = statuses.keys();\n\t\t\tfor (let i = 0; i < entriesToRemove; i++) {\n\t\t\t\tconst key = iterator.next().value;\n\t\t\t\tif (key) statuses.delete(key);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Type guard for resolver with string `requirement` property */\n\tfunction hasStringRequirement(\n\t\tdef: unknown,\n\t): def is { requirement: string } {\n\t\treturn (\n\t\t\ttypeof def === \"object\" &&\n\t\t\tdef !== null &&\n\t\t\t\"requirement\" in def &&\n\t\t\ttypeof (def as { requirement: unknown }).requirement === \"string\"\n\t\t);\n\t}\n\n\t/** Type guard for resolver with function `requirement` property */\n\tfunction hasFunctionRequirement(\n\t\tdef: unknown,\n\t): def is { requirement: (req: Requirement) => boolean } {\n\t\treturn (\n\t\t\ttypeof def === \"object\" &&\n\t\t\tdef !== null &&\n\t\t\t\"requirement\" in def &&\n\t\t\ttypeof (def as { requirement: unknown }).requirement === \"function\"\n\t\t);\n\t}\n\n\t/**\n\t * Check if a resolver handles a requirement.\n\t * Supports:\n\t * - `requirement: \"TYPE\"` - string matching\n\t * - `requirement: (req) => req is T` - function type guard\n\t */\n\tfunction resolverHandles(def: ResolversDef<S>[string], req: Requirement): boolean {\n\t\t// Check string-based `requirement`\n\t\tif (hasStringRequirement(def)) {\n\t\t\treturn req.type === def.requirement;\n\t\t}\n\n\t\t// Check function-based `requirement` (type guard)\n\t\tif (hasFunctionRequirement(def)) {\n\t\t\treturn def.requirement(req);\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/** Find a resolver that handles a requirement */\n\tfunction findResolver(req: Requirement): string | null {\n\t\t// Check cache first for this requirement type\n\t\tconst reqType = req.type;\n\t\tconst cached = resolversByType.get(reqType);\n\t\tif (cached) {\n\t\t\t// Try cached resolvers first\n\t\t\tfor (const id of cached) {\n\t\t\t\tconst def = definitions[id];\n\t\t\t\tif (def && resolverHandles(def, req)) {\n\t\t\t\t\treturn id;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Fallback to full search and cache the result\n\t\tfor (const [id, def] of Object.entries(definitions)) {\n\t\t\tif (resolverHandles(def, req)) {\n\t\t\t\t// Cache this resolver for this type (with size cap)\n\t\t\t\tif (!resolversByType.has(reqType)) {\n\t\t\t\t\t// Evict oldest entry if cache is full\n\t\t\t\t\tif (resolversByType.size >= MAX_RESOLVER_CACHE) {\n\t\t\t\t\t\tconst oldest = resolversByType.keys().next().value;\n\t\t\t\t\t\tif (oldest !== undefined) resolversByType.delete(oldest);\n\t\t\t\t\t}\n\t\t\t\t\tresolversByType.set(reqType, []);\n\t\t\t\t}\n\t\t\t\tconst typeResolvers = resolversByType.get(reqType)!;\n\t\t\t\tif (!typeResolvers.includes(id)) {\n\t\t\t\t\ttypeResolvers.push(id);\n\t\t\t\t}\n\t\t\t\treturn id;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** Create resolver context */\n\tfunction createContext(signal: AbortSignal): ResolverContext<S> {\n\t\treturn {\n\t\t\tfacts,\n\t\t\tsignal,\n\t\t\tsnapshot: () => facts.$snapshot() as FactsSnapshot<S>,\n\t\t};\n\t}\n\n\t/** Execute a single requirement resolution with retry */\n\tasync function executeResolve(\n\t\tresolverId: string,\n\t\treq: RequirementWithId,\n\t\tcontroller: AbortController,\n\t): Promise<void> {\n\t\tconst def = definitions[resolverId];\n\t\tif (!def) return;\n\t\tconst retryPolicy = { ...DEFAULT_RETRY, ...def.retry };\n\t\tlet lastError: Error | null = null;\n\n\t\tfor (let attempt = 1; attempt <= retryPolicy.attempts; attempt++) {\n\t\t\t// Check if canceled\n\t\t\tif (controller.signal.aborted) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tconst state = inflight.get(req.id);\n\t\t\tif (state) {\n\t\t\t\tstate.attempt = attempt;\n\t\t\t\tstate.status = {\n\t\t\t\t\tstate: \"running\",\n\t\t\t\t\trequirementId: req.id,\n\t\t\t\t\tstartedAt: state.startedAt,\n\t\t\t\t\tattempt,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst ctx = createContext(controller.signal);\n\n\t\t\t\tif (def.resolve) {\n\t\t\t\t\t// Batch the synchronous portion of resolve to coalesce fact mutations.\n\t\t\t\t\t// For sync-body async resolvers, all mutations are batched and flushed once.\n\t\t\t\t\t// For truly async resolvers, mutations before the first await are batched.\n\t\t\t\t\tlet resolvePromise!: Promise<void>;\n\t\t\t\t\tstore.batch(() => {\n\t\t\t\t\t\tresolvePromise = def.resolve!(req.requirement as Parameters<NonNullable<typeof def.resolve>>[0], ctx) as Promise<void>;\n\t\t\t\t\t});\n\n\t\t\t\t\tconst timeout = def.timeout;\n\t\t\t\t\tif (timeout && timeout > 0) {\n\t\t\t\t\t\tawait withTimeout(\n\t\t\t\t\t\t\tresolvePromise,\n\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\t`Resolver \"${resolverId}\" timed out after ${timeout}ms`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait resolvePromise;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Success\n\t\t\t\tconst duration = Date.now() - (state?.startedAt ?? Date.now());\n\t\t\t\tstatuses.set(req.id, {\n\t\t\t\t\tstate: \"success\",\n\t\t\t\t\trequirementId: req.id,\n\t\t\t\t\tcompletedAt: Date.now(),\n\t\t\t\t\tduration,\n\t\t\t\t});\n\t\t\t\tcleanupStatuses(); // Prevent memory leak\n\t\t\t\tonComplete?.(resolverId, req, duration);\n\t\t\t\treturn;\n\t\t\t} catch (error) {\n\t\t\t\tlastError = error instanceof Error ? error : new Error(String(error));\n\n\t\t\t\t// Check if it was an abort\n\t\t\t\tif (controller.signal.aborted) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Check shouldRetry predicate — if it returns false, stop immediately\n\t\t\t\tif (retryPolicy.shouldRetry && !retryPolicy.shouldRetry(lastError, attempt)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// If we have more attempts, wait and retry\n\t\t\t\tif (attempt < retryPolicy.attempts) {\n\t\t\t\t\t// Check abort before starting delay (avoids unnecessary waiting)\n\t\t\t\t\tif (controller.signal.aborted) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst delay = calculateDelay(retryPolicy, attempt);\n\t\t\t\t\tonRetry?.(resolverId, req, attempt + 1);\n\n\t\t\t\t\t// Use AbortSignal-aware sleep to respond to cancellation immediately\n\t\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\t\tconst timeoutId = setTimeout(resolve, delay);\n\t\t\t\t\t\t// Listen for abort during sleep\n\t\t\t\t\t\tconst abortHandler = () => {\n\t\t\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcontroller.signal.addEventListener(\"abort\", abortHandler, { once: true });\n\t\t\t\t\t});\n\n\t\t\t\t\t// Check abort after sleep\n\t\t\t\t\tif (controller.signal.aborted) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// All attempts failed (or shouldRetry returned false)\n\t\tstatuses.set(req.id, {\n\t\t\tstate: \"error\",\n\t\t\trequirementId: req.id,\n\t\t\terror: lastError!,\n\t\t\tfailedAt: Date.now(),\n\t\t\tattempts: retryPolicy.attempts,\n\t\t});\n\t\tcleanupStatuses();\n\t\tonError?.(resolverId, req, lastError);\n\t}\n\n\t/** Execute a batch of requirements with retry, timeout, and partial failure support */\n\tasync function executeBatch(\n\t\tresolverId: string,\n\t\trequirements: RequirementWithId[],\n\t): Promise<void> {\n\t\tconst def = definitions[resolverId];\n\t\tif (!def) return;\n\n\t\t// If no batch handler, fall back to individual resolution\n\t\tif (!def.resolveBatch && !def.resolveBatchWithResults) {\n\t\t\tawait Promise.all(\n\t\t\t\trequirements.map((req) => {\n\t\t\t\t\tconst controller = new AbortController();\n\t\t\t\t\treturn executeResolve(resolverId, req, controller);\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst retryPolicy = { ...DEFAULT_RETRY, ...def.retry };\n\t\tconst batchConfig = { ...DEFAULT_BATCH, ...def.batch };\n\t\tconst controller = new AbortController();\n\t\tconst startedAt = Date.now();\n\t\tlet lastError: Error | null = null;\n\n\t\t// Use batch timeout if configured, otherwise fall back to resolver timeout\n\t\tconst timeout = batchConfig.timeoutMs ?? def.timeout;\n\n\t\tfor (let attempt = 1; attempt <= retryPolicy.attempts; attempt++) {\n\t\t\t// Check if canceled\n\t\t\tif (controller.signal.aborted) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst ctx = createContext(controller.signal);\n\t\t\t\tconst reqPayloads = requirements.map((r) => r.requirement);\n\n\t\t\t\t// Check for resolveBatchWithResults (per-item results)\n\t\t\t\tif (def.resolveBatchWithResults) {\n\t\t\t\t\tlet results: BatchResolveResults;\n\n\t\t\t\t\t// Batch fact mutations for the synchronous portion of the resolver\n\t\t\t\t\tlet resolvePromise!: Promise<BatchResolveResults>;\n\t\t\t\t\tstore.batch(() => {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Requirement type varies\n\t\t\t\t\t\tresolvePromise = def.resolveBatchWithResults!(reqPayloads as any, ctx);\n\t\t\t\t\t});\n\n\t\t\t\t\tif (timeout && timeout > 0) {\n\t\t\t\t\t\tresults = await withTimeout(\n\t\t\t\t\t\t\tresolvePromise,\n\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\t`Batch resolver \"${resolverId}\" timed out after ${timeout}ms`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresults = await resolvePromise;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Validate results length\n\t\t\t\t\tif (results.length !== requirements.length) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`[Directive] Batch resolver \"${resolverId}\" returned ${results.length} results ` +\n\t\t\t\t\t\t\t\t`but expected ${requirements.length}. Results array must match input order.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Process per-item results\n\t\t\t\t\tconst duration = Date.now() - startedAt;\n\t\t\t\t\tlet hasFailures = false;\n\n\t\t\t\t\tfor (let i = 0; i < requirements.length; i++) {\n\t\t\t\t\t\tconst req = requirements[i]!;\n\t\t\t\t\t\tconst result = results[i]!;\n\n\t\t\t\t\t\tif (result.success) {\n\t\t\t\t\t\t\tstatuses.set(req.id, {\n\t\t\t\t\t\t\t\tstate: \"success\",\n\t\t\t\t\t\t\t\trequirementId: req.id,\n\t\t\t\t\t\t\t\tcompletedAt: Date.now(),\n\t\t\t\t\t\t\t\tduration,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tonComplete?.(resolverId, req, duration);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\thasFailures = true;\n\t\t\t\t\t\t\tconst error = result.error ?? new Error(\"Batch item failed\");\n\t\t\t\t\t\t\tstatuses.set(req.id, {\n\t\t\t\t\t\t\t\tstate: \"error\",\n\t\t\t\t\t\t\t\trequirementId: req.id,\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t\tfailedAt: Date.now(),\n\t\t\t\t\t\t\t\tattempts: attempt,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tonError?.(resolverId, req, error);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// No failures: all succeeded, done\n\t\t\t\t\tif (!hasFailures) return;\n\n\t\t\t\t\t// Partial success (some succeeded, some failed): don't retry the batch\n\t\t\t\t\tif (requirements.some((_, i) => results[i]?.success)) return;\n\n\t\t\t\t\t// ALL failed: fall through to retry logic below\n\t\t\t\t} else {\n\t\t\t\t\t// Use all-or-nothing resolveBatch\n\t\t\t\t\t// Batch fact mutations for the synchronous portion of the resolver\n\t\t\t\t\tlet resolvePromise!: Promise<void>;\n\t\t\t\t\tstore.batch(() => {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Requirement type varies\n\t\t\t\t\t\tresolvePromise = def.resolveBatch!(reqPayloads as any, ctx) as Promise<void>;\n\t\t\t\t\t});\n\n\t\t\t\t\tif (timeout && timeout > 0) {\n\t\t\t\t\t\tawait withTimeout(\n\t\t\t\t\t\t\tresolvePromise,\n\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\t`Batch resolver \"${resolverId}\" timed out after ${timeout}ms`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait resolvePromise;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Mark all as success\n\t\t\t\t\tconst duration = Date.now() - startedAt;\n\t\t\t\t\tfor (const req of requirements) {\n\t\t\t\t\t\tstatuses.set(req.id, {\n\t\t\t\t\t\t\tstate: \"success\",\n\t\t\t\t\t\t\trequirementId: req.id,\n\t\t\t\t\t\t\tcompletedAt: Date.now(),\n\t\t\t\t\t\t\tduration,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tonComplete?.(resolverId, req, duration);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tlastError = error instanceof Error ? error : new Error(String(error));\n\n\t\t\t\t// Check if it was an abort\n\t\t\t\tif (controller.signal.aborted) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Check shouldRetry predicate — if it returns false, stop immediately\n\t\t\t\tif (retryPolicy.shouldRetry && !retryPolicy.shouldRetry(lastError, attempt)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// If we have more attempts, wait and retry\n\t\t\t\tif (attempt < retryPolicy.attempts) {\n\t\t\t\t\tconst delay = calculateDelay(retryPolicy, attempt);\n\t\t\t\t\t// Notify retry for all requirements\n\t\t\t\t\tfor (const req of requirements) {\n\t\t\t\t\t\tonRetry?.(resolverId, req, attempt + 1);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Use AbortSignal-aware sleep\n\t\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\t\tconst timeoutId = setTimeout(resolve, delay);\n\t\t\t\t\t\tconst abortHandler = () => {\n\t\t\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcontroller.signal.addEventListener(\"abort\", abortHandler, { once: true });\n\t\t\t\t\t});\n\n\t\t\t\t\t// Check abort after sleep\n\t\t\t\t\tif (controller.signal.aborted) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// All attempts failed (or shouldRetry returned false) - mark all as error\n\t\tfor (const req of requirements) {\n\t\t\tstatuses.set(req.id, {\n\t\t\t\tstate: \"error\",\n\t\t\t\trequirementId: req.id,\n\t\t\t\terror: lastError!,\n\t\t\t\tfailedAt: Date.now(),\n\t\t\t\tattempts: retryPolicy.attempts,\n\t\t\t});\n\t\t\tonError?.(resolverId, req, lastError);\n\t\t}\n\t\tcleanupStatuses();\n\t}\n\n\t/** Add a requirement to a batch */\n\tfunction addToBatch(resolverId: string, req: RequirementWithId): void {\n\t\tconst def = definitions[resolverId];\n\t\tif (!def) return;\n\t\tconst batchConfig = { ...DEFAULT_BATCH, ...def.batch };\n\n\t\tif (!batches.has(resolverId)) {\n\t\t\tbatches.set(resolverId, {\n\t\t\t\tresolverId,\n\t\t\t\trequirements: [],\n\t\t\t\ttimer: null,\n\t\t\t});\n\t\t}\n\n\t\tconst batch = batches.get(resolverId)!;\n\t\tbatch.requirements.push(req);\n\n\t\t// Start or reset timer\n\t\tif (batch.timer) {\n\t\t\tclearTimeout(batch.timer);\n\t\t}\n\n\t\tbatch.timer = setTimeout(() => {\n\t\t\tprocessBatch(resolverId);\n\t\t}, batchConfig.windowMs);\n\t}\n\n\t/** Process a single batch */\n\tfunction processBatch(resolverId: string): void {\n\t\tconst batch = batches.get(resolverId);\n\t\tif (!batch || batch.requirements.length === 0) return;\n\n\t\tconst requirements = [...batch.requirements];\n\t\tbatch.requirements = [];\n\t\tbatch.timer = null;\n\n\t\t// Execute batch\n\t\texecuteBatch(resolverId, requirements).then(() => {\n\t\t\tonResolutionComplete?.();\n\t\t});\n\t}\n\n\tconst manager: ResolversManager<S> = {\n\t\tresolve(req: RequirementWithId): void {\n\t\t\t// Already resolving?\n\t\t\tif (inflight.has(req.id)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Find resolver\n\t\t\tconst resolverId = findResolver(req.requirement);\n\t\t\tif (!resolverId) {\n\t\t\t\tconsole.warn(`[Directive] No resolver found for requirement: ${req.id}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst def = definitions[resolverId];\n\t\t\tif (!def) return;\n\n\t\t\t// Check if this is a batched resolver\n\t\t\tif (def.batch?.enabled) {\n\t\t\t\taddToBatch(resolverId, req);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Start resolution\n\t\t\tconst controller = new AbortController();\n\t\t\tconst startedAt = Date.now();\n\n\t\t\tconst state: ResolverState = {\n\t\t\t\trequirementId: req.id,\n\t\t\t\tresolverId,\n\t\t\t\tcontroller,\n\t\t\t\tstartedAt,\n\t\t\t\tattempt: 1,\n\t\t\t\tstatus: {\n\t\t\t\t\tstate: \"pending\",\n\t\t\t\t\trequirementId: req.id,\n\t\t\t\t\tstartedAt,\n\t\t\t\t},\n\t\t\t\toriginalRequirement: req,\n\t\t\t};\n\n\t\t\tinflight.set(req.id, state);\n\t\t\tonStart?.(resolverId, req);\n\n\t\t\t// Execute asynchronously\n\t\t\texecuteResolve(resolverId, req, controller)\n\t\t\t\t.finally(() => {\n\t\t\t\t\t// Only fire onResolutionComplete if we're the first to clean up.\n\t\t\t\t\t// If cancel() already removed us from inflight, skip to avoid\n\t\t\t\t\t// spurious double-notifications.\n\t\t\t\t\tconst wasInflight = inflight.delete(req.id);\n\t\t\t\t\tif (wasInflight) {\n\t\t\t\t\t\tonResolutionComplete?.();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t},\n\n\t\tcancel(requirementId: string): void {\n\t\t\tconst state = inflight.get(requirementId);\n\t\t\tif (!state) return;\n\n\t\t\tstate.controller.abort();\n\t\t\tinflight.delete(requirementId);\n\n\t\t\tstatuses.set(requirementId, {\n\t\t\t\tstate: \"canceled\",\n\t\t\t\trequirementId,\n\t\t\t\tcanceledAt: Date.now(),\n\t\t\t});\n\t\t\tcleanupStatuses();\n\n\t\t\tonCancel?.(state.resolverId, state.originalRequirement);\n\t\t},\n\n\t\tcancelAll(): void {\n\t\t\tfor (const [id] of inflight) {\n\t\t\t\tthis.cancel(id);\n\t\t\t}\n\n\t\t\t// Clear batches\n\t\t\tfor (const batch of batches.values()) {\n\t\t\t\tif (batch.timer) {\n\t\t\t\t\tclearTimeout(batch.timer);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbatches.clear();\n\t\t},\n\n\t\tgetStatus(requirementId: string): ResolverStatus {\n\t\t\t// Check inflight first\n\t\t\tconst state = inflight.get(requirementId);\n\t\t\tif (state) {\n\t\t\t\treturn state.status;\n\t\t\t}\n\n\t\t\t// Check completed statuses\n\t\t\tconst status = statuses.get(requirementId);\n\t\t\tif (status) {\n\t\t\t\treturn status;\n\t\t\t}\n\n\t\t\treturn { state: \"idle\" };\n\t\t},\n\n\t\tgetInflight(): string[] {\n\t\t\treturn [...inflight.keys()];\n\t\t},\n\n\t\tgetInflightInfo(): InflightInfo[] {\n\t\t\treturn [...inflight.values()].map((state) => ({\n\t\t\t\tid: state.requirementId,\n\t\t\t\tresolverId: state.resolverId,\n\t\t\t\tstartedAt: state.startedAt,\n\t\t\t}));\n\t\t},\n\n\t\tisResolving(requirementId: string): boolean {\n\t\t\treturn inflight.has(requirementId);\n\t\t},\n\n\t\tprocessBatches(): void {\n\t\t\tfor (const resolverId of batches.keys()) {\n\t\t\t\tprocessBatch(resolverId);\n\t\t\t}\n\t\t},\n\n\t\tregisterDefinitions(newDefs: ResolversDef<Schema>): void {\n\t\t\tfor (const [key, def] of Object.entries(newDefs)) {\n\t\t\t\t(definitions as Record<string, unknown>)[key] = def;\n\t\t\t}\n\t\t\t// Clear the resolver-by-type cache so new resolvers are discovered\n\t\t\tresolversByType.clear();\n\t\t},\n\t};\n\n\treturn manager;\n}\n","/**\n * Time-Travel Debugging - Snapshot-based state history\n *\n * Features:\n * - Ring buffer of state snapshots\n * - Go back/forward through history\n * - Replay from any snapshot\n * - Export/import state history\n */\n\nimport type { DebugConfig, Facts, FactsStore, Schema, Snapshot, TimeTravelAPI } from \"../core/types.js\";\nimport { isPrototypeSafe } from \"./utils.js\";\n\n// ============================================================================\n// Time-Travel Manager\n// ============================================================================\n\n/** A changeset groups multiple snapshots into a single undo/redo unit. */\nexport interface Changeset {\n\tlabel: string;\n\tstartIndex: number;\n\tendIndex: number;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface TimeTravelManager<_S extends Schema> extends TimeTravelAPI {\n\t/** Take a snapshot of current state */\n\ttakeSnapshot(trigger: string): Snapshot;\n\t/** Restore facts from a snapshot */\n\trestore(snapshot: Snapshot): void;\n\t/** Check if time-travel is enabled */\n\treadonly isEnabled: boolean;\n\t/** True while restoring a snapshot (engine should skip reconciliation) */\n\treadonly isRestoring: boolean;\n\t/** Pause snapshot taking */\n\tpause(): void;\n\t/** Resume snapshot taking */\n\tresume(): void;\n}\n\n/** Options for creating a time-travel manager */\nexport interface CreateTimeTravelOptions<S extends Schema> {\n\tconfig: DebugConfig;\n\tfacts: Facts<S>;\n\tstore: FactsStore<S>;\n\t/** Callback when a snapshot is taken */\n\tonSnapshot?: (snapshot: Snapshot) => void;\n\t/** Callback when time-travel occurs */\n\tonTimeTravel?: (from: number, to: number) => void;\n}\n\n/**\n * Create a snapshot-based time-travel debugger with a ring buffer of state\n * history.\n *\n * Snapshots are taken automatically after fact changes (during\n * reconciliation) and can be navigated with `goBack`/`goForward`/`goTo`.\n * Changesets group multiple snapshots into a single undo/redo unit.\n * The entire history can be exported to JSON and re-imported for\n * cross-session debugging.\n *\n * @param options - Debug config (maxSnapshots, timeTravel flag), facts proxy, store, and snapshot/time-travel callbacks\n * @returns A `TimeTravelManager` with takeSnapshot/restore/goBack/goForward/goTo/replay/export/import and changeset methods\n */\nexport function createTimeTravelManager<S extends Schema>(\n\toptions: CreateTimeTravelOptions<S>,\n): TimeTravelManager<S> {\n\tconst { config, facts, store, onSnapshot, onTimeTravel } = options;\n\n\tconst isEnabled = config.timeTravel ?? false;\n\tconst maxSnapshots = config.maxSnapshots ?? 100;\n\n\t// Ring buffer of snapshots\n\tconst snapshots: Snapshot[] = [];\n\tlet currentIndex = -1;\n\tlet nextId = 1;\n\tlet paused = false;\n\tlet restoring = false;\n\n\t// Changeset tracking\n\tconst changesets: Changeset[] = [];\n\tlet pendingChangesetLabel: string | null = null;\n\tlet pendingChangesetStart = -1;\n\n\t/** Get current facts as a plain object */\n\tfunction getCurrentFacts(): Record<string, unknown> {\n\t\treturn store.toObject();\n\t}\n\n\t/** Serialize facts to a snapshot-friendly format */\n\tfunction serializeFacts(): Record<string, unknown> {\n\t\tconst factsObj = getCurrentFacts();\n\n\t\t// Deep clone to prevent mutation\n\t\treturn structuredClone(factsObj);\n\t}\n\n\t/** Deserialize and restore facts from a snapshot */\n\tfunction deserializeFacts(serialized: Record<string, unknown>): void {\n\t\t// Validate entire object tree for prototype pollution\n\t\tif (!isPrototypeSafe(serialized)) {\n\t\t\tconsole.error(\"[Directive] Potential prototype pollution detected in snapshot data, skipping restore\");\n\t\t\treturn;\n\t\t}\n\n\t\tstore.batch(() => {\n\t\t\tfor (const [key, value] of Object.entries(serialized)) {\n\t\t\t\t// Prototype pollution protection (redundant but defensive)\n\t\t\t\tif (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") {\n\t\t\t\t\tconsole.warn(`[Directive] Skipping dangerous key \"${key}\" during fact restoration`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// @ts-expect-error - dynamic key access\n\t\t\t\tfacts[key] = value;\n\t\t\t}\n\t\t});\n\t}\n\n\tconst manager: TimeTravelManager<S> = {\n\t\tget isEnabled() {\n\t\t\treturn isEnabled;\n\t\t},\n\n\t\tget isRestoring() {\n\t\t\treturn restoring;\n\t\t},\n\n\t\tget isPaused() {\n\t\t\treturn paused;\n\t\t},\n\n\t\tget snapshots() {\n\t\t\treturn [...snapshots];\n\t\t},\n\n\t\tget currentIndex() {\n\t\t\treturn currentIndex;\n\t\t},\n\n\t\ttakeSnapshot(trigger: string): Snapshot {\n\t\t\tif (!isEnabled || paused) {\n\t\t\t\treturn { id: -1, timestamp: Date.now(), facts: {}, trigger };\n\t\t\t}\n\n\t\t\tconst snapshot: Snapshot = {\n\t\t\t\tid: nextId++,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tfacts: serializeFacts(),\n\t\t\t\ttrigger,\n\t\t\t};\n\n\t\t\t// If we're not at the end, truncate future snapshots\n\t\t\tif (currentIndex < snapshots.length - 1) {\n\t\t\t\tsnapshots.splice(currentIndex + 1);\n\t\t\t}\n\n\t\t\t// Add new snapshot\n\t\t\tsnapshots.push(snapshot);\n\t\t\tcurrentIndex = snapshots.length - 1;\n\n\t\t\t// Enforce max size (ring buffer)\n\t\t\twhile (snapshots.length > maxSnapshots) {\n\t\t\t\tsnapshots.shift();\n\t\t\t\tcurrentIndex--;\n\t\t\t}\n\n\t\t\tonSnapshot?.(snapshot);\n\t\t\treturn snapshot;\n\t\t},\n\n\t\trestore(snapshot: Snapshot): void {\n\t\t\tif (!isEnabled) return;\n\n\t\t\t// Set restoring flag so the engine skips reconciliation scheduling.\n\t\t\t// The restored state is already \"reconciled\" — it was captured after\n\t\t\t// a complete reconcile cycle. Re-reconciling would create spurious\n\t\t\t// snapshots that break undo/redo navigation.\n\t\t\tpaused = true;\n\t\t\trestoring = true;\n\n\t\t\ttry {\n\t\t\t\tdeserializeFacts(snapshot.facts);\n\t\t\t} finally {\n\t\t\t\tpaused = false;\n\t\t\t\trestoring = false;\n\t\t\t}\n\t\t},\n\n\t\tgoBack(steps = 1): void {\n\t\t\tif (!isEnabled || snapshots.length === 0) return;\n\n\t\t\tconst fromIndex = currentIndex;\n\n\t\t\t// Check if we're inside a changeset — jump to its start\n\t\t\tlet toIndex = currentIndex;\n\t\t\tconst cs = changesets.find((c) => currentIndex > c.startIndex && currentIndex <= c.endIndex);\n\t\t\tif (cs) {\n\t\t\t\ttoIndex = cs.startIndex;\n\t\t\t} else {\n\t\t\t\t// Check if we're at the end of a changeset — jump past its start\n\t\t\t\tconst prevCs = changesets.find((c) => currentIndex === c.startIndex);\n\t\t\t\tif (prevCs) {\n\t\t\t\t\t// We're at the boundary. Look for the changeset before this one.\n\t\t\t\t\tconst earlierCs = changesets.find((c) => c.endIndex < currentIndex && currentIndex - c.endIndex <= steps);\n\t\t\t\t\ttoIndex = earlierCs ? earlierCs.startIndex : Math.max(0, currentIndex - steps);\n\t\t\t\t} else {\n\t\t\t\t\ttoIndex = Math.max(0, currentIndex - steps);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (fromIndex === toIndex) return;\n\n\t\t\tcurrentIndex = toIndex;\n\t\t\tconst snapshot = snapshots[currentIndex];\n\t\t\tif (snapshot) {\n\t\t\t\tthis.restore(snapshot);\n\t\t\t\tonTimeTravel?.(fromIndex, toIndex);\n\t\t\t}\n\t\t},\n\n\t\tgoForward(steps = 1): void {\n\t\t\tif (!isEnabled || snapshots.length === 0) return;\n\n\t\t\tconst fromIndex = currentIndex;\n\n\t\t\t// Check if we're inside or at the start of a changeset — jump to its end\n\t\t\tlet toIndex = currentIndex;\n\t\t\tconst cs = changesets.find((c) => currentIndex >= c.startIndex && currentIndex < c.endIndex);\n\t\t\tif (cs) {\n\t\t\t\ttoIndex = cs.endIndex;\n\t\t\t} else {\n\t\t\t\ttoIndex = Math.min(snapshots.length - 1, currentIndex + steps);\n\t\t\t}\n\n\t\t\tif (fromIndex === toIndex) return;\n\n\t\t\tcurrentIndex = toIndex;\n\t\t\tconst snapshot = snapshots[currentIndex];\n\t\t\tif (snapshot) {\n\t\t\t\tthis.restore(snapshot);\n\t\t\t\tonTimeTravel?.(fromIndex, toIndex);\n\t\t\t}\n\t\t},\n\n\t\tgoTo(snapshotId: number): void {\n\t\t\tif (!isEnabled) return;\n\n\t\t\tconst index = snapshots.findIndex((s) => s.id === snapshotId);\n\t\t\tif (index === -1) {\n\t\t\t\tconsole.warn(`[Directive] Snapshot ${snapshotId} not found`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst fromIndex = currentIndex;\n\t\t\tcurrentIndex = index;\n\t\t\tconst snapshot = snapshots[currentIndex];\n\t\t\tif (snapshot) {\n\t\t\t\tthis.restore(snapshot);\n\t\t\t\tonTimeTravel?.(fromIndex, index);\n\t\t\t}\n\t\t},\n\n\t\treplay(): void {\n\t\t\tif (!isEnabled || snapshots.length === 0) return;\n\n\t\t\t// Start from the beginning\n\t\t\tcurrentIndex = 0;\n\t\t\tconst snapshot = snapshots[0];\n\t\t\tif (snapshot) {\n\t\t\t\tthis.restore(snapshot);\n\t\t\t}\n\t\t},\n\n\t\texport(): string {\n\t\t\treturn JSON.stringify({\n\t\t\t\tversion: 1,\n\t\t\t\tsnapshots,\n\t\t\t\tcurrentIndex,\n\t\t\t});\n\t\t},\n\n\t\timport(json: string): void {\n\t\t\tif (!isEnabled) return;\n\n\t\t\ttry {\n\t\t\t\tconst data = JSON.parse(json);\n\n\t\t\t\t// Validate import data structure to prevent prototype pollution\n\t\t\t\tif (typeof data !== \"object\" || data === null) {\n\t\t\t\t\tthrow new Error(\"Invalid time-travel data: expected object\");\n\t\t\t\t}\n\t\t\t\tif (data.version !== 1) {\n\t\t\t\t\tthrow new Error(`Unsupported time-travel export version: ${data.version}`);\n\t\t\t\t}\n\t\t\t\tif (!Array.isArray(data.snapshots)) {\n\t\t\t\t\tthrow new Error(\"Invalid time-travel data: snapshots must be an array\");\n\t\t\t\t}\n\t\t\t\tif (typeof data.currentIndex !== \"number\") {\n\t\t\t\t\tthrow new Error(\"Invalid time-travel data: currentIndex must be a number\");\n\t\t\t\t}\n\n\t\t\t\t// Validate each snapshot has required properties\n\t\t\t\tfor (const snap of data.snapshots) {\n\t\t\t\t\tif (typeof snap !== \"object\" || snap === null) {\n\t\t\t\t\t\tthrow new Error(\"Invalid snapshot: expected object\");\n\t\t\t\t\t}\n\t\t\t\t\tif (typeof snap.id !== \"number\" || typeof snap.timestamp !== \"number\" ||\n\t\t\t\t\t\ttypeof snap.trigger !== \"string\" || typeof snap.facts !== \"object\") {\n\t\t\t\t\t\tthrow new Error(\"Invalid snapshot structure\");\n\t\t\t\t\t}\n\t\t\t\t\t// Deep check for prototype pollution attacks (including nested objects)\n\t\t\t\t\tif (!isPrototypeSafe(snap.facts)) {\n\t\t\t\t\t\tthrow new Error(\"Invalid fact data: potential prototype pollution detected in nested objects\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsnapshots.length = 0;\n\t\t\t\tsnapshots.push(...data.snapshots);\n\t\t\t\tcurrentIndex = data.currentIndex;\n\n\t\t\t\t// Restore current state\n\t\t\t\tconst snapshot = snapshots[currentIndex];\n\t\t\t\tif (snapshot) {\n\t\t\t\t\tthis.restore(snapshot);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"[Directive] Failed to import time-travel data:\", error);\n\t\t\t}\n\t\t},\n\n\t\tbeginChangeset(label: string): void {\n\t\t\tif (!isEnabled) return;\n\t\t\tpendingChangesetLabel = label;\n\t\t\tpendingChangesetStart = currentIndex;\n\t\t},\n\n\t\tendChangeset(): void {\n\t\t\tif (!isEnabled || pendingChangesetLabel === null) return;\n\t\t\tif (currentIndex > pendingChangesetStart) {\n\t\t\t\tchangesets.push({\n\t\t\t\t\tlabel: pendingChangesetLabel,\n\t\t\t\t\tstartIndex: pendingChangesetStart,\n\t\t\t\t\tendIndex: currentIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t\tpendingChangesetLabel = null;\n\t\t\tpendingChangesetStart = -1;\n\t\t},\n\n\t\tpause(): void {\n\t\t\tpaused = true;\n\t\t},\n\n\t\tresume(): void {\n\t\t\tpaused = false;\n\t\t},\n\t};\n\n\treturn manager;\n}\n\n/**\n * Create a no-op time-travel manager used when `debug.timeTravel` is\n * disabled. All methods are safe to call but perform no work.\n *\n * @returns A `TimeTravelManager` where every method is a no-op and `isEnabled` is `false`\n */\nexport function createDisabledTimeTravel<S extends Schema>(): TimeTravelManager<S> {\n\tconst noopSnapshot: Snapshot = { id: -1, timestamp: 0, facts: {}, trigger: \"\" };\n\n\treturn {\n\t\tisEnabled: false,\n\t\tisRestoring: false,\n\t\tisPaused: false,\n\t\tsnapshots: [],\n\t\tcurrentIndex: -1,\n\t\ttakeSnapshot: () => noopSnapshot,\n\t\trestore: () => {},\n\t\tgoBack: () => {},\n\t\tgoForward: () => {},\n\t\tgoTo: () => {},\n\t\treplay: () => {},\n\t\texport: () => \"{}\",\n\t\timport: () => {},\n\t\tbeginChangeset: () => {},\n\t\tendChangeset: () => {},\n\t\tpause: () => {},\n\t\tresume: () => {},\n\t};\n}\n","/**\n * Engine - The core reconciliation loop\n *\n * The engine orchestrates:\n * 1. Fact changes trigger reconciliation\n * 2. Constraints produce requirements\n * 3. Resolvers fulfill requirements\n * 4. Effects run after stabilization\n * 5. Derivations are invalidated and recomputed\n */\n\nimport { createConstraintsManager, type ConstraintsManager } from \"./constraints.js\";\nimport { createDerivationsManager, type DerivationsManager } from \"./derivations.js\";\nimport { createEffectsManager, type EffectsManager } from \"./effects.js\";\nimport { createErrorBoundaryManager, type ErrorBoundaryManager } from \"./errors.js\";\nimport { createFacts } from \"./facts.js\";\nimport { createPluginManager, type PluginManager } from \"./plugins.js\";\nimport { RequirementSet } from \"./requirements.js\";\nimport { createResolversManager, type ResolversManager } from \"./resolvers.js\";\nimport { createDisabledTimeTravel, createTimeTravelManager, type TimeTravelManager } from \"../utils/time-travel.js\";\nimport { isPrototypeSafe, hashObject } from \"../utils/utils.js\";\n\n// Blocked properties for prototype pollution protection\nconst BLOCKED_PROPS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\nimport type {\n\tConstraintsDef,\n\tDerivationsDef,\n\tEffectsDef,\n\tEventsDef,\n\tFactsSnapshot,\n\tInferSchema,\n\tReconcileResult,\n\tResolversDef,\n\tSchema,\n\tSystem,\n\tSystemConfig,\n\tSystemEvent,\n\tSystemInspection,\n} from \"./types.js\";\n\n// ============================================================================\n// Engine Implementation\n// ============================================================================\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ninterface EngineState<_S extends Schema> {\n\tisRunning: boolean;\n\tisReconciling: boolean;\n\treconcileScheduled: boolean;\n\tisInitializing: boolean;\n\tisInitialized: boolean;\n\tisReady: boolean;\n\tisDestroyed: boolean;\n\tchangedKeys: Set<string>;\n\tpreviousRequirements: RequirementSet;\n\treadyPromise: Promise<void> | null;\n\treadyResolve: (() => void) | null;\n}\n\n/**\n * Create the core Directive reconciliation engine that wires facts, derivations,\n * effects, constraints, resolvers, plugins, error boundaries, and time-travel\n * into a single reactive system.\n *\n * This is the internal factory used by `createSystem`. Most users should call\n * `createSystem` instead, which provides a friendlier API and handles module\n * composition.\n *\n * @param config - Full system configuration: modules, plugins, error boundary settings, and debug options\n * @returns A `System` instance with facts, derive, events, dispatch, subscribe, watch, settle, and lifecycle methods\n *\n * @example\n * ```ts\n * // Prefer createSystem for most use cases:\n * import { createSystem, createModule, t } from \"@directive-run/core\";\n *\n * const counter = createModule(\"counter\", {\n * schema: { count: t.number() },\n * init: (facts) => { facts.count = 0; },\n * });\n *\n * const system = createSystem({ module: counter });\n * system.start();\n * system.facts.count = 42;\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: Engine uses flat schema internally, public API uses ModuleSchema\nexport function createEngine<S extends Schema>(\n\tconfig: SystemConfig<any>,\n): System<any> {\n\t// Merge all module definitions with collision detection\n\t// Use Object.create(null) to prevent prototype chain traversal (e.g., \"toString\" in mergedEvents)\n\tconst mergedSchema = Object.create(null) as S;\n\tconst mergedEvents: EventsDef<S> = Object.create(null);\n\tconst mergedDerive: DerivationsDef<S> = Object.create(null);\n\tconst mergedEffects: EffectsDef<S> = Object.create(null);\n\tconst mergedConstraints: ConstraintsDef<S> = Object.create(null);\n\tconst mergedResolvers: ResolversDef<S> = Object.create(null);\n\n\t// Track which module defined each key for collision detection\n\tconst schemaOwners = new Map<string, string>();\n\n\tfor (const module of config.modules) {\n\t\t// Security: Validate module definitions for dangerous keys\n\t\t// Always run in all environments — this is a security boundary, not a dev convenience\n\t\tconst validateKeys = (obj: object | undefined, section: string) => {\n\t\t\tif (!obj) return;\n\t\t\tfor (const key of Object.keys(obj)) {\n\t\t\t\tif (BLOCKED_PROPS.has(key)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Security: Module \"${module.id}\" has dangerous key \"${key}\" in ${section}. ` +\n\t\t\t\t\t\t\t`This could indicate a prototype pollution attempt.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tvalidateKeys(module.schema, \"schema\");\n\t\tvalidateKeys(module.events, \"events\");\n\t\tvalidateKeys(module.derive, \"derive\");\n\t\tvalidateKeys(module.effects, \"effects\");\n\t\tvalidateKeys(module.constraints, \"constraints\");\n\t\tvalidateKeys(module.resolvers, \"resolvers\");\n\n\t\t// Check for schema collisions\n\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\tfor (const key of Object.keys(module.schema)) {\n\t\t\t\tconst existingOwner = schemaOwners.get(key);\n\t\t\t\tif (existingOwner) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Schema collision: Fact \"${key}\" is defined in both module \"${existingOwner}\" and \"${module.id}\". ` +\n\t\t\t\t\t\t\t`Use namespacing (e.g., \"${module.id}::${key}\") or merge into one module.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tschemaOwners.set(key, module.id);\n\t\t\t}\n\t\t}\n\n\t\tObject.assign(mergedSchema, module.schema);\n\t\tif (module.events) Object.assign(mergedEvents, module.events);\n\t\tif (module.derive) Object.assign(mergedDerive, module.derive);\n\t\tif (module.effects) Object.assign(mergedEffects, module.effects);\n\t\tif (module.constraints) Object.assign(mergedConstraints, module.constraints);\n\t\tif (module.resolvers) Object.assign(mergedResolvers, module.resolvers);\n\t}\n\n\t// Build snapshotEventNames: Set<string> | null\n\t// If any module declares snapshotEvents, build the filter set.\n\t// Modules WITHOUT snapshotEvents have all their events added (they still snapshot).\n\tlet snapshotEventNames: Set<string> | null = null;\n\t// biome-ignore lint/suspicious/noExplicitAny: Module may have snapshotEvents at runtime\n\tconst hasAnySnapshotEvents = config.modules.some((m: any) => m.snapshotEvents);\n\tif (hasAnySnapshotEvents) {\n\t\tsnapshotEventNames = new Set<string>();\n\t\tfor (const module of config.modules) {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Module may have snapshotEvents at runtime\n\t\t\tconst mod = module as any;\n\t\t\tif (mod.snapshotEvents) {\n\t\t\t\tfor (const eventName of mod.snapshotEvents) {\n\t\t\t\t\tsnapshotEventNames.add(eventName);\n\t\t\t\t}\n\t\t\t} else if (mod.events) {\n\t\t\t\t// No filter — all events from this module create snapshots\n\t\t\t\tfor (const eventName of Object.keys(mod.events)) {\n\t\t\t\t\tsnapshotEventNames.add(eventName);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Snapshot intent flags — track whether the current change batch should create a snapshot\n\tlet dispatchDepth = 0;\n\tlet shouldTakeSnapshot = false;\n\n\t// Dev-mode: Warn if a fact and derivation share the same name\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tconst derivationNames = new Set(Object.keys(mergedDerive));\n\t\tfor (const key of Object.keys(mergedSchema)) {\n\t\t\tif (derivationNames.has(key)) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] \"${key}\" exists as both a fact and a derivation. ` +\n\t\t\t\t\t`This may cause unexpected dependency tracking behavior.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create plugin manager\n\tconst pluginManager: PluginManager<S> = createPluginManager();\n\tfor (const plugin of config.plugins ?? []) {\n\t\tpluginManager.register(plugin);\n\t}\n\n\t// Create error boundary\n\tconst errorBoundary: ErrorBoundaryManager = createErrorBoundaryManager({\n\t\tconfig: config.errorBoundary,\n\t\tonError: (error) => pluginManager.emitError(error),\n\t\tonRecovery: (error, strategy) => pluginManager.emitErrorRecovery(error, strategy),\n\t});\n\n\t// Create facts store and proxy\n\t// Note: We need to create a local invalidate function that will be set after derivationsManager is created\n\tlet invalidateDerivation: (key: string) => void = () => {};\n\tlet invalidateManyDerivations: (keys: string[]) => void = () => {};\n\n\t// Forward-declared so onChange/onBatch closures can check isRestoring.\n\t// Assigned after createTimeTravelManager() below.\n\tlet timeTravelRef: TimeTravelManager<S> | null = null;\n\n\tconst { store, facts } = createFacts<S>({\n\t\tschema: mergedSchema,\n\t\tonChange: (key, value, prev) => {\n\t\t\tpluginManager.emitFactSet(key, value, prev);\n\t\t\t// Invalidate derivations so they recompute on read\n\t\t\tinvalidateDerivation(key);\n\t\t\t// During time-travel restore, skip change tracking and reconciliation.\n\t\t\t// The restored state is already reconciled; re-reconciling would create\n\t\t\t// spurious snapshots that break undo/redo.\n\t\t\tif (timeTravelRef?.isRestoring) return;\n\t\t\t// Direct fact mutations (outside event dispatch) always create snapshots\n\t\t\tif (dispatchDepth === 0) {\n\t\t\t\tshouldTakeSnapshot = true;\n\t\t\t}\n\t\t\tstate.changedKeys.add(key);\n\t\t\tscheduleReconcile();\n\t\t},\n\t\tonBatch: (changes) => {\n\t\t\tpluginManager.emitFactsBatch(changes);\n\t\t\tconst keys: string[] = [];\n\t\t\tfor (const change of changes) {\n\t\t\t\tkeys.push(change.key);\n\t\t\t}\n\t\t\t// Invalidate all affected derivations at once — listeners fire only\n\t\t\t// after ALL keys are invalidated, so they see consistent state.\n\t\t\tinvalidateManyDerivations(keys);\n\t\t\t// During time-travel restore, skip change tracking and reconciliation.\n\t\t\tif (timeTravelRef?.isRestoring) return;\n\t\t\t// Resolver/effect batches (outside event dispatch) always create snapshots\n\t\t\tif (dispatchDepth === 0) {\n\t\t\t\tshouldTakeSnapshot = true;\n\t\t\t}\n\t\t\tfor (const change of changes) {\n\t\t\t\tstate.changedKeys.add(change.key);\n\t\t\t}\n\t\t\tscheduleReconcile();\n\t\t},\n\t});\n\n\t// Create derivations manager\n\tconst derivationsManager: DerivationsManager<S, DerivationsDef<S>> = createDerivationsManager({\n\t\tdefinitions: mergedDerive,\n\t\tfacts,\n\t\tstore,\n\t\tonCompute: (id, value, deps) => pluginManager.emitDerivationCompute(id, value, deps),\n\t\tonInvalidate: (id) => pluginManager.emitDerivationInvalidate(id),\n\t\tonError: (id, error) => {\n\t\t\terrorBoundary.handleError(\"derivation\", id, error);\n\t\t},\n\t});\n\n\t// Now wire up derivation invalidation\n\tinvalidateDerivation = (key: string) => derivationsManager.invalidate(key);\n\tinvalidateManyDerivations = (keys: string[]) => derivationsManager.invalidateMany(keys);\n\n\t// Create effects manager\n\tconst effectsManager: EffectsManager<S> = createEffectsManager({\n\t\tdefinitions: mergedEffects,\n\t\tfacts,\n\t\tstore,\n\t\tonRun: (id) => pluginManager.emitEffectRun(id),\n\t\tonError: (id, error) => {\n\t\t\terrorBoundary.handleError(\"effect\", id, error);\n\t\t\tpluginManager.emitEffectError(id, error);\n\t\t},\n\t});\n\n\t// Create constraints manager\n\tconst constraintsManager: ConstraintsManager<S> = createConstraintsManager({\n\t\tdefinitions: mergedConstraints,\n\t\tfacts,\n\t\tonEvaluate: (id, active) => pluginManager.emitConstraintEvaluate(id, active),\n\t\tonError: (id, error) => {\n\t\t\terrorBoundary.handleError(\"constraint\", id, error);\n\t\t\tpluginManager.emitConstraintError(id, error);\n\t\t},\n\t});\n\n\t// Create resolvers manager\n\tconst resolversManager: ResolversManager<S> = createResolversManager({\n\t\tdefinitions: mergedResolvers,\n\t\tfacts,\n\t\tstore,\n\t\tonStart: (resolver, req) => pluginManager.emitResolverStart(resolver, req),\n\t\tonComplete: (resolver, req, duration) => {\n\t\t\tpluginManager.emitResolverComplete(resolver, req, duration);\n\t\t\tpluginManager.emitRequirementMet(req, resolver);\n\t\t\t// Mark the constraint as resolved for `after` ordering\n\t\t\tconstraintsManager.markResolved(req.fromConstraint);\n\t\t},\n\t\tonError: (resolver, req, error) => {\n\t\t\terrorBoundary.handleError(\"resolver\", resolver, error, req);\n\t\t\tpluginManager.emitResolverError(resolver, req, error);\n\t\t},\n\t\tonRetry: (resolver, req, attempt) => pluginManager.emitResolverRetry(resolver, req, attempt),\n\t\tonCancel: (resolver, req) => {\n\t\t\tpluginManager.emitResolverCancel(resolver, req);\n\t\t\tpluginManager.emitRequirementCanceled(req);\n\t\t},\n\t\tonResolutionComplete: () => {\n\t\t\t// After a resolver completes, schedule another reconcile\n\t\t\tnotifySettlementChange();\n\t\t\tscheduleReconcile();\n\t\t},\n\t});\n\n\t// Time-travel listeners — notified when snapshot state changes\n\tconst timeTravelListeners = new Set<() => void>();\n\n\tfunction notifyTimeTravelChange(): void {\n\t\tfor (const listener of timeTravelListeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n\n\t// Create time-travel manager\n\tconst timeTravelManager: TimeTravelManager<S> = config.debug?.timeTravel\n\t\t? createTimeTravelManager({\n\t\t\t\tconfig: config.debug,\n\t\t\t\tfacts,\n\t\t\t\tstore,\n\t\t\t\tonSnapshot: (snapshot) => {\n\t\t\t\t\tpluginManager.emitSnapshot(snapshot);\n\t\t\t\t\tnotifyTimeTravelChange();\n\t\t\t\t},\n\t\t\t\tonTimeTravel: (from, to) => {\n\t\t\t\t\tpluginManager.emitTimeTravel(from, to);\n\t\t\t\t\tnotifyTimeTravelChange();\n\t\t\t\t},\n\t\t\t})\n\t\t: createDisabledTimeTravel();\n\ttimeTravelRef = timeTravelManager;\n\n\t// Settlement listeners — notified when isSettled may have changed\n\tconst settlementListeners = new Set<() => void>();\n\n\tfunction notifySettlementChange(): void {\n\t\tfor (const listener of settlementListeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n\n\t// Reconcile depth guard — prevents runaway reconcile → scheduleReconcile chains\n\tconst MAX_RECONCILE_DEPTH = 50;\n\tlet reconcileDepth = 0;\n\n\t// Engine state\n\tconst state: EngineState<S> = {\n\t\tisRunning: false,\n\t\tisReconciling: false,\n\t\treconcileScheduled: false,\n\t\tisInitializing: false,\n\t\tisInitialized: false,\n\t\tisReady: false,\n\t\tisDestroyed: false,\n\t\tchangedKeys: new Set(),\n\t\tpreviousRequirements: new RequirementSet(),\n\t\treadyPromise: null,\n\t\treadyResolve: null,\n\t};\n\n\t/** Schedule a reconciliation on the next microtask */\n\tfunction scheduleReconcile(): void {\n\t\t// Suppress reconciliation during initialization phase\n\t\tif (!state.isRunning || state.reconcileScheduled || state.isInitializing) return;\n\n\t\tstate.reconcileScheduled = true;\n\t\tnotifySettlementChange();\n\t\tqueueMicrotask(() => {\n\t\t\tstate.reconcileScheduled = false;\n\t\t\tif (state.isRunning && !state.isInitializing) {\n\t\t\t\t// Await reconcile to prevent race conditions\n\t\t\t\t// Error is caught inside reconcile, so no need to handle here\n\t\t\t\treconcile().catch((error) => {\n\t\t\t\t\t// Only log unexpected errors (reconcile handles its own errors)\n\t\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\t\tconsole.error(\"[Directive] Unexpected error in reconcile:\", error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\n\t/** The main reconciliation loop */\n\tasync function reconcile(): Promise<void> {\n\t\tif (state.isReconciling) return;\n\n\t\treconcileDepth++;\n\t\tif (reconcileDepth > MAX_RECONCILE_DEPTH) {\n\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] Reconcile loop exceeded ${MAX_RECONCILE_DEPTH} iterations. ` +\n\t\t\t\t\t`This usually means resolvers are creating circular requirement chains. ` +\n\t\t\t\t\t`Check that resolvers aren't mutating facts that re-trigger their own constraints.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treconcileDepth = 0;\n\t\t\treturn;\n\t\t}\n\n\t\tstate.isReconciling = true;\n\t\tnotifySettlementChange();\n\n\t\ttry {\n\t\t\t// Take snapshot before reconciliation (respects snapshotEvents filtering)\n\t\t\tif (state.changedKeys.size > 0) {\n\t\t\t\tif (snapshotEventNames === null || shouldTakeSnapshot) {\n\t\t\t\t\ttimeTravelManager.takeSnapshot(`facts-changed:${[...state.changedKeys].join(\",\")}`);\n\t\t\t\t}\n\t\t\t\tshouldTakeSnapshot = false;\n\t\t\t}\n\n\t\t\t// Get snapshot for plugins\n\t\t\tconst snapshot = facts.$snapshot() as FactsSnapshot<S>;\n\t\t\tpluginManager.emitReconcileStart(snapshot);\n\n\t\t\t// Note: Derivations are already invalidated immediately when facts change\n\t\t\t// (in the onChange/onBatch callbacks), so we don't need to do it here\n\n\t\t\t// Run effects for changed keys\n\t\t\tawait effectsManager.runEffects(state.changedKeys);\n\n\t\t\t// Copy changed keys for constraint evaluation before clearing\n\t\t\tconst keysForConstraints = new Set(state.changedKeys);\n\n\t\t\t// Clear changed keys\n\t\t\tstate.changedKeys.clear();\n\n\t\t\t// Evaluate constraints (pass changed keys for incremental evaluation)\n\t\t\tconst currentRequirements = await constraintsManager.evaluate(keysForConstraints);\n\t\t\tconst currentSet = new RequirementSet();\n\t\t\tfor (const req of currentRequirements) {\n\t\t\t\tcurrentSet.add(req);\n\t\t\t\tpluginManager.emitRequirementCreated(req);\n\t\t\t}\n\n\t\t\t// Diff with previous requirements\n\t\t\tconst { added, removed } = currentSet.diff(state.previousRequirements);\n\n\t\t\t// Cancel resolvers for removed requirements\n\t\t\tfor (const req of removed) {\n\t\t\t\tresolversManager.cancel(req.id);\n\t\t\t}\n\n\t\t\t// Start resolvers for new requirements\n\t\t\tfor (const req of added) {\n\t\t\t\tresolversManager.resolve(req);\n\t\t\t}\n\n\t\t\t// Update previous requirements\n\t\t\tstate.previousRequirements = currentSet;\n\n\t\t\t// Build reconcile result\n\t\t\tconst inflightInfo = resolversManager.getInflightInfo();\n\t\t\tconst result: ReconcileResult = {\n\t\t\t\tunmet: currentRequirements.filter((r) => !resolversManager.isResolving(r.id)),\n\t\t\t\tinflight: inflightInfo,\n\t\t\t\tcompleted: [], // Completed resolvers are tracked separately via onComplete callback\n\t\t\t\tcanceled: removed.map((r) => ({\n\t\t\t\t\tid: r.id,\n\t\t\t\t\tresolverId: inflightInfo.find((i) => i.id === r.id)?.resolverId ?? \"unknown\",\n\t\t\t\t})),\n\t\t\t};\n\n\t\t\tpluginManager.emitReconcileEnd(result);\n\n\t\t\t// Mark system as ready after first successful reconcile\n\t\t\tif (!state.isReady) {\n\t\t\t\tstate.isReady = true;\n\t\t\t\tif (state.readyResolve) {\n\t\t\t\t\tstate.readyResolve();\n\t\t\t\t\tstate.readyResolve = null;\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tstate.isReconciling = false;\n\n\t\t\t// Schedule next reconcile BEFORE notifying settlement change,\n\t\t\t// so listeners never see a brief isSettled=true flash when\n\t\t\t// more changes are pending.\n\t\t\tif (state.changedKeys.size > 0) {\n\t\t\t\tscheduleReconcile();\n\t\t\t} else if (!state.reconcileScheduled) {\n\t\t\t\t// System has settled — reset depth counter\n\t\t\t\treconcileDepth = 0;\n\t\t\t}\n\n\t\t\tnotifySettlementChange();\n\t\t}\n\t}\n\n\t// Create typed derive accessor using a Proxy\n\tconst deriveAccessor = new Proxy({} as Record<string, unknown>, {\n\t\tget(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\t\t\treturn derivationsManager.get(prop as keyof DerivationsDef<S>);\n\t\t},\n\t\thas(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\t\t\treturn prop in mergedDerive;\n\t\t},\n\t\townKeys() {\n\t\t\treturn Object.keys(mergedDerive);\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\t\t\tif (prop in mergedDerive) {\n\t\t\t\treturn { configurable: true, enumerable: true };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n\n\t// Create typed events accessor using a Proxy\n\t// This provides system.events.eventName(payload) syntax\n\tconst eventsAccessor = new Proxy({} as Record<string, (payload?: Record<string, unknown>) => void>, {\n\t\tget(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\t\t\t// Return a function that dispatches the event\n\t\t\treturn (payload?: Record<string, unknown>) => {\n\t\t\t\tconst handler = mergedEvents[prop];\n\t\t\t\tif (handler) {\n\t\t\t\t\tdispatchDepth++;\n\t\t\t\t\tif (snapshotEventNames === null || snapshotEventNames.has(prop)) {\n\t\t\t\t\t\tshouldTakeSnapshot = true;\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tstore.batch(() => {\n\t\t\t\t\t\t\thandler(facts, { type: prop, ...payload });\n\t\t\t\t\t\t});\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tdispatchDepth--;\n\t\t\t\t\t}\n\t\t\t\t} else if (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] Unknown event type \"${prop}\". ` +\n\t\t\t\t\t\t\t`No handler is registered for this event. ` +\n\t\t\t\t\t\t\t`Available events: ${Object.keys(mergedEvents).join(\", \") || \"(none)\"}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\thas(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\t\t\treturn prop in mergedEvents;\n\t\t},\n\t\townKeys() {\n\t\t\treturn Object.keys(mergedEvents);\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\t// Prototype pollution protection\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\t\t\tif (prop in mergedEvents) {\n\t\t\t\treturn { configurable: true, enumerable: true };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n\n\t// Create the system interface\n\t// biome-ignore lint/suspicious/noExplicitAny: Engine uses flat schema internally, public API uses ModuleSchema\n\tconst system: System<any> = {\n\t\tfacts,\n\t\tdebug: timeTravelManager.isEnabled ? timeTravelManager : null,\n\t\tderive: deriveAccessor,\n\t\tevents: eventsAccessor,\n\t\tconstraints: {\n\t\t\tdisable: (id: string) => constraintsManager.disable(id),\n\t\t\tenable: (id: string) => constraintsManager.enable(id),\n\t\t},\n\t\teffects: {\n\t\t\tdisable: (id: string) => effectsManager.disable(id),\n\t\t\tenable: (id: string) => effectsManager.enable(id),\n\t\t\tisEnabled: (id: string) => effectsManager.isEnabled(id),\n\t\t},\n\n\t\tstart(): void {\n\t\t\tif (state.isRunning) return;\n\t\t\tstate.isRunning = true;\n\n\t\t\t// Mark as initializing to suppress reconciliation during module init\n\t\t\tstate.isInitializing = true;\n\n\t\t\t// Initialize modules (reconciliation is suppressed during this phase)\n\t\t\tfor (const module of config.modules) {\n\t\t\t\tif (module.init) {\n\t\t\t\t\tstore.batch(() => {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Engine internal type coercion\n\t\t\t\t\t\tmodule.init!(facts as any);\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Call module hooks\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Engine internal type coercion\n\t\t\t\tmodule.hooks?.onStart?.(system as any);\n\t\t\t}\n\n\t\t\t// Apply initialFacts/hydrate via callback (still in init phase)\n\t\t\t// This ensures initialFacts are applied AFTER module init but BEFORE reconcile\n\t\t\tif (config.onAfterModuleInit) {\n\t\t\t\tstore.batch(() => {\n\t\t\t\t\tconfig.onAfterModuleInit!();\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Mark initialization complete\n\t\t\tstate.isInitializing = false;\n\t\t\tstate.isInitialized = true;\n\n\t\t\t// Emit start event\n\t\t\tpluginManager.emitStart(system);\n\n\t\t\t// Initial reconcile (now that all modules are initialized)\n\t\t\tscheduleReconcile();\n\t\t},\n\n\t\tstop(): void {\n\t\t\tif (!state.isRunning) return;\n\t\t\tstate.isRunning = false;\n\n\t\t\t// Cancel all resolvers\n\t\t\tresolversManager.cancelAll();\n\n\t\t\t// Run all effect cleanups\n\t\t\teffectsManager.cleanupAll();\n\n\t\t\t// Call module hooks\n\t\t\tfor (const module of config.modules) {\n\t\t\t\tmodule.hooks?.onStop?.(system);\n\t\t\t}\n\n\t\t\t// Emit stop event\n\t\t\tpluginManager.emitStop(system);\n\t\t},\n\n\t\tdestroy(): void {\n\t\t\tthis.stop();\n\t\t\tstate.isDestroyed = true;\n\t\t\tsettlementListeners.clear();\n\t\t\ttimeTravelListeners.clear();\n\t\t\tpluginManager.emitDestroy(system);\n\t\t},\n\n\t\tdispatch(event: SystemEvent): void {\n\t\t\tif (BLOCKED_PROPS.has(event.type)) return;\n\t\t\tconst handler = mergedEvents[event.type];\n\t\t\tif (handler) {\n\t\t\t\tdispatchDepth++;\n\t\t\t\tif (snapshotEventNames === null || snapshotEventNames.has(event.type)) {\n\t\t\t\t\tshouldTakeSnapshot = true;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tstore.batch(() => {\n\t\t\t\t\t\thandler(facts, event);\n\t\t\t\t\t});\n\t\t\t\t} finally {\n\t\t\t\t\tdispatchDepth--;\n\t\t\t\t}\n\t\t\t} else if (process.env.NODE_ENV !== \"production\") {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] Unknown event type \"${event.type}\". ` +\n\t\t\t\t\t\t`No handler is registered for this event. ` +\n\t\t\t\t\t\t`Available events: ${Object.keys(mergedEvents).join(\", \") || \"(none)\"}`,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\n\t\tread<T = unknown>(derivationId: string): T {\n\t\t\treturn derivationsManager.get(derivationId as keyof DerivationsDef<S>) as T;\n\t\t},\n\n\t\tsubscribe(ids: string[], listener: () => void): () => void {\n\t\t\tconst derivationIds: string[] = [];\n\t\t\tconst factKeys: string[] = [];\n\n\t\t\tfor (const id of ids) {\n\t\t\t\tif (id in mergedDerive) {\n\t\t\t\t\tderivationIds.push(id);\n\t\t\t\t} else if (id in mergedSchema) {\n\t\t\t\t\tfactKeys.push(id);\n\t\t\t\t} else if (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(`[Directive] subscribe: unknown key \"${id}\"`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst unsubs: Array<() => void> = [];\n\t\t\tif (derivationIds.length > 0) {\n\t\t\t\tunsubs.push(\n\t\t\t\t\tderivationsManager.subscribe(\n\t\t\t\t\t\tderivationIds as Array<keyof DerivationsDef<S>>,\n\t\t\t\t\t\tlistener,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (factKeys.length > 0) {\n\t\t\t\tunsubs.push(store.subscribe(factKeys as Array<keyof InferSchema<S>>, listener));\n\t\t\t}\n\n\t\t\treturn () => {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t};\n\t\t},\n\n\t\twatch<T = unknown>(\n\t\t\tid: string,\n\t\t\tcallback: (newValue: T, previousValue: T | undefined) => void,\n\t\t\toptions?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n\t\t): () => void {\n\t\t\tconst isEqual = options?.equalityFn\n\t\t\t\t? (a: T, b: T | undefined) => options.equalityFn!(a, b)\n\t\t\t\t: (a: T, b: T | undefined) => Object.is(a, b);\n\n\t\t\tif (id in mergedDerive) {\n\t\t\t\t// Derivation path\n\t\t\t\tlet previousValue: T | undefined = derivationsManager.get(\n\t\t\t\t\tid as keyof DerivationsDef<S>,\n\t\t\t\t) as T | undefined;\n\n\t\t\t\treturn derivationsManager.subscribe(\n\t\t\t\t\t[id as keyof DerivationsDef<S>],\n\t\t\t\t\t() => {\n\t\t\t\t\t\tconst newValue = derivationsManager.get(id as keyof DerivationsDef<S>) as T;\n\t\t\t\t\t\tif (!isEqual(newValue, previousValue)) {\n\t\t\t\t\t\t\tconst oldValue = previousValue;\n\t\t\t\t\t\t\tpreviousValue = newValue;\n\t\t\t\t\t\t\tcallback(newValue, oldValue);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Fact path\n\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\tif (!(id in mergedSchema)) {\n\t\t\t\t\tconsole.warn(`[Directive] watch: unknown key \"${id}\"`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet prev = store.get(id as keyof InferSchema<S>) as T | undefined;\n\t\t\treturn store.subscribe([id as keyof InferSchema<S>], () => {\n\t\t\t\tconst next = store.get(id as keyof InferSchema<S>) as T;\n\t\t\t\tif (!isEqual(next, prev)) {\n\t\t\t\t\tconst old = prev;\n\t\t\t\t\tprev = next;\n\t\t\t\t\tcallback(next, old);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\twhen(\n\t\t\tpredicate: (facts: Record<string, unknown>) => boolean,\n\t\t\toptions?: { timeout?: number },\n\t\t): Promise<void> {\n\t\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\t\t// Check immediately\n\t\t\t\tconst factsObj = store.toObject();\n\t\t\t\tif (predicate(factsObj)) {\n\t\t\t\t\tresolve();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet unsub: (() => void) | undefined;\n\t\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\n\t\t\t\tconst cleanup = () => {\n\t\t\t\t\tunsub?.();\n\t\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\t};\n\n\t\t\t\t// Subscribe to all fact changes\n\t\t\t\tunsub = store.subscribeAll(() => {\n\t\t\t\t\tconst current = store.toObject();\n\t\t\t\t\tif (predicate(current)) {\n\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Timeout\n\t\t\t\tif (options?.timeout !== undefined && options.timeout > 0) {\n\t\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\treject(new Error(`[Directive] when: timed out after ${options.timeout}ms`));\n\t\t\t\t\t}, options.timeout);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\tinspect(): SystemInspection {\n\t\t\treturn {\n\t\t\t\tunmet: state.previousRequirements.all(),\n\t\t\t\tinflight: resolversManager.getInflightInfo(),\n\t\t\t\tconstraints: constraintsManager.getAllStates().map((s) => ({\n\t\t\t\t\tid: s.id,\n\t\t\t\t\tactive: s.lastResult ?? false,\n\t\t\t\t\tpriority: s.priority,\n\t\t\t\t})),\n\t\t\t\tresolvers: Object.fromEntries(\n\t\t\t\t\tresolversManager.getInflight().map((id) => [id, resolversManager.getStatus(id)]),\n\t\t\t\t),\n\t\t\t};\n\t\t},\n\n\t\texplain(requirementId: string): string | null {\n\t\t\t// Find the requirement in current unmet requirements\n\t\t\tconst requirements = state.previousRequirements.all();\n\t\t\tconst req = requirements.find((r) => r.id === requirementId);\n\n\t\t\tif (!req) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst constraintState = constraintsManager.getState(req.fromConstraint);\n\t\t\tconst resolverStatus = resolversManager.getStatus(requirementId);\n\n\t\t\t// Get relevant facts by looking at the constraint's last known state\n\t\t\tconst relevantFacts: Record<string, unknown> = {};\n\t\t\tconst factsSnapshot = store.toObject();\n\n\t\t\t// Include all facts for now (could be optimized with dependency tracking)\n\t\t\tfor (const [key, value] of Object.entries(factsSnapshot)) {\n\t\t\t\trelevantFacts[key] = value;\n\t\t\t}\n\n\t\t\tconst lines: string[] = [\n\t\t\t\t`Requirement \"${req.requirement.type}\" (id: ${req.id})`,\n\t\t\t\t`├─ Produced by constraint: ${req.fromConstraint}`,\n\t\t\t\t`├─ Constraint priority: ${constraintState?.priority ?? 0}`,\n\t\t\t\t`├─ Constraint active: ${constraintState?.lastResult ?? \"unknown\"}`,\n\t\t\t\t`├─ Resolver status: ${resolverStatus.state}`,\n\t\t\t];\n\n\t\t\t// Add requirement details\n\t\t\tconst reqDetails = Object.entries(req.requirement)\n\t\t\t\t.filter(([k]) => k !== \"type\")\n\t\t\t\t.map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n\t\t\t\t.join(\", \");\n\t\t\tif (reqDetails) {\n\t\t\t\tlines.push(`├─ Requirement payload: { ${reqDetails} }`);\n\t\t\t}\n\n\t\t\t// Add relevant facts (limit to prevent huge output)\n\t\t\tconst factEntries = Object.entries(relevantFacts).slice(0, 10);\n\t\t\tif (factEntries.length > 0) {\n\t\t\t\tlines.push(`└─ Relevant facts:`);\n\t\t\t\tfactEntries.forEach(([k, v], i) => {\n\t\t\t\t\tconst prefix = i === factEntries.length - 1 ? \" └─\" : \" ├─\";\n\t\t\t\t\tconst valueStr = typeof v === \"object\" ? JSON.stringify(v) : String(v);\n\t\t\t\t\tlines.push(`${prefix} ${k} = ${valueStr.slice(0, 50)}${valueStr.length > 50 ? \"...\" : \"\"}`);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn lines.join(\"\\n\");\n\t\t},\n\n\t\tasync settle(maxWait = 5000): Promise<void> {\n\t\t\tconst startTime = Date.now();\n\n\t\t\t// Use while loop instead of recursion to prevent stack overflow\n\t\t\twhile (true) {\n\t\t\t\t// Wait for any pending microtasks\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 0));\n\n\t\t\t\t// Check if we have inflight resolvers or unmet requirements with resolvers\n\t\t\t\tconst inspection = this.inspect();\n\t\t\t\tconst settled =\n\t\t\t\t\tinspection.inflight.length === 0 &&\n\t\t\t\t\t!state.isReconciling &&\n\t\t\t\t\t!state.reconcileScheduled;\n\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Check timeout\n\t\t\t\tif (Date.now() - startTime > maxWait) {\n\t\t\t\t\tconst details: string[] = [];\n\t\t\t\t\tif (inspection.inflight.length > 0) {\n\t\t\t\t\t\tdetails.push(\n\t\t\t\t\t\t\t`${inspection.inflight.length} resolvers inflight: ${inspection.inflight.map((r) => r.resolverId).join(\", \")}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (state.isReconciling) {\n\t\t\t\t\t\tdetails.push(\"reconciliation in progress\");\n\t\t\t\t\t}\n\t\t\t\t\tif (state.reconcileScheduled) {\n\t\t\t\t\t\tdetails.push(\"reconcile scheduled\");\n\t\t\t\t\t}\n\t\t\t\t\t// Include pending requirements for better debugging\n\t\t\t\t\tconst unmet = state.previousRequirements.all();\n\t\t\t\t\tif (unmet.length > 0) {\n\t\t\t\t\t\tdetails.push(\n\t\t\t\t\t\t\t`${unmet.length} unmet requirements: ${unmet.map((r) => r.requirement.type).join(\", \")}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] settle() timed out after ${maxWait}ms. ${details.join(\"; \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Wait a bit and check again\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 10));\n\t\t\t}\n\t\t},\n\n\t\tgetSnapshot() {\n\t\t\treturn {\n\t\t\t\tfacts: store.toObject(),\n\t\t\t\tversion: 1,\n\t\t\t};\n\t\t},\n\n\t\tgetDistributableSnapshot<T = Record<string, unknown>>(\n\t\t\toptions: {\n\t\t\t\tincludeDerivations?: string[];\n\t\t\t\texcludeDerivations?: string[];\n\t\t\t\tincludeFacts?: string[];\n\t\t\t\tttlSeconds?: number;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t\tincludeVersion?: boolean;\n\t\t\t} = {},\n\t\t): {\n\t\t\tdata: T;\n\t\t\tcreatedAt: number;\n\t\t\texpiresAt?: number;\n\t\t\tversion?: string;\n\t\t\tmetadata?: Record<string, unknown>;\n\t\t} {\n\t\t\tconst {\n\t\t\t\tincludeDerivations,\n\t\t\t\texcludeDerivations,\n\t\t\t\tincludeFacts,\n\t\t\t\tttlSeconds,\n\t\t\t\tmetadata,\n\t\t\t\tincludeVersion,\n\t\t\t} = options;\n\n\t\t\tconst data: Record<string, unknown> = {};\n\n\t\t\t// Collect derivation keys to include\n\t\t\tconst allDerivationKeys = Object.keys(mergedDerive);\n\t\t\tlet derivationKeys: string[];\n\n\t\t\tif (includeDerivations) {\n\t\t\t\t// Only include specified derivations\n\t\t\t\tderivationKeys = includeDerivations.filter((k) => allDerivationKeys.includes(k));\n\n\t\t\t\t// Warn about unknown derivation keys in dev mode\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconst unknown = includeDerivations.filter((k) => !allDerivationKeys.includes(k));\n\t\t\t\t\tif (unknown.length > 0) {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[Directive] getDistributableSnapshot: Unknown derivation keys ignored: ${unknown.join(\", \")}. ` +\n\t\t\t\t\t\t\t\t`Available: ${allDerivationKeys.join(\", \") || \"(none)\"}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Include all derivations by default\n\t\t\t\tderivationKeys = allDerivationKeys;\n\t\t\t}\n\n\t\t\t// Apply exclusions\n\t\t\tif (excludeDerivations) {\n\t\t\t\tconst excludeSet = new Set(excludeDerivations);\n\t\t\t\tderivationKeys = derivationKeys.filter((k) => !excludeSet.has(k));\n\t\t\t}\n\n\t\t\t// Read derivation values\n\t\t\tfor (const key of derivationKeys) {\n\t\t\t\ttry {\n\t\t\t\t\tdata[key] = derivationsManager.get(key as keyof DerivationsDef<S>);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Skip derivations that error during computation\n\t\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\t\tconsole.warn(`[Directive] getDistributableSnapshot: Skipping derivation \"${key}\" due to error:`, error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Include specified facts\n\t\t\tif (includeFacts && includeFacts.length > 0) {\n\t\t\t\tconst factsSnapshot = store.toObject();\n\t\t\t\tconst allFactKeys = Object.keys(factsSnapshot);\n\n\t\t\t\t// Warn about unknown fact keys in dev mode\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconst unknown = includeFacts.filter((k) => !(k in factsSnapshot));\n\t\t\t\t\tif (unknown.length > 0) {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[Directive] getDistributableSnapshot: Unknown fact keys ignored: ${unknown.join(\", \")}. ` +\n\t\t\t\t\t\t\t\t`Available: ${allFactKeys.join(\", \") || \"(none)\"}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (const key of includeFacts) {\n\t\t\t\t\tif (key in factsSnapshot) {\n\t\t\t\t\t\tdata[key] = factsSnapshot[key];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Build the snapshot\n\t\t\tconst createdAt = Date.now();\n\t\t\tconst snapshot: {\n\t\t\t\tdata: T;\n\t\t\t\tcreatedAt: number;\n\t\t\t\texpiresAt?: number;\n\t\t\t\tversion?: string;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t} = {\n\t\t\t\tdata: data as T,\n\t\t\t\tcreatedAt,\n\t\t\t};\n\n\t\t\t// Add TTL\n\t\t\tif (ttlSeconds !== undefined && ttlSeconds > 0) {\n\t\t\t\tsnapshot.expiresAt = createdAt + ttlSeconds * 1000;\n\t\t\t}\n\n\t\t\t// Add version hash\n\t\t\tif (includeVersion) {\n\t\t\t\t// Simple version hash based on data content\n\t\t\t\tsnapshot.version = hashObject(data);\n\t\t\t}\n\n\t\t\t// Add metadata\n\t\t\tif (metadata) {\n\t\t\t\tsnapshot.metadata = metadata;\n\t\t\t}\n\n\t\t\treturn snapshot;\n\t\t},\n\n\t\twatchDistributableSnapshot<T = Record<string, unknown>>(\n\t\t\toptions: {\n\t\t\t\tincludeDerivations?: string[];\n\t\t\t\texcludeDerivations?: string[];\n\t\t\t\tincludeFacts?: string[];\n\t\t\t\tttlSeconds?: number;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t\tincludeVersion?: boolean;\n\t\t\t},\n\t\t\tcallback: (snapshot: {\n\t\t\t\tdata: T;\n\t\t\t\tcreatedAt: number;\n\t\t\t\texpiresAt?: number;\n\t\t\t\tversion?: string;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t}) => void,\n\t\t): () => void {\n\t\t\tconst { includeDerivations, excludeDerivations } = options;\n\n\t\t\t// Determine which derivations to watch\n\t\t\tconst allDerivationKeys = Object.keys(mergedDerive);\n\t\t\tlet derivationKeys: string[];\n\n\t\t\tif (includeDerivations) {\n\t\t\t\tderivationKeys = includeDerivations.filter((k) => allDerivationKeys.includes(k));\n\t\t\t} else {\n\t\t\t\tderivationKeys = allDerivationKeys;\n\t\t\t}\n\n\t\t\tif (excludeDerivations) {\n\t\t\t\tconst excludeSet = new Set(excludeDerivations);\n\t\t\t\tderivationKeys = derivationKeys.filter((k) => !excludeSet.has(k));\n\t\t\t}\n\n\t\t\tif (derivationKeys.length === 0) {\n\t\t\t\t// Nothing to watch, return no-op unsubscribe\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\"[Directive] watchDistributableSnapshot: No derivations to watch. \" +\n\t\t\t\t\t\t\t\"Callback will never be called.\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn () => {};\n\t\t\t}\n\n\t\t\t// Get initial snapshot to seed version and ensure derivations are computed\n\t\t\t// (derivations must be computed before subscribing so listeners are called on invalidation)\n\t\t\tconst initialSnapshot = this.getDistributableSnapshot<T>({\n\t\t\t\t...options,\n\t\t\t\tincludeVersion: true,\n\t\t\t});\n\t\t\tlet previousVersion = initialSnapshot.version;\n\n\t\t\t// Subscribe to all watched derivations\n\t\t\treturn derivationsManager.subscribe(\n\t\t\t\tderivationKeys as Array<keyof DerivationsDef<S>>,\n\t\t\t\t() => {\n\t\t\t\t\t// Generate a new snapshot\n\t\t\t\t\tconst snapshot = this.getDistributableSnapshot<T>({\n\t\t\t\t\t\t...options,\n\t\t\t\t\t\t// Always include version for change detection\n\t\t\t\t\t\tincludeVersion: true,\n\t\t\t\t\t});\n\n\t\t\t\t\t// Only call callback if snapshot actually changed\n\t\t\t\t\tif (snapshot.version !== previousVersion) {\n\t\t\t\t\t\tpreviousVersion = snapshot.version;\n\t\t\t\t\t\tcallback(snapshot);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\n\t\trestore(snapshot) {\n\t\t\tif (!snapshot || typeof snapshot !== \"object\") {\n\t\t\t\tthrow new Error(\"[Directive] restore() requires a valid snapshot object\");\n\t\t\t}\n\t\t\tif (!snapshot.facts || typeof snapshot.facts !== \"object\") {\n\t\t\t\tthrow new Error(\"[Directive] restore() snapshot must have a facts object\");\n\t\t\t}\n\n\t\t\t// Security: Validate snapshot for prototype pollution\n\t\t\tif (!isPrototypeSafe(snapshot)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"[Directive] restore() rejected: snapshot contains potentially dangerous keys \" +\n\t\t\t\t\t\t\"(__proto__, constructor, or prototype). This may indicate a prototype pollution attack.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tstore.batch(() => {\n\t\t\t\tfor (const [key, value] of Object.entries(snapshot.facts)) {\n\t\t\t\t\t// Skip dangerous keys (defense in depth)\n\t\t\t\t\tif (BLOCKED_PROPS.has(key)) continue;\n\t\t\t\t\tstore.set(key as keyof InferSchema<S>, value as InferSchema<S>[keyof InferSchema<S>]);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\tonSettledChange(listener: () => void): () => void {\n\t\t\tsettlementListeners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tsettlementListeners.delete(listener);\n\t\t\t};\n\t\t},\n\n\t\tonTimeTravelChange(listener: () => void): () => void {\n\t\t\ttimeTravelListeners.add(listener);\n\t\t\treturn () => {\n\t\t\t\ttimeTravelListeners.delete(listener);\n\t\t\t};\n\t\t},\n\n\t\tbatch(fn: () => void): void {\n\t\t\tstore.batch(fn);\n\t\t},\n\n\t\tget isSettled(): boolean {\n\t\t\tconst inspection = this.inspect();\n\t\t\treturn (\n\t\t\t\tinspection.inflight.length === 0 &&\n\t\t\t\t!state.isReconciling &&\n\t\t\t\t!state.reconcileScheduled\n\t\t\t);\n\t\t},\n\n\t\tget isRunning(): boolean {\n\t\t\treturn state.isRunning;\n\t\t},\n\n\t\tget isInitialized(): boolean {\n\t\t\treturn state.isInitialized;\n\t\t},\n\n\t\tget isReady(): boolean {\n\t\t\treturn state.isReady;\n\t\t},\n\n\t\twhenReady(): Promise<void> {\n\t\t\t// If already ready, resolve immediately\n\t\t\tif (state.isReady) {\n\t\t\t\treturn Promise.resolve();\n\t\t\t}\n\n\t\t\t// If not running, the promise would never resolve\n\t\t\tif (!state.isRunning) {\n\t\t\t\treturn Promise.reject(\n\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\"[Directive] whenReady() called before start(). \" +\n\t\t\t\t\t\t\"Call system.start() first, then await system.whenReady().\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Create promise if not exists\n\t\t\tif (!state.readyPromise) {\n\t\t\t\tstate.readyPromise = new Promise<void>((resolve) => {\n\t\t\t\t\tstate.readyResolve = resolve;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn state.readyPromise;\n\t\t},\n\t};\n\n\t/**\n\t * Register a new module into a running (or stopped) engine.\n\t * Merges the module's schema, events, derive, effects, constraints, and resolvers\n\t * into the existing engine state, runs init, and triggers reconciliation.\n\t */\n\tfunction registerModule(module: {\n\t\tid: string;\n\t\tschema: Record<string, unknown>;\n\t\trequirements?: Record<string, unknown>;\n\t\tinit?: (facts: unknown) => void;\n\t\tderive?: Record<string, (facts: unknown, derive: unknown) => unknown>;\n\t\tevents?: Record<string, (facts: unknown, event: unknown) => void>;\n\t\teffects?: Record<string, unknown>;\n\t\tconstraints?: Record<string, unknown>;\n\t\tresolvers?: Record<string, unknown>;\n\t\thooks?: { onInit?: (s: unknown) => void; onStart?: (s: unknown) => void; onStop?: (s: unknown) => void; onError?: (e: unknown, ctx: unknown) => void };\n\t\tsnapshotEvents?: string[];\n\t}): void {\n\t\t// Guard: cannot register during reconciliation (would corrupt iteration state)\n\t\tif (state.isReconciling) {\n\t\t\tthrow new Error(\n\t\t\t\t`[Directive] Cannot register module \"${module.id}\" during reconciliation. ` +\n\t\t\t\t`Wait for the current reconciliation cycle to complete.`,\n\t\t\t);\n\t\t}\n\n\t\t// Guard: cannot register on a destroyed system\n\t\tif (state.isDestroyed) {\n\t\t\tthrow new Error(\n\t\t\t\t`[Directive] Cannot register module \"${module.id}\" on a destroyed system.`,\n\t\t\t);\n\t\t}\n\n\t\t// Security: validate keys\n\t\tconst validateKeys = (obj: object | undefined, section: string) => {\n\t\t\tif (!obj) return;\n\t\t\tfor (const key of Object.keys(obj)) {\n\t\t\t\tif (BLOCKED_PROPS.has(key)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Security: Module \"${module.id}\" has dangerous key \"${key}\" in ${section}.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tvalidateKeys(module.schema, \"schema\");\n\t\tvalidateKeys(module.events, \"events\");\n\t\tvalidateKeys(module.derive, \"derive\");\n\t\tvalidateKeys(module.effects, \"effects\");\n\t\tvalidateKeys(module.constraints, \"constraints\");\n\t\tvalidateKeys(module.resolvers, \"resolvers\");\n\n\t\t// Schema collision detection (unconditional — production collision would cause data corruption)\n\t\tfor (const key of Object.keys(module.schema)) {\n\t\t\tif (key in mergedSchema) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Schema collision: Fact \"${key}\" already exists. Cannot register module \"${module.id}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\t// Fact/derivation name collision check (dev-only warning)\n\t\tif (process.env.NODE_ENV !== \"production\" && module.derive) {\n\t\t\tconst existingFactKeys = new Set(Object.keys(mergedSchema));\n\t\t\tfor (const key of Object.keys(module.derive)) {\n\t\t\t\tif (existingFactKeys.has(key)) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] \"${key}\" exists as both a fact and a derivation after registering module \"${module.id}\".`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Update snapshotEventNames BEFORE merging events so we capture pre-merge state\n\t\tif (module.snapshotEvents) {\n\t\t\tif (snapshotEventNames === null) {\n\t\t\t\t// First module with snapshotEvents — initialize the set with all existing event names\n\t\t\t\tsnapshotEventNames = new Set<string>(Object.keys(mergedEvents));\n\t\t\t}\n\t\t\tfor (const eventName of module.snapshotEvents) {\n\t\t\t\tsnapshotEventNames.add(eventName);\n\t\t\t}\n\t\t} else if (snapshotEventNames !== null && module.events) {\n\t\t\t// Filtering is active and this module has no filter — add all its events\n\t\t\tfor (const eventName of Object.keys(module.events)) {\n\t\t\t\tsnapshotEventNames.add(eventName);\n\t\t\t}\n\t\t}\n\n\t\t// Merge into existing engine state\n\t\tObject.assign(mergedSchema, module.schema);\n\t\tif (module.events) Object.assign(mergedEvents, module.events);\n\t\tif (module.derive) {\n\t\t\tObject.assign(mergedDerive, module.derive);\n\t\t\t// Register new derivations with the derivations manager\n\t\t\tderivationsManager.registerDefinitions(module.derive as DerivationsDef<S>);\n\t\t}\n\t\tif (module.effects) {\n\t\t\tObject.assign(mergedEffects, module.effects);\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic module registration\n\t\t\teffectsManager.registerDefinitions(module.effects as any);\n\t\t}\n\t\tif (module.constraints) {\n\t\t\tObject.assign(mergedConstraints, module.constraints);\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic module registration\n\t\t\tconstraintsManager.registerDefinitions(module.constraints as any);\n\t\t}\n\t\tif (module.resolvers) {\n\t\t\tObject.assign(mergedResolvers, module.resolvers);\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic module registration\n\t\t\tresolversManager.registerDefinitions(module.resolvers as any);\n\t\t}\n\n\t\t// Register new schema keys with the facts store\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal dynamic method\n\t\t(store as any).registerKeys(module.schema as Record<string, unknown>);\n\n\t\t// Track the new module in config.modules for hooks\n\t\tconfig.modules.push(module as typeof config.modules[number]);\n\n\t\t// Run init within a batch\n\t\tif (module.init) {\n\t\t\tstore.batch(() => {\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Dynamic module init\n\t\t\t\tmodule.init!(facts as any);\n\t\t\t});\n\t\t}\n\n\t\t// Call lifecycle hooks\n\t\tmodule.hooks?.onInit?.(system);\n\t\tif (state.isRunning) {\n\t\t\tmodule.hooks?.onStart?.(system);\n\t\t\t// Trigger reconciliation to evaluate new constraints\n\t\t\tscheduleReconcile();\n\t\t}\n\t}\n\n\t// Attach registerModule to system\n\t(system as unknown as Record<string, unknown>).registerModule = registerModule;\n\n\t// Initialize plugins\n\tpluginManager.emitInit(system);\n\n\t// Call module init hooks\n\tfor (const module of config.modules) {\n\t\tmodule.hooks?.onInit?.(system);\n\t}\n\n\treturn system;\n}\n","/**\n * System - The top-level API for creating a Directive runtime\n *\n * A system combines modules with plugins and configuration.\n * Modules are passed as an object with namespaced access:\n *\n * @example\n * ```typescript\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n *\n * system.facts.auth.token // Namespaced facts\n * system.derive.data.userCount // Namespaced derivations\n * system.events.auth.login() // Namespaced events\n * ```\n */\n\nimport { createEngine } from \"./engine.js\";\nimport { isPrototypeSafe } from \"../utils/utils.js\";\nimport type {\n\tModuleDef,\n\tModuleSchema,\n\tModulesMap,\n\tNamespacedSystem,\n\tCreateSystemOptionsNamed,\n\tCreateSystemOptionsSingle,\n\tSingleModuleSystem,\n} from \"./types.js\";\n\n// ============================================================================\n// Blocked Properties (Security)\n// ============================================================================\n\nconst BLOCKED_PROPS = Object.freeze(\n\tnew Set([\"__proto__\", \"constructor\", \"prototype\"]),\n);\n\n/** Namespace separator for internal key prefixing (e.g., \"auth::token\") */\nconst SEPARATOR = \"::\";\n\n// ============================================================================\n// Topological Sort for Module Dependencies\n// ============================================================================\n\n/**\n * Perform topological sort on modules based on crossModuleDeps.\n * Returns module namespaces in dependency order (dependencies first).\n *\n * @throws Error if circular dependency detected\n */\nfunction topologicalSort<Modules extends ModulesMap>(\n\tmodulesMap: Modules,\n): Array<keyof Modules & string> {\n\tconst namespaces = Object.keys(modulesMap) as Array<keyof Modules & string>;\n\tconst visited = new Set<string>();\n\tconst visiting = new Set<string>(); // For cycle detection\n\tconst result: Array<keyof Modules & string> = [];\n\tconst path: string[] = []; // Reuse array to avoid O(n²) memory\n\n\tfunction visit(namespace: string): void {\n\t\tif (visited.has(namespace)) return;\n\n\t\t// Cycle detection\n\t\tif (visiting.has(namespace)) {\n\t\t\tconst cycleStart = path.indexOf(namespace);\n\t\t\tconst cycle = [...path.slice(cycleStart), namespace].join(\" → \");\n\t\t\tthrow new Error(\n\t\t\t\t`[Directive] Circular dependency detected: ${cycle}. ` +\n\t\t\t\t`Modules cannot have circular crossModuleDeps. ` +\n\t\t\t\t`Break the cycle by removing one of the cross-module references.`,\n\t\t\t);\n\t\t}\n\n\t\tvisiting.add(namespace);\n\t\tpath.push(namespace);\n\n\t\t// Visit dependencies first\n\t\tconst mod = modulesMap[namespace];\n\t\tif (mod?.crossModuleDeps) {\n\t\t\tfor (const depNamespace of Object.keys(mod.crossModuleDeps)) {\n\t\t\t\tif (namespaces.includes(depNamespace as keyof Modules & string)) {\n\t\t\t\t\tvisit(depNamespace);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpath.pop();\n\t\tvisiting.delete(namespace);\n\t\tvisited.add(namespace);\n\t\tresult.push(namespace as keyof Modules & string);\n\t}\n\n\tfor (const namespace of namespaces) {\n\t\tvisit(namespace);\n\t}\n\n\treturn result;\n}\n\n// ============================================================================\n// Proxy Cache (Performance)\n// ============================================================================\n\n/**\n * WeakMap to cache module facts proxies. Keyed by the facts store object.\n * Inner map is keyed by namespace string.\n */\nconst moduleFactsProxyCache = new WeakMap<\n\tRecord<string, unknown>,\n\tMap<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache namespaced facts proxies.\n */\nconst namespacedFactsProxyCache = new WeakMap<\n\tRecord<string, unknown>,\n\tRecord<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache namespaced derive proxies.\n */\nconst namespacedDeriveProxyCache = new WeakMap<\n\tRecord<string, unknown>,\n\tRecord<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache module derive proxies.\n */\nconst moduleDeriveProxyCache = new WeakMap<\n\tRecord<string, unknown>,\n\tMap<string, Record<string, unknown>>\n>();\n\n// ============================================================================\n// createSystem\n// ============================================================================\n\n/**\n * Create a Directive system.\n *\n * Supports two modes:\n * - **Single module**: Use `module` prop for direct access without namespace\n * - **Multiple modules**: Use `modules` prop for namespaced access\n *\n * @example Single module (direct access)\n * ```ts\n * const system = createSystem({ module: counterModule });\n * system.facts.count // Direct access\n * system.events.increment() // Direct events\n * ```\n *\n * @example Multiple modules (namespaced access)\n * ```ts\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n * system.facts.auth.token // Namespaced access\n * system.events.auth.login() // Namespaced events\n * ```\n */\nexport function createSystem<S extends ModuleSchema>(\n\toptions: CreateSystemOptionsSingle<S>,\n): SingleModuleSystem<S>;\nexport function createSystem<const Modules extends ModulesMap>(\n\toptions: CreateSystemOptionsNamed<Modules>,\n): NamespacedSystem<Modules>;\nexport function createSystem<S extends ModuleSchema, Modules extends ModulesMap>(\n\toptions: CreateSystemOptionsSingle<S> | CreateSystemOptionsNamed<Modules>,\n): SingleModuleSystem<S> | NamespacedSystem<Modules> {\n\t// Single module mode (module prop)\n\tif (\"module\" in options) {\n\t\tif (!options.module) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[Directive] createSystem requires a module. Got: \" + typeof options.module,\n\t\t\t);\n\t\t}\n\t\treturn createSingleModuleSystem(options as CreateSystemOptionsSingle<S>) as SingleModuleSystem<S>;\n\t}\n\n\t// Namespaced mode (modules prop)\n\tconst namedOptions = options as CreateSystemOptionsNamed<Modules>;\n\n\t// Validate not an array\n\tif (Array.isArray(namedOptions.modules)) {\n\t\tthrow new Error(\n\t\t\t`[Directive] createSystem expects modules as an object, not an array.\\n\\n` +\n\t\t\t`Instead of:\\n` +\n\t\t\t` createSystem({ modules: [authModule, dataModule] })\\n\\n` +\n\t\t\t`Use:\\n` +\n\t\t\t` createSystem({ modules: { auth: authModule, data: dataModule } })\\n\\n` +\n\t\t\t`Or for a single module:\\n` +\n\t\t\t` createSystem({ module: counterModule })`,\n\t\t);\n\t}\n\n\treturn createNamespacedSystem(namedOptions) as NamespacedSystem<Modules>;\n}\n\n// ============================================================================\n// Internal Implementation\n// ============================================================================\n\nfunction createNamespacedSystem<Modules extends ModulesMap>(\n\toptions: CreateSystemOptionsNamed<Modules>,\n): NamespacedSystem<Modules> {\n\tconst modulesMap = options.modules;\n\tconst moduleNamespaces = new Set(Object.keys(modulesMap));\n\n\t// Build snapshot module filter set (null = all modules snapshot)\n\tconst snapshotModulesSet = options.debug?.snapshotModules\n\t\t? new Set(options.debug.snapshotModules)\n\t\t: null;\n\n\t// Validate tickMs if provided\n\tif (options.tickMs !== undefined && options.tickMs <= 0) {\n\t\tthrow new Error(\"[Directive] tickMs must be a positive number\");\n\t}\n\n\t// Dev-mode: Validate crossModuleDeps reference existing modules\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tfor (const [namespace, mod] of Object.entries(modulesMap)) {\n\t\t\tif (mod.crossModuleDeps) {\n\t\t\t\tfor (const depNamespace of Object.keys(mod.crossModuleDeps)) {\n\t\t\t\t\tif (depNamespace === namespace) {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[Directive] Module \"${namespace}\" references itself in crossModuleDeps. ` +\n\t\t\t\t\t\t\t`Use \"facts.self\" to access own module's facts instead.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (!moduleNamespaces.has(depNamespace)) {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[Directive] Module \"${namespace}\" declares crossModuleDeps.${depNamespace}, ` +\n\t\t\t\t\t\t\t`but no module with namespace \"${depNamespace}\" exists in the system. ` +\n\t\t\t\t\t\t\t`Available modules: ${[...moduleNamespaces].join(\", \")}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Dev-mode: Validate snapshotModules references existing modules\n\tif (process.env.NODE_ENV !== \"production\" && options.debug?.snapshotModules) {\n\t\tfor (const name of options.debug.snapshotModules) {\n\t\t\tif (!moduleNamespaces.has(name)) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] debug.snapshotModules entry \"${name}\" doesn't match any module. ` +\n\t\t\t\t\t`Available modules: ${[...moduleNamespaces].join(\", \")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Determine module initialization order\n\tlet orderedNamespaces: Array<keyof Modules & string>;\n\tconst initOrder = options.initOrder ?? \"auto\";\n\n\tif (Array.isArray(initOrder)) {\n\t\t// Explicit order provided - validate it includes all modules\n\t\tconst explicitOrder = initOrder as Array<keyof Modules & string>;\n\t\tconst missingModules = Object.keys(modulesMap).filter(\n\t\t\t(ns) => !explicitOrder.includes(ns as keyof Modules & string),\n\t\t);\n\t\tif (missingModules.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`[Directive] initOrder is missing modules: ${missingModules.join(\", \")}. ` +\n\t\t\t\t`All modules must be included in the explicit order.`,\n\t\t\t);\n\t\t}\n\t\torderedNamespaces = explicitOrder;\n\t} else if (initOrder === \"declaration\") {\n\t\t// Use object key order (current behavior)\n\t\torderedNamespaces = Object.keys(modulesMap) as Array<keyof Modules & string>;\n\t} else {\n\t\t// \"auto\" - use topological sort based on crossModuleDeps\n\t\torderedNamespaces = topologicalSort(modulesMap);\n\t}\n\n\t// Apply zero-config defaults if enabled\n\tlet debug = options.debug;\n\tlet errorBoundary = options.errorBoundary;\n\n\tif (options.zeroConfig) {\n\t\tconst isDev = process.env.NODE_ENV !== \"production\";\n\n\t\tdebug = {\n\t\t\ttimeTravel: isDev,\n\t\t\tmaxSnapshots: 100,\n\t\t\t...options.debug,\n\t\t};\n\n\t\terrorBoundary = {\n\t\t\tonConstraintError: \"skip\",\n\t\t\tonResolverError: \"skip\",\n\t\t\tonEffectError: \"skip\",\n\t\t\tonDerivationError: \"skip\",\n\t\t\t...options.errorBoundary,\n\t\t};\n\t}\n\n\t// Validate module names and schema keys don't contain the separator\n\tfor (const namespace of Object.keys(modulesMap)) {\n\t\tif (namespace.includes(SEPARATOR)) {\n\t\t\tthrow new Error(\n\t\t\t\t`[Directive] Module name \"${namespace}\" contains the reserved separator \"${SEPARATOR}\". ` +\n\t\t\t\t`Module names cannot contain \"${SEPARATOR}\".`,\n\t\t\t);\n\t\t}\n\t\tconst mod = modulesMap[namespace];\n\t\tif (mod) {\n\t\t\tfor (const key of Object.keys(mod.schema.facts)) {\n\t\t\t\tif (key.includes(SEPARATOR)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Schema key \"${key}\" in module \"${namespace}\" contains the reserved separator \"${SEPARATOR}\". ` +\n\t\t\t\t\t\t`Schema keys cannot contain \"${SEPARATOR}\".`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Transform modules to flat format with prefixed keys\n\t// auth.token → auth::token internally\n\t// Process in dependency order (determined above)\n\tconst flatModules: Array<ModuleDef<ModuleSchema>> = [];\n\n\tfor (const namespace of orderedNamespaces) {\n\t\tconst mod = modulesMap[namespace];\n\t\tif (!mod) continue; // TypeScript guard - should never happen\n\t\t// Compute cross-module deps info once per module (used by derive, constraints, effects)\n\t\tconst hasCrossModuleDeps = mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0;\n\t\tconst depNamespaces = hasCrossModuleDeps ? Object.keys(mod.crossModuleDeps!) : [];\n\n\t\t// Prefix all fact keys with namespace\n\t\tconst prefixedFacts: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(mod.schema.facts)) {\n\t\t\tprefixedFacts[`${namespace}${SEPARATOR}${key}`] = value;\n\t\t}\n\n\t\t// Prefix all derivation keys with namespace\n\t\tconst prefixedDerivations: Record<string, unknown> = {};\n\t\tif (mod.schema.derivations) {\n\t\t\tfor (const [key, value] of Object.entries(mod.schema.derivations)) {\n\t\t\t\tprefixedDerivations[`${namespace}${SEPARATOR}${key}`] = value;\n\t\t\t}\n\t\t}\n\n\t\t// Prefix all event keys with namespace\n\t\tconst prefixedEvents: Record<string, unknown> = {};\n\t\tif (mod.schema.events) {\n\t\t\tfor (const [key, value] of Object.entries(mod.schema.events)) {\n\t\t\t\tprefixedEvents[`${namespace}${SEPARATOR}${key}`] = value;\n\t\t\t}\n\t\t}\n\n\t\t// Transform init to use prefixed keys\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Facts proxy type coercion\n\t\tconst prefixedInit = mod.init\n\t\t\t? (facts: any) => {\n\t\t\t\t\t// Create a proxy that translates unprefixed keys to prefixed\n\t\t\t\t\tconst moduleFactsProxy = createModuleFactsProxy(facts, namespace);\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Module init type coercion\n\t\t\t\t\t(mod.init as any)(moduleFactsProxy);\n\t\t\t\t}\n\t\t\t: undefined;\n\n\t\t// Transform derive functions to use prefixed keys\n\t\tconst prefixedDerive: Record<string, (facts: unknown, derive: unknown) => unknown> = {};\n\t\tif (mod.derive) {\n\t\t\tfor (const [key, fn] of Object.entries(mod.derive)) {\n\t\t\t\tprefixedDerive[`${namespace}${SEPARATOR}${key}`] = (facts: unknown, derive: unknown) => {\n\t\t\t\t\t// Use cross-module proxy (facts.self + facts.{dep}) if crossModuleDeps is defined\n\t\t\t\t\t// Otherwise use flat access to own module only\n\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t// Derive proxy stays scoped to own module\n\t\t\t\t\tconst deriveProxy = createModuleDeriveProxy(derive as Record<string, unknown>, namespace);\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Derive function type coercion\n\t\t\t\t\treturn (fn as any)(factsProxy, deriveProxy);\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Transform event handlers to use prefixed keys\n\t\tconst prefixedEventHandlers: Record<string, (facts: unknown, event: unknown) => void> = {};\n\t\tif (mod.events) {\n\t\t\tfor (const [key, handler] of Object.entries(mod.events)) {\n\t\t\t\tprefixedEventHandlers[`${namespace}${SEPARATOR}${key}`] = (facts: unknown, event: unknown) => {\n\t\t\t\t\tconst moduleFactsProxy = createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Event handler type coercion\n\t\t\t\t\t(handler as any)(moduleFactsProxy, event);\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Transform constraints to use namespaced facts proxy\n\t\tconst prefixedConstraints: Record<string, unknown> = {};\n\t\tif (mod.constraints) {\n\t\t\tfor (const [key, constraint] of Object.entries(mod.constraints)) {\n\t\t\t\tconst constraintDef = constraint as {\n\t\t\t\t\twhen: (facts: unknown) => boolean | Promise<boolean>;\n\t\t\t\t\trequire: unknown | ((facts: unknown) => unknown);\n\t\t\t\t\tpriority?: number;\n\t\t\t\t\tasync?: boolean;\n\t\t\t\t\ttimeout?: number;\n\t\t\t\t\tdeps?: string[];\n\t\t\t\t};\n\n\t\t\t\tprefixedConstraints[`${namespace}${SEPARATOR}${key}`] = {\n\t\t\t\t\t...constraintDef,\n\t\t\t\t\t// Transform deps to use prefixed keys\n\t\t\t\t\tdeps: constraintDef.deps?.map((dep) => `${namespace}${SEPARATOR}${dep}`),\n\t\t\t\t\twhen: (facts: unknown) => {\n\t\t\t\t\t\t// Use cross-module proxy (facts.self + facts.{dep}) if crossModuleDeps is defined\n\t\t\t\t\t\t// Otherwise use module-scoped proxy for direct access (facts.key → namespace::key)\n\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\treturn constraintDef.when(factsProxy);\n\t\t\t\t\t},\n\t\t\t\t\trequire: typeof constraintDef.require === \"function\"\n\t\t\t\t\t\t? (facts: unknown) => {\n\t\t\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\t\t\treturn (constraintDef.require as (facts: unknown) => unknown)(factsProxy);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: constraintDef.require,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Transform resolvers to use namespaced facts proxy\n\t\tconst prefixedResolvers: Record<string, unknown> = {};\n\t\tif (mod.resolvers) {\n\t\t\tfor (const [key, resolver] of Object.entries(mod.resolvers)) {\n\t\t\t\tconst resolverDef = resolver as {\n\t\t\t\t\trequirement: string;\n\t\t\t\t\tresolve: (req: unknown, ctx: { facts: unknown; signal: AbortSignal }) => Promise<void>;\n\t\t\t\t\tkey?: (req: unknown) => string;\n\t\t\t\t\tretry?: unknown;\n\t\t\t\t\ttimeout?: number;\n\t\t\t\t};\n\n\t\t\t\tprefixedResolvers[`${namespace}${SEPARATOR}${key}`] = {\n\t\t\t\t\t...resolverDef,\n\t\t\t\t\tresolve: async (req: unknown, ctx: { facts: unknown; signal: AbortSignal }) => {\n\t\t\t\t\t\tconst namespacedFacts = createNamespacedFactsProxy(ctx.facts as Record<string, unknown>, modulesMap, () => Object.keys(modulesMap));\n\t\t\t\t\t\tawait resolverDef.resolve(req, {\n\t\t\t\t\t\t\tfacts: namespacedFacts[namespace],\n\t\t\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Transform effects to use namespaced facts proxy\n\t\tconst prefixedEffects: Record<string, unknown> = {};\n\t\tif (mod.effects) {\n\t\t\tfor (const [key, effect] of Object.entries(mod.effects)) {\n\t\t\t\tconst effectDef = effect as {\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Effect run function type\n\t\t\t\t\trun: (facts: any, prev: any) => void | Promise<void>;\n\t\t\t\t\tdeps?: string[];\n\t\t\t\t};\n\n\t\t\t\tprefixedEffects[`${namespace}${SEPARATOR}${key}`] = {\n\t\t\t\t\t...effectDef,\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Effect run function wrapper\n\t\t\t\t\trun: (facts: any, prev: any) => {\n\t\t\t\t\t\t// Use cross-module proxy (facts.self + facts.{dep}) if crossModuleDeps is defined\n\t\t\t\t\t\t// Otherwise use module-scoped proxy for direct access (facts.key → namespace::key)\n\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\tconst prevProxy = prev\n\t\t\t\t\t\t\t? (hasCrossModuleDeps\n\t\t\t\t\t\t\t\t\t? createCrossModuleFactsProxy(prev as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t\t\t: createModuleFactsProxy(prev as Record<string, unknown>, namespace))\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\treturn effectDef.run(factsProxy, prevProxy);\n\t\t\t\t\t},\n\t\t\t\t\t// Transform deps to use prefixed keys\n\t\t\t\t\tdeps: effectDef.deps?.map((dep) => `${namespace}${SEPARATOR}${dep}`),\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tflatModules.push({\n\t\t\tid: mod.id,\n\t\t\tschema: {\n\t\t\t\tfacts: prefixedFacts,\n\t\t\t\tderivations: prefixedDerivations,\n\t\t\t\tevents: prefixedEvents,\n\t\t\t\trequirements: mod.schema.requirements ?? {},\n\t\t\t},\n\t\t\tinit: prefixedInit,\n\t\t\tderive: prefixedDerive,\n\t\t\tevents: prefixedEventHandlers,\n\t\t\teffects: prefixedEffects,\n\t\t\tconstraints: prefixedConstraints,\n\t\t\tresolvers: prefixedResolvers,\n\t\t\thooks: mod.hooks,\n\t\t\tsnapshotEvents: (snapshotModulesSet && !snapshotModulesSet.has(namespace))\n\t\t\t\t? [] // Module excluded from snapshots\n\t\t\t\t: mod.snapshotEvents?.map((e: string) => `${namespace}${SEPARATOR}${e}`),\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Module transformation\n\t\t} as any);\n\t}\n\n\t// Dev-mode warning: tickMs set without tick event handler\n\tif (process.env.NODE_ENV !== \"production\" && options.tickMs && options.tickMs > 0) {\n\t\tconst hasTickHandler = flatModules.some(\n\t\t\t(m) => m.events && Object.keys(m.events).some((k) => k.endsWith(`${SEPARATOR}tick`)),\n\t\t);\n\t\tif (!hasTickHandler) {\n\t\t\tconsole.warn(\n\t\t\t\t`[Directive] tickMs is set to ${options.tickMs}ms but no module defines a \"tick\" event handler.`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Store for hydrated facts (set by hydrate(), applied during init)\n\tlet hydratedFacts: Record<string, Record<string, unknown>> | null = null;\n\n\t// Engine reference (set after creation, used by applyNamespacedFacts)\n\t// biome-ignore lint/suspicious/noExplicitAny: Engine type\n\tlet engine: any = null;\n\n\t/**\n\t * Apply namespaced facts to the engine's flat store.\n\t * Converts { auth: { token: \"x\" } } to { \"auth::token\": \"x\" }\n\t * Includes prototype pollution protection.\n\t */\n\tfunction applyNamespacedFacts(\n\t\tnamespacedFacts: Record<string, Record<string, unknown>>,\n\t): void {\n\t\tfor (const [namespace, facts] of Object.entries(namespacedFacts)) {\n\t\t\t// Skip blocked property names\n\t\t\tif (BLOCKED_PROPS.has(namespace)) {\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] initialFacts/hydrate contains blocked namespace \"${namespace}\". Skipping.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!moduleNamespaces.has(namespace)) {\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] initialFacts/hydrate contains unknown namespace \"${namespace}\". ` +\n\t\t\t\t\t\t`Available modules: ${[...moduleNamespaces].join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Validate facts object for prototype pollution\n\t\t\tif (facts && typeof facts === \"object\" && !isPrototypeSafe(facts)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] initialFacts/hydrate for namespace \"${namespace}\" contains potentially ` +\n\t\t\t\t\t`dangerous keys (__proto__, constructor, or prototype). This may indicate a ` +\n\t\t\t\t\t`prototype pollution attack.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tfor (const [key, value] of Object.entries(facts)) {\n\t\t\t\t// Skip blocked keys\n\t\t\t\tif (BLOCKED_PROPS.has(key)) continue;\n\t\t\t\t(engine.facts as Record<string, unknown>)[`${namespace}${SEPARATOR}${key}`] = value;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create engine with flat modules\n\tengine = createEngine({\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Module format conversion\n\t\tmodules: flatModules.map((mod) => ({\n\t\t\tid: mod.id,\n\t\t\tschema: mod.schema.facts,\n\t\t\trequirements: mod.schema.requirements,\n\t\t\tinit: mod.init,\n\t\t\tderive: mod.derive,\n\t\t\tevents: mod.events,\n\t\t\teffects: mod.effects,\n\t\t\tconstraints: mod.constraints,\n\t\t\tresolvers: mod.resolvers,\n\t\t\thooks: mod.hooks,\n\t\t\tsnapshotEvents: mod.snapshotEvents,\n\t\t})) as any,\n\t\tplugins: options.plugins,\n\t\tdebug,\n\t\terrorBoundary,\n\t\ttickMs: options.tickMs,\n\t\t// Callback to apply initialFacts/hydrate during init phase (after module inits, before reconcile)\n\t\tonAfterModuleInit: () => {\n\t\t\t// Apply initialFacts first\n\t\t\tif (options.initialFacts) {\n\t\t\t\tapplyNamespacedFacts(options.initialFacts as Record<string, Record<string, unknown>>);\n\t\t\t}\n\t\t\t// Apply hydrated facts second (takes precedence)\n\t\t\tif (hydratedFacts) {\n\t\t\t\tapplyNamespacedFacts(hydratedFacts);\n\t\t\t\thydratedFacts = null;\n\t\t\t}\n\t\t},\n\t});\n\n\t// Build namespace → internal keys map (for subscribeModule / wildcard support)\n\tconst namespaceKeysMap = new Map<string, string[]>();\n\tfor (const namespace of Object.keys(modulesMap)) {\n\t\tconst mod = modulesMap[namespace];\n\t\tif (!mod) continue;\n\t\tconst keys: string[] = [];\n\t\tfor (const key of Object.keys(mod.schema.facts)) {\n\t\t\tkeys.push(`${namespace}${SEPARATOR}${key}`);\n\t\t}\n\t\tif (mod.schema.derivations) {\n\t\t\tfor (const key of Object.keys(mod.schema.derivations)) {\n\t\t\t\tkeys.push(`${namespace}${SEPARATOR}${key}`);\n\t\t\t}\n\t\t}\n\t\tnamespaceKeysMap.set(namespace, keys);\n\t}\n\n\t// Cached module names array, shared by all namespaced proxies.\n\t// Set to null on registerModule to lazily recompute.\n\tconst moduleNamesCache: { names: string[] | null } = { names: null };\n\tfunction getModuleNames(): string[] {\n\t\tif (moduleNamesCache.names === null) {\n\t\t\tmoduleNamesCache.names = Object.keys(modulesMap);\n\t\t}\n\t\treturn moduleNamesCache.names;\n\t}\n\n\t// Create namespaced proxies for external access\n\tconst namespacedFactsProxy = createNamespacedFactsProxy(engine.facts as unknown as Record<string, unknown>, modulesMap, getModuleNames);\n\tconst namespacedDeriveProxy = createNamespacedDeriveProxy(engine.derive as unknown as Record<string, unknown>, modulesMap, getModuleNames);\n\tconst namespacedEventsProxy = createNamespacedEventsProxy(engine, modulesMap, getModuleNames);\n\n\t// Build the namespaced system\n\tlet tickInterval: ReturnType<typeof setInterval> | null = null;\n\tconst tickMs = options.tickMs;\n\n\tconst system: NamespacedSystem<Modules> = {\n\t\t_mode: \"namespaced\",\n\t\tfacts: namespacedFactsProxy,\n\t\tdebug: engine.debug,\n\t\tderive: namespacedDeriveProxy,\n\t\tevents: namespacedEventsProxy,\n\t\tconstraints: engine.constraints,\n\t\teffects: engine.effects,\n\n\t\tget isRunning() {\n\t\t\treturn engine.isRunning;\n\t\t},\n\n\t\tget isSettled() {\n\t\t\treturn engine.isSettled;\n\t\t},\n\n\t\tget isInitialized() {\n\t\t\treturn engine.isInitialized;\n\t\t},\n\n\t\tget isReady() {\n\t\t\treturn engine.isReady;\n\t\t},\n\n\t\twhenReady: engine.whenReady.bind(engine),\n\n\t\tasync hydrate(\n\t\t\tloader: () =>\n\t\t\t\t| Promise<Record<string, Record<string, unknown>>>\n\t\t\t\t| Record<string, Record<string, unknown>>,\n\t\t) {\n\t\t\tif (engine.isRunning) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"[Directive] hydrate() must be called before start(). \" +\n\t\t\t\t\t\"The system is already running.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst result = await loader();\n\t\t\tif (result && typeof result === \"object\") {\n\t\t\t\thydratedFacts = result;\n\t\t\t}\n\t\t},\n\n\t\tstart(): void {\n\t\t\t// Engine.start() runs module inits, then applies initialFacts/hydrate via callback\n\t\t\tengine.start();\n\n\t\t\tif (tickMs && tickMs > 0) {\n\t\t\t\t// Find the first module with a tick event and dispatch to it\n\t\t\t\tconst tickEventKey = Object.keys(flatModules[0]?.events ?? {}).find((k) => k.endsWith(`${SEPARATOR}tick`));\n\t\t\t\tif (tickEventKey) {\n\t\t\t\t\ttickInterval = setInterval(() => {\n\t\t\t\t\t\tengine.dispatch({ type: tickEventKey });\n\t\t\t\t\t}, tickMs);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tstop(): void {\n\t\t\tif (tickInterval) {\n\t\t\t\tclearInterval(tickInterval);\n\t\t\t\ttickInterval = null;\n\t\t\t}\n\t\t\tengine.stop();\n\t\t},\n\n\t\tdestroy(): void {\n\t\t\tthis.stop();\n\t\t\tengine.destroy();\n\t\t},\n\n\t\tdispatch(event: { type: string; [key: string]: unknown }) {\n\t\t\t// Events are dispatched with namespace prefix\n\t\t\t// e.g., { type: \"login\", token: \"abc\" } from auth module\n\t\t\t// becomes { type: \"auth::login\", token: \"abc\" }\n\t\t\t// But we keep them simple - the event type should match the schema\n\t\t\tengine.dispatch(event);\n\t\t},\n\n\t\tbatch: engine.batch.bind(engine),\n\n\t\t/**\n\t\t * Read a derivation value using namespaced syntax.\n\t\t * Accepts \"namespace.key\" format.\n\t\t *\n\t\t * @example\n\t\t * system.read(\"auth.status\") // → \"authenticated\"\n\t\t * system.read(\"data.count\") // → 5\n\t\t */\n\t\tread<T = unknown>(derivationId: string): T {\n\t\t\treturn engine.read(toInternalKey(derivationId));\n\t\t},\n\n\t\t/**\n\t\t * Subscribe to derivation changes using namespaced syntax.\n\t\t * Accepts \"namespace.key\" format.\n\t\t * Supports wildcard \"namespace.*\" to subscribe to all keys in a module.\n\t\t *\n\t\t * @example\n\t\t * system.subscribe([\"auth.status\", \"data.count\"], () => {\n\t\t * console.log(\"Auth or data changed\");\n\t\t * });\n\t\t *\n\t\t * @example Wildcard\n\t\t * system.subscribe([\"game.*\", \"chat.*\"], () => render());\n\t\t */\n\t\tsubscribe(ids: string[], listener: () => void): () => void {\n\t\t\tconst internalIds: string[] = [];\n\t\t\tfor (const id of ids) {\n\t\t\t\tif (id.endsWith(\".*\")) {\n\t\t\t\t\tconst ns = id.slice(0, -2);\n\t\t\t\t\tconst keys = namespaceKeysMap.get(ns);\n\t\t\t\t\tif (keys) {\n\t\t\t\t\t\tinternalIds.push(...keys);\n\t\t\t\t\t} else if (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\t\tconsole.warn(`[Directive] subscribe wildcard \"${id}\" — namespace \"${ns}\" not found.`);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tinternalIds.push(toInternalKey(id));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn engine.subscribe(internalIds, listener);\n\t\t},\n\n\t\t/**\n\t\t * Subscribe to ALL fact and derivation changes in a module namespace.\n\t\t * Shorthand for subscribing to every key in a module.\n\t\t *\n\t\t * @example\n\t\t * const unsub = system.subscribeModule(\"game\", () => render());\n\t\t */\n\t\tsubscribeModule(namespace: string, listener: () => void): () => void {\n\t\t\tconst keys = namespaceKeysMap.get(namespace);\n\t\t\tif (!keys || keys.length === 0) {\n\t\t\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Directive] subscribeModule(\"${namespace}\") — namespace not found. ` +\n\t\t\t\t\t\t`Available: ${[...namespaceKeysMap.keys()].join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn () => {};\n\t\t\t}\n\t\t\treturn engine.subscribe(keys, listener);\n\t\t},\n\n\t\t/**\n\t\t * Watch a fact or derivation for changes using namespaced syntax.\n\t\t * The key is auto-detected -- works with both fact keys and derivation keys.\n\t\t * Accepts \"namespace.key\" format.\n\t\t *\n\t\t * @example\n\t\t * system.watch(\"auth.token\", (newVal, oldVal) => { ... }) // fact\n\t\t * system.watch(\"auth.status\", (newVal, oldVal) => { ... }) // derivation\n\t\t */\n\t\twatch<T = unknown>(\n\t\t\tid: string,\n\t\t\tcallback: (newValue: T, previousValue: T | undefined) => void,\n\t\t\toptions?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n\t\t): () => void {\n\t\t\treturn engine.watch(toInternalKey(id), callback, options);\n\t\t},\n\n\t\t/**\n\t\t * Returns a promise that resolves when the predicate becomes true.\n\t\t * The predicate receives namespaced facts (e.g., facts.auth.token).\n\t\t */\n\t\twhen(\n\t\t\tpredicate: (facts: Record<string, unknown>) => boolean,\n\t\t\toptions?: { timeout?: number },\n\t\t): Promise<void> {\n\t\t\t// Wrap predicate to provide namespaced facts view\n\t\t\treturn engine.when(\n\t\t\t\t() => predicate(namespacedFactsProxy as unknown as Record<string, unknown>),\n\t\t\t\toptions,\n\t\t\t);\n\t\t},\n\n\t\tonSettledChange: engine.onSettledChange.bind(engine),\n\t\tonTimeTravelChange: engine.onTimeTravelChange.bind(engine),\n\t\tinspect: engine.inspect.bind(engine),\n\t\tsettle: engine.settle.bind(engine),\n\t\texplain: engine.explain.bind(engine),\n\t\tgetSnapshot: engine.getSnapshot.bind(engine),\n\t\trestore: engine.restore.bind(engine),\n\n\t\t/**\n\t\t * Get a distributable snapshot with namespaced key translation.\n\t\t * Accepts \"namespace.key\" format in options (e.g., \"auth.effectivePlan\").\n\t\t * Returns data with namespaced keys (e.g., { auth: { effectivePlan: ... } }).\n\t\t */\n\t\tgetDistributableSnapshot<T = Record<string, unknown>>(\n\t\t\toptions?: {\n\t\t\t\tincludeDerivations?: string[];\n\t\t\t\texcludeDerivations?: string[];\n\t\t\t\tincludeFacts?: string[];\n\t\t\t\tttlSeconds?: number;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t\tincludeVersion?: boolean;\n\t\t\t},\n\t\t): {\n\t\t\tdata: T;\n\t\t\tcreatedAt: number;\n\t\t\texpiresAt?: number;\n\t\t\tversion?: string;\n\t\t\tmetadata?: Record<string, unknown>;\n\t\t} {\n\t\t\t// Translate namespaced keys to internal format\n\t\t\tconst internalOptions = {\n\t\t\t\t...options,\n\t\t\t\tincludeDerivations: options?.includeDerivations?.map(toInternalKey),\n\t\t\t\texcludeDerivations: options?.excludeDerivations?.map(toInternalKey),\n\t\t\t\tincludeFacts: options?.includeFacts?.map(toInternalKey),\n\t\t\t};\n\n\t\t\tconst snapshot = engine.getDistributableSnapshot(internalOptions);\n\n\t\t\t// Transform data keys from internal format (auth::status) to namespaced format (auth: { status })\n\t\t\tconst namespacedData: Record<string, Record<string, unknown>> = {};\n\n\t\t\tfor (const [key, value] of Object.entries(snapshot.data as Record<string, unknown>)) {\n\t\t\t\t// Find the namespace prefix (first separator)\n\t\t\t\tconst sepIndex = key.indexOf(SEPARATOR);\n\t\t\t\tif (sepIndex > 0) {\n\t\t\t\t\tconst namespace = key.slice(0, sepIndex);\n\t\t\t\t\tconst localKey = key.slice(sepIndex + SEPARATOR.length);\n\t\t\t\t\tif (!namespacedData[namespace]) {\n\t\t\t\t\t\tnamespacedData[namespace] = {};\n\t\t\t\t\t}\n\t\t\t\t\tnamespacedData[namespace][localKey] = value;\n\t\t\t\t} else {\n\t\t\t\t\t// No namespace found, keep as-is\n\t\t\t\t\tif (!namespacedData[\"_root\"]) {\n\t\t\t\t\t\tnamespacedData[\"_root\"] = {};\n\t\t\t\t\t}\n\t\t\t\t\tnamespacedData[\"_root\"][key] = value;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\t...snapshot,\n\t\t\t\tdata: namespacedData as T,\n\t\t\t};\n\t\t},\n\n\t\t/**\n\t\t * Watch for changes to distributable snapshot derivations.\n\t\t * Accepts \"namespace.key\" format in options.\n\t\t * Callback receives data with namespaced keys.\n\t\t */\n\t\twatchDistributableSnapshot<T = Record<string, unknown>>(\n\t\t\toptions: {\n\t\t\t\tincludeDerivations?: string[];\n\t\t\t\texcludeDerivations?: string[];\n\t\t\t\tincludeFacts?: string[];\n\t\t\t\tttlSeconds?: number;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t\tincludeVersion?: boolean;\n\t\t\t},\n\t\t\tcallback: (snapshot: {\n\t\t\t\tdata: T;\n\t\t\t\tcreatedAt: number;\n\t\t\t\texpiresAt?: number;\n\t\t\t\tversion?: string;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t}) => void,\n\t\t): () => void {\n\t\t\t// Translate namespaced keys to internal format\n\t\t\tconst internalOptions = {\n\t\t\t\t...options,\n\t\t\t\tincludeDerivations: options?.includeDerivations?.map(toInternalKey),\n\t\t\t\texcludeDerivations: options?.excludeDerivations?.map(toInternalKey),\n\t\t\t\tincludeFacts: options?.includeFacts?.map(toInternalKey),\n\t\t\t};\n\n\t\t\treturn engine.watchDistributableSnapshot(\n\t\t\t\tinternalOptions,\n\t\t\t\t(snapshot: { data: Record<string, unknown>; createdAt: number; expiresAt?: number; version?: string; metadata?: Record<string, unknown> }) => {\n\t\t\t\t\t// Transform data keys from internal format to namespaced format\n\t\t\t\t\tconst namespacedData: Record<string, Record<string, unknown>> = {};\n\n\t\t\t\t\tfor (const [key, value] of Object.entries(snapshot.data)) {\n\t\t\t\t\t\tconst sepIndex = key.indexOf(SEPARATOR);\n\t\t\t\t\t\tif (sepIndex > 0) {\n\t\t\t\t\t\t\tconst namespace = key.slice(0, sepIndex);\n\t\t\t\t\t\t\tconst localKey = key.slice(sepIndex + SEPARATOR.length);\n\t\t\t\t\t\t\tif (!namespacedData[namespace]) {\n\t\t\t\t\t\t\t\tnamespacedData[namespace] = {};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnamespacedData[namespace][localKey] = value;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (!namespacedData[\"_root\"]) {\n\t\t\t\t\t\t\t\tnamespacedData[\"_root\"] = {};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnamespacedData[\"_root\"][key] = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcallback({\n\t\t\t\t\t\t...snapshot,\n\t\t\t\t\t\tdata: namespacedData as T,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\tregisterModule(namespace: string, moduleDef: ModuleDef<ModuleSchema>): void {\n\t\t\t// Validate namespace\n\t\t\tif (moduleNamespaces.has(namespace)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Module namespace \"${namespace}\" already exists. ` +\n\t\t\t\t\t`Cannot register a duplicate namespace.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (namespace.includes(SEPARATOR)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Module name \"${namespace}\" contains the reserved separator \"${SEPARATOR}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (BLOCKED_PROPS.has(namespace)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Module name \"${namespace}\" is a blocked property.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Validate schema keys\n\t\t\tfor (const key of Object.keys(moduleDef.schema.facts)) {\n\t\t\t\tif (key.includes(SEPARATOR)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[Directive] Schema key \"${key}\" in module \"${namespace}\" contains the reserved separator \"${SEPARATOR}\".`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst mod = moduleDef;\n\t\t\tconst hasCrossModuleDeps = mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0;\n\t\t\tconst depNamespaces = hasCrossModuleDeps ? Object.keys(mod.crossModuleDeps!) : [];\n\n\t\t\t// Build prefixed schema, derive, events, effects, constraints, resolvers\n\t\t\t// (same logic as initial createNamespacedSystem)\n\t\t\tconst prefixedFacts: Record<string, unknown> = {};\n\t\t\tfor (const [key, value] of Object.entries(mod.schema.facts)) {\n\t\t\t\tprefixedFacts[`${namespace}${SEPARATOR}${key}`] = value;\n\t\t\t}\n\n\t\t\tconst prefixedInit = mod.init\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Module init type coercion\n\t\t\t\t? (facts: any) => {\n\t\t\t\t\t\tconst moduleFactsProxy = createModuleFactsProxy(facts, namespace);\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Module init type coercion\n\t\t\t\t\t\t(mod.init as any)(moduleFactsProxy);\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\n\t\t\tconst prefixedDerive: Record<string, (facts: unknown, derive: unknown) => unknown> = {};\n\t\t\tif (mod.derive) {\n\t\t\t\tfor (const [key, fn] of Object.entries(mod.derive)) {\n\t\t\t\t\tprefixedDerive[`${namespace}${SEPARATOR}${key}`] = (facts: unknown, derive: unknown) => {\n\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\tconst deriveProxy = createModuleDeriveProxy(derive as Record<string, unknown>, namespace);\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Derive function type coercion\n\t\t\t\t\t\treturn (fn as any)(factsProxy, deriveProxy);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst prefixedEventHandlers: Record<string, (facts: unknown, event: unknown) => void> = {};\n\t\t\tif (mod.events) {\n\t\t\t\tfor (const [key, handler] of Object.entries(mod.events)) {\n\t\t\t\t\tprefixedEventHandlers[`${namespace}${SEPARATOR}${key}`] = (facts: unknown, event: unknown) => {\n\t\t\t\t\t\tconst moduleFactsProxy = createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Event handler type coercion\n\t\t\t\t\t\t(handler as any)(moduleFactsProxy, event);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst prefixedConstraints: Record<string, unknown> = {};\n\t\t\tif (mod.constraints) {\n\t\t\t\tfor (const [key, constraint] of Object.entries(mod.constraints)) {\n\t\t\t\t\tconst constraintDef = constraint as {\n\t\t\t\t\t\twhen: (facts: unknown) => boolean | Promise<boolean>;\n\t\t\t\t\t\trequire: unknown | ((facts: unknown) => unknown);\n\t\t\t\t\t\tpriority?: number;\n\t\t\t\t\t\tasync?: boolean;\n\t\t\t\t\t\ttimeout?: number;\n\t\t\t\t\t\tdeps?: string[];\n\t\t\t\t\t};\n\t\t\t\t\tprefixedConstraints[`${namespace}${SEPARATOR}${key}`] = {\n\t\t\t\t\t\t...constraintDef,\n\t\t\t\t\t\tdeps: constraintDef.deps?.map((dep) => `${namespace}${SEPARATOR}${dep}`),\n\t\t\t\t\t\twhen: (facts: unknown) => {\n\t\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\t\treturn constraintDef.when(factsProxy);\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequire: typeof constraintDef.require === \"function\"\n\t\t\t\t\t\t\t? (facts: unknown) => {\n\t\t\t\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\t\t\t\treturn (constraintDef.require as (facts: unknown) => unknown)(factsProxy);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: constraintDef.require,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst prefixedResolvers: Record<string, unknown> = {};\n\t\t\tif (mod.resolvers) {\n\t\t\t\tfor (const [key, resolver] of Object.entries(mod.resolvers)) {\n\t\t\t\t\tconst resolverDef = resolver as {\n\t\t\t\t\t\trequirement: string;\n\t\t\t\t\t\tresolve: (req: unknown, ctx: { facts: unknown; signal: AbortSignal }) => Promise<void>;\n\t\t\t\t\t\tkey?: (req: unknown) => string;\n\t\t\t\t\t\tretry?: unknown;\n\t\t\t\t\t\ttimeout?: number;\n\t\t\t\t\t};\n\t\t\t\t\tprefixedResolvers[`${namespace}${SEPARATOR}${key}`] = {\n\t\t\t\t\t\t...resolverDef,\n\t\t\t\t\t\tresolve: async (req: unknown, ctx: { facts: unknown; signal: AbortSignal }) => {\n\t\t\t\t\t\t\t// Use live modulesMap reference (already mutated by registerModule before this runs)\n\t\t\t\t\t\t\tconst namespacedFacts = createNamespacedFactsProxy(ctx.facts as Record<string, unknown>, modulesMap, getModuleNames);\n\t\t\t\t\t\t\tawait resolverDef.resolve(req, {\n\t\t\t\t\t\t\t\tfacts: namespacedFacts[namespace],\n\t\t\t\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst prefixedEffects: Record<string, unknown> = {};\n\t\t\tif (mod.effects) {\n\t\t\t\tfor (const [key, effect] of Object.entries(mod.effects)) {\n\t\t\t\t\tconst effectDef = effect as {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Effect run function type\n\t\t\t\t\t\trun: (facts: any, prev: any) => void | Promise<void>;\n\t\t\t\t\t\tdeps?: string[];\n\t\t\t\t\t};\n\t\t\t\t\tprefixedEffects[`${namespace}${SEPARATOR}${key}`] = {\n\t\t\t\t\t\t...effectDef,\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Effect run function wrapper\n\t\t\t\t\t\trun: (facts: any, prev: any) => {\n\t\t\t\t\t\t\tconst factsProxy = hasCrossModuleDeps\n\t\t\t\t\t\t\t\t? createCrossModuleFactsProxy(facts as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t\t: createModuleFactsProxy(facts as Record<string, unknown>, namespace);\n\t\t\t\t\t\t\tconst prevProxy = prev\n\t\t\t\t\t\t\t\t? (hasCrossModuleDeps\n\t\t\t\t\t\t\t\t\t\t? createCrossModuleFactsProxy(prev as Record<string, unknown>, namespace, depNamespaces)\n\t\t\t\t\t\t\t\t\t\t: createModuleFactsProxy(prev as Record<string, unknown>, namespace))\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\t\treturn effectDef.run(factsProxy, prevProxy);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdeps: effectDef.deps?.map((dep) => `${namespace}${SEPARATOR}${dep}`),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Register namespace\n\t\t\tmoduleNamespaces.add(namespace);\n\t\t\t(modulesMap as Record<string, ModuleDef<ModuleSchema>>)[namespace] = mod;\n\t\t\t// Invalidate cached module names so proxies see the new namespace\n\t\t\tmoduleNamesCache.names = null;\n\n\t\t\t// Update namespace keys map\n\t\t\tconst keys: string[] = [];\n\t\t\tfor (const key of Object.keys(mod.schema.facts)) {\n\t\t\t\tkeys.push(`${namespace}${SEPARATOR}${key}`);\n\t\t\t}\n\t\t\tif (mod.schema.derivations) {\n\t\t\t\tfor (const key of Object.keys(mod.schema.derivations)) {\n\t\t\t\t\tkeys.push(`${namespace}${SEPARATOR}${key}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tnamespaceKeysMap.set(namespace, keys);\n\n\t\t\t// Delegate to engine's registerModule\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Engine registerModule type\n\t\t\t(engine as any).registerModule({\n\t\t\t\tid: mod.id,\n\t\t\t\tschema: prefixedFacts,\n\t\t\t\trequirements: mod.schema.requirements ?? {},\n\t\t\t\tinit: prefixedInit,\n\t\t\t\tderive: Object.keys(prefixedDerive).length > 0 ? prefixedDerive : undefined,\n\t\t\t\tevents: Object.keys(prefixedEventHandlers).length > 0 ? prefixedEventHandlers : undefined,\n\t\t\t\teffects: Object.keys(prefixedEffects).length > 0 ? prefixedEffects : undefined,\n\t\t\t\tconstraints: Object.keys(prefixedConstraints).length > 0 ? prefixedConstraints : undefined,\n\t\t\t\tresolvers: Object.keys(prefixedResolvers).length > 0 ? prefixedResolvers : undefined,\n\t\t\t\thooks: mod.hooks,\n\t\t\t\tsnapshotEvents: (snapshotModulesSet && !snapshotModulesSet.has(namespace))\n\t\t\t\t\t? [] // Module excluded from snapshots\n\t\t\t\t\t: mod.snapshotEvents?.map((e: string) => `${namespace}${SEPARATOR}${e}`),\n\t\t\t});\n\t\t},\n\n\t// biome-ignore lint/suspicious/noExplicitAny: Type narrowing for NamespacedSystem\n\t} as any;\n\n\treturn system;\n}\n\n// ============================================================================\n// Key Conversion Helpers\n// ============================================================================\n\n/**\n * Convert a namespaced key (e.g., \"auth.status\") to internal prefixed format (\"auth::status\").\n * If the key is already in prefixed format, returns it unchanged.\n *\n * @example\n * toInternalKey(\"auth.status\") // → \"auth::status\"\n * toInternalKey(\"auth::status\") // → \"auth::status\" (unchanged)\n * toInternalKey(\"status\") // → \"status\" (unchanged)\n */\nfunction toInternalKey(key: string): string {\n\t// If key contains a dot, convert to separator format\n\tif (key.includes(\".\")) {\n\t\tconst [namespace, ...rest] = key.split(\".\");\n\t\treturn `${namespace}${SEPARATOR}${rest.join(SEPARATOR)}`;\n\t}\n\t// Already in internal format or simple key\n\treturn key;\n}\n\n// ============================================================================\n// Proxy Helpers\n// ============================================================================\n\n/**\n * Create a proxy for a single module's facts (used in init, event handlers).\n * Translates unprefixed keys to prefixed: `token` → `auth::token`\n *\n * Proxies are cached per facts store and namespace for performance.\n */\nfunction createModuleFactsProxy(\n\tfacts: Record<string, unknown>,\n\tnamespace: string,\n): Record<string, unknown> {\n\t// Check cache first\n\tlet namespaceCache = moduleFactsProxyCache.get(facts);\n\tif (namespaceCache) {\n\t\tconst cached = namespaceCache.get(namespace);\n\t\tif (cached) return cached;\n\t} else {\n\t\tnamespaceCache = new Map();\n\t\tmoduleFactsProxyCache.set(facts, namespaceCache);\n\t}\n\n\tconst proxy = new Proxy({} as Record<string, unknown>, {\n\t\tget(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\t\t\t// Special properties pass through\n\t\t\tif (prop === \"$store\" || prop === \"$snapshot\") {\n\t\t\t\treturn (facts as Record<string, unknown>)[prop];\n\t\t\t}\n\t\t\treturn (facts as Record<string, unknown>)[`${namespace}${SEPARATOR}${prop}`];\n\t\t},\n\t\tset(_, prop: string | symbol, value: unknown) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\t\t\t(facts as Record<string, unknown>)[`${namespace}${SEPARATOR}${prop}`] = value;\n\t\t\treturn true;\n\t\t},\n\t\thas(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\t\t\treturn `${namespace}${SEPARATOR}${prop}` in facts;\n\t\t},\n\t\tdeleteProperty(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\t\t\tdelete (facts as Record<string, unknown>)[`${namespace}${SEPARATOR}${prop}`];\n\t\t\treturn true;\n\t\t},\n\t});\n\n\tnamespaceCache.set(namespace, proxy);\n\treturn proxy;\n}\n\n/**\n * Create a nested proxy for namespaced facts access.\n * `facts.auth.token` → reads `auth::token` from flat store\n *\n * Uses Set for O(1) namespace lookups and caches the outer proxy.\n */\nfunction createNamespacedFactsProxy(\n\tfacts: Record<string, unknown>,\n\tmodulesMap: ModulesMap,\n\tgetModuleNames: () => string[],\n): Record<string, Record<string, unknown>> {\n\t// Check cache first\n\tconst cached = namespacedFactsProxyCache.get(facts);\n\tif (cached) return cached;\n\n\tconst proxy = new Proxy({} as Record<string, Record<string, unknown>>, {\n\t\tget(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(namespace)) return undefined;\n\t\t\tif (!Object.hasOwn(modulesMap, namespace)) return undefined;\n\n\t\t\t// Return a cached proxy for this module's facts\n\t\t\treturn createModuleFactsProxy(facts, namespace);\n\t\t},\n\t\thas(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(namespace)) return false;\n\t\t\treturn Object.hasOwn(modulesMap, namespace);\n\t\t},\n\t\townKeys() {\n\t\t\treturn getModuleNames();\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return undefined;\n\t\t\tif (Object.hasOwn(modulesMap, namespace)) {\n\t\t\t\treturn { configurable: true, enumerable: true };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n\n\tnamespacedFactsProxyCache.set(facts, proxy);\n\treturn proxy;\n}\n\n/**\n * WeakMap to cache cross-module facts proxies.\n * Keyed by facts store, then by \"selfNamespace:depKeys\" string.\n */\nconst crossModuleFactsProxyCache = new WeakMap<\n\tRecord<string, unknown>,\n\tMap<string, Record<string, Record<string, unknown>>>\n>();\n\n/**\n * Create a proxy for cross-module facts access with \"self\" for own module.\n * `facts.self.users` → reads own module's facts\n * `facts.auth.token` → reads dependency module's facts\n *\n * Used when a module has crossModuleDeps defined.\n */\nfunction createCrossModuleFactsProxy(\n\tfacts: Record<string, unknown>,\n\tselfNamespace: string,\n\tdepNamespaces: string[],\n): Record<string, Record<string, unknown>> {\n\t// Create cache key using JSON.stringify for robustness with special characters\n\tconst cacheKey = `${selfNamespace}:${JSON.stringify([...depNamespaces].sort())}`;\n\n\t// Check cache first\n\tlet namespaceCache = crossModuleFactsProxyCache.get(facts);\n\tif (namespaceCache) {\n\t\tconst cached = namespaceCache.get(cacheKey);\n\t\tif (cached) return cached;\n\t} else {\n\t\tnamespaceCache = new Map();\n\t\tcrossModuleFactsProxyCache.set(facts, namespaceCache);\n\t}\n\n\tconst depNamesSet = new Set(depNamespaces);\n\tconst allKeys = [\"self\", ...depNamespaces];\n\n\tconst proxy = new Proxy({} as Record<string, Record<string, unknown>>, {\n\t\tget(_, key: string | symbol) {\n\t\t\tif (typeof key === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(key)) return undefined;\n\n\t\t\t// \"self\" maps to own module's namespace\n\t\t\tif (key === \"self\") {\n\t\t\t\treturn createModuleFactsProxy(facts, selfNamespace);\n\t\t\t}\n\n\t\t\t// Check if it's a declared dependency\n\t\t\tif (depNamesSet.has(key)) {\n\t\t\t\treturn createModuleFactsProxy(facts, key);\n\t\t\t}\n\n\t\t\t// Dev-mode warning for undeclared cross-module access\n\t\t\tif (process.env.NODE_ENV !== \"production\" && typeof key === \"string\") {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] Module \"${selfNamespace}\" accessed undeclared cross-module property \"${key}\". ` +\n\t\t\t\t\t`Add it to crossModuleDeps or use \"facts.self.${key}\" for own module facts.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn undefined;\n\t\t},\n\t\thas(_, key: string | symbol) {\n\t\t\tif (typeof key === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(key)) return false;\n\t\t\treturn key === \"self\" || depNamesSet.has(key);\n\t\t},\n\t\townKeys() {\n\t\t\treturn allKeys;\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, key: string | symbol) {\n\t\t\tif (typeof key === \"symbol\") return undefined;\n\t\t\tif (key === \"self\" || depNamesSet.has(key)) {\n\t\t\t\treturn { configurable: true, enumerable: true };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n\n\tnamespaceCache.set(cacheKey, proxy);\n\treturn proxy;\n}\n\n/**\n * Create a proxy for a single module's derivations.\n * Translates unprefixed keys to prefixed: `status` → `auth::status`\n *\n * Proxies are cached per derive store and namespace for performance.\n */\nfunction createModuleDeriveProxy(\n\tderive: Record<string, unknown>,\n\tnamespace: string,\n): Record<string, unknown> {\n\t// Check cache first\n\tlet namespaceCache = moduleDeriveProxyCache.get(derive);\n\tif (namespaceCache) {\n\t\tconst cached = namespaceCache.get(namespace);\n\t\tif (cached) return cached;\n\t} else {\n\t\tnamespaceCache = new Map();\n\t\tmoduleDeriveProxyCache.set(derive, namespaceCache);\n\t}\n\n\tconst proxy = new Proxy({} as Record<string, unknown>, {\n\t\tget(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return undefined;\n\t\t\treturn derive[`${namespace}${SEPARATOR}${prop}`];\n\t\t},\n\t\thas(_, prop: string | symbol) {\n\t\t\tif (typeof prop === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(prop)) return false;\n\t\t\treturn `${namespace}${SEPARATOR}${prop}` in derive;\n\t\t},\n\t});\n\n\tnamespaceCache.set(namespace, proxy);\n\treturn proxy;\n}\n\n/**\n * Create a nested proxy for namespaced derivations access.\n * `derive.auth.status` → reads `auth::status` from flat derive\n *\n * Uses Set for O(1) namespace lookups and caches the outer proxy.\n */\nfunction createNamespacedDeriveProxy(\n\tderive: Record<string, unknown>,\n\tmodulesMap: ModulesMap,\n\tgetModuleNames: () => string[],\n): Record<string, Record<string, unknown>> {\n\t// Check cache first\n\tconst cached = namespacedDeriveProxyCache.get(derive);\n\tif (cached) return cached;\n\n\tconst proxy = new Proxy({} as Record<string, Record<string, unknown>>, {\n\t\tget(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(namespace)) return undefined;\n\t\t\tif (!Object.hasOwn(modulesMap, namespace)) return undefined;\n\n\t\t\t// Return a cached proxy for this module's derivations\n\t\t\treturn createModuleDeriveProxy(derive, namespace);\n\t\t},\n\t\thas(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(namespace)) return false;\n\t\t\treturn Object.hasOwn(modulesMap, namespace);\n\t\t},\n\t\townKeys() {\n\t\t\treturn getModuleNames();\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return undefined;\n\t\t\tif (Object.hasOwn(modulesMap, namespace)) {\n\t\t\t\treturn { configurable: true, enumerable: true };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n\n\tnamespacedDeriveProxyCache.set(derive, proxy);\n\treturn proxy;\n}\n\n/**\n * WeakMap to cache module events proxies.\n */\nconst moduleEventsProxyCache = new WeakMap<\n\t// biome-ignore lint/suspicious/noExplicitAny: Engine type for cache key\n\tany,\n\tMap<string, Record<string, (payload?: Record<string, unknown>) => void>>\n>();\n\n/**\n * Create a nested proxy for namespaced events access.\n * `events.auth.login({ token })` → dispatches `{ type: \"auth::login\", token }`\n *\n * Uses Set for O(1) namespace lookups and caches proxies for performance.\n */\nfunction createNamespacedEventsProxy(\n\t// biome-ignore lint/suspicious/noExplicitAny: Engine type\n\tengine: any,\n\tmodulesMap: ModulesMap,\n\tgetModuleNames: () => string[],\n): Record<string, Record<string, (payload?: Record<string, unknown>) => void>> {\n\t// Get or create the namespace cache for this engine\n\tlet namespaceCache = moduleEventsProxyCache.get(engine);\n\tif (!namespaceCache) {\n\t\tnamespaceCache = new Map();\n\t\tmoduleEventsProxyCache.set(engine, namespaceCache);\n\t}\n\n\treturn new Proxy({} as Record<string, Record<string, (payload?: Record<string, unknown>) => void>>, {\n\t\tget(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(namespace)) return undefined;\n\t\t\tif (!Object.hasOwn(modulesMap, namespace)) return undefined;\n\n\t\t\t// Check cache for this namespace's event proxy\n\t\t\tconst cached = namespaceCache!.get(namespace);\n\t\t\tif (cached) return cached;\n\n\t\t\t// Create and cache the module events proxy\n\t\t\tconst moduleEventsProxy = new Proxy({} as Record<string, (payload?: Record<string, unknown>) => void>, {\n\t\t\t\tget(_, eventName: string | symbol) {\n\t\t\t\t\tif (typeof eventName === \"symbol\") return undefined;\n\t\t\t\t\tif (BLOCKED_PROPS.has(eventName)) return undefined;\n\n\t\t\t\t\t// Return a function that dispatches the prefixed event\n\t\t\t\t\treturn (payload?: Record<string, unknown>) => {\n\t\t\t\t\t\tengine.dispatch({ type: `${namespace}${SEPARATOR}${eventName}`, ...payload });\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tnamespaceCache!.set(namespace, moduleEventsProxy);\n\t\t\treturn moduleEventsProxy;\n\t\t},\n\t\thas(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return false;\n\t\t\tif (BLOCKED_PROPS.has(namespace)) return false;\n\t\t\treturn Object.hasOwn(modulesMap, namespace);\n\t\t},\n\t\townKeys() {\n\t\t\treturn getModuleNames();\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, namespace: string | symbol) {\n\t\t\tif (typeof namespace === \"symbol\") return undefined;\n\t\t\tif (Object.hasOwn(modulesMap, namespace)) {\n\t\t\t\treturn { configurable: true, enumerable: true };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n}\n\n// ============================================================================\n// Single Module System\n// ============================================================================\n\n/**\n * Create a system with a single module (no namespacing).\n * Facts, derivations, and events are accessed directly.\n */\nfunction createSingleModuleSystem<S extends ModuleSchema>(\n\toptions: CreateSystemOptionsSingle<S>,\n): SingleModuleSystem<S> {\n\tconst mod = options.module;\n\n\t// Validate module is provided\n\tif (!mod) {\n\t\tthrow new Error(\n\t\t\t\"[Directive] createSystem requires a module. Got: \" + typeof mod,\n\t\t);\n\t}\n\n\t// Validate tickMs if provided\n\tif (options.tickMs !== undefined && options.tickMs <= 0) {\n\t\tthrow new Error(\"[Directive] tickMs must be a positive number\");\n\t}\n\n\t// Validate initialFacts for prototype pollution\n\tif (options.initialFacts && !isPrototypeSafe(options.initialFacts)) {\n\t\tthrow new Error(\n\t\t\t\"[Directive] initialFacts contains potentially dangerous keys \" +\n\t\t\t\"(__proto__, constructor, or prototype). This may indicate a \" +\n\t\t\t\"prototype pollution attack.\",\n\t\t);\n\t}\n\n\t// Dev-mode warnings\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\t// Warn if crossModuleDeps is defined (ignored in single module mode)\n\t\tif (mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0) {\n\t\t\tconsole.warn(\n\t\t\t\t\"[Directive] Single module mode ignores crossModuleDeps. \" +\n\t\t\t\t\"Use multiple modules if cross-module access is needed: \" +\n\t\t\t\t\"createSystem({ modules: { ... } })\",\n\t\t\t);\n\t\t}\n\n\t\t// Warn if tickMs set without tick event handler\n\t\tif (options.tickMs && options.tickMs > 0) {\n\t\t\tconst hasTickHandler = mod.events && \"tick\" in mod.events;\n\t\t\tif (!hasTickHandler) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[Directive] tickMs is set to ${options.tickMs}ms but module has no \"tick\" event handler.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Warn if snapshotModules is set (has no effect in single-module mode)\n\t\tif (options.debug?.snapshotModules) {\n\t\t\tconsole.warn(\n\t\t\t\t\"[Directive] debug.snapshotModules has no effect in single-module mode. \" +\n\t\t\t\t\"Use snapshotEvents on the module definition instead, or switch to \" +\n\t\t\t\t\"createSystem({ modules: { ... } }) for multi-module filtering.\",\n\t\t\t);\n\t\t}\n\t}\n\n\t// Apply zero-config defaults if enabled\n\tlet debug = options.debug;\n\tlet errorBoundary = options.errorBoundary;\n\n\tif (options.zeroConfig) {\n\t\tconst isDev = process.env.NODE_ENV !== \"production\";\n\n\t\tdebug = {\n\t\t\ttimeTravel: isDev,\n\t\t\tmaxSnapshots: 100,\n\t\t\t...options.debug,\n\t\t};\n\n\t\terrorBoundary = {\n\t\t\tonConstraintError: \"skip\",\n\t\t\tonResolverError: \"skip\",\n\t\t\tonEffectError: \"skip\",\n\t\t\tonDerivationError: \"skip\",\n\t\t\t...options.errorBoundary,\n\t\t};\n\t}\n\n\t// Store for hydrated facts\n\tlet hydratedFacts: Record<string, unknown> | null = null;\n\n\t// Engine reference\n\t// biome-ignore lint/suspicious/noExplicitAny: Engine type\n\tlet engine: any = null;\n\n\t// Create engine with the module directly (no prefixing needed)\n\tengine = createEngine({\n\t\tmodules: [\n\t\t\t{\n\t\t\t\tid: mod.id,\n\t\t\t\tschema: mod.schema.facts,\n\t\t\t\trequirements: mod.schema.requirements,\n\t\t\t\tinit: mod.init,\n\t\t\t\tderive: mod.derive,\n\t\t\t\tevents: mod.events,\n\t\t\t\teffects: mod.effects,\n\t\t\t\tconstraints: mod.constraints,\n\t\t\t\tresolvers: mod.resolvers,\n\t\t\t\thooks: mod.hooks,\n\t\t\t\tsnapshotEvents: mod.snapshotEvents,\n\t\t\t},\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Module format\n\t\t] as any,\n\t\tplugins: options.plugins,\n\t\tdebug,\n\t\terrorBoundary,\n\t\ttickMs: options.tickMs,\n\t\tonAfterModuleInit: () => {\n\t\t\t// Apply initialFacts\n\t\t\tif (options.initialFacts) {\n\t\t\t\tfor (const [key, value] of Object.entries(options.initialFacts)) {\n\t\t\t\t\tif (BLOCKED_PROPS.has(key)) continue;\n\t\t\t\t\t(engine.facts as Record<string, unknown>)[key] = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Apply hydrated facts (takes precedence)\n\t\t\tif (hydratedFacts) {\n\t\t\t\tfor (const [key, value] of Object.entries(hydratedFacts)) {\n\t\t\t\t\tif (BLOCKED_PROPS.has(key)) continue;\n\t\t\t\t\t(engine.facts as Record<string, unknown>)[key] = value;\n\t\t\t\t}\n\t\t\t\thydratedFacts = null;\n\t\t\t}\n\t\t},\n\t});\n\n\t// Create events proxy for direct access\n\tconst eventsProxy = new Proxy({} as Record<string, (payload?: Record<string, unknown>) => void>, {\n\t\tget(_, eventName: string | symbol) {\n\t\t\tif (typeof eventName === \"symbol\") return undefined;\n\t\t\tif (BLOCKED_PROPS.has(eventName)) return undefined;\n\n\t\t\treturn (payload?: Record<string, unknown>) => {\n\t\t\t\tengine.dispatch({ type: eventName, ...payload });\n\t\t\t};\n\t\t},\n\t});\n\n\t// Build the single module system\n\tlet tickInterval: ReturnType<typeof setInterval> | null = null;\n\tconst tickMs = options.tickMs;\n\n\tconst system: SingleModuleSystem<S> = {\n\t\t_mode: \"single\",\n\t\tfacts: engine.facts,\n\t\tdebug: engine.debug,\n\t\tderive: engine.derive,\n\t\tevents: eventsProxy as SingleModuleSystem<S>[\"events\"],\n\t\tconstraints: engine.constraints,\n\t\teffects: engine.effects,\n\n\t\tget isRunning() {\n\t\t\treturn engine.isRunning;\n\t\t},\n\n\t\tget isSettled() {\n\t\t\treturn engine.isSettled;\n\t\t},\n\n\t\tget isInitialized() {\n\t\t\treturn engine.isInitialized;\n\t\t},\n\n\t\tget isReady() {\n\t\t\treturn engine.isReady;\n\t\t},\n\n\t\twhenReady: engine.whenReady.bind(engine),\n\n\t\tasync hydrate(\n\t\t\tloader: () => Promise<Record<string, unknown>> | Record<string, unknown>,\n\t\t) {\n\t\t\tif (engine.isRunning) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"[Directive] hydrate() must be called before start(). \" +\n\t\t\t\t\t\"The system is already running.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst result = await loader();\n\t\t\tif (result && typeof result === \"object\") {\n\t\t\t\thydratedFacts = result as Record<string, unknown>;\n\t\t\t}\n\t\t},\n\n\t\tstart(): void {\n\t\t\tengine.start();\n\n\t\t\tif (tickMs && tickMs > 0) {\n\t\t\t\tconst hasTickHandler = mod.events && \"tick\" in mod.events;\n\t\t\t\tif (hasTickHandler) {\n\t\t\t\t\ttickInterval = setInterval(() => {\n\t\t\t\t\t\tengine.dispatch({ type: \"tick\" });\n\t\t\t\t\t}, tickMs);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tstop(): void {\n\t\t\tif (tickInterval) {\n\t\t\t\tclearInterval(tickInterval);\n\t\t\t\ttickInterval = null;\n\t\t\t}\n\t\t\tengine.stop();\n\t\t},\n\n\t\tdestroy(): void {\n\t\t\tthis.stop();\n\t\t\tengine.destroy();\n\t\t},\n\n\t\tdispatch(event: { type: string; [key: string]: unknown }) {\n\t\t\tengine.dispatch(event);\n\t\t},\n\n\t\tbatch: engine.batch.bind(engine),\n\n\t\tread<T = unknown>(derivationId: string): T {\n\t\t\treturn engine.read(derivationId);\n\t\t},\n\n\t\tsubscribe(ids: string[], listener: () => void): () => void {\n\t\t\treturn engine.subscribe(ids, listener);\n\t\t},\n\n\t\twatch<T = unknown>(\n\t\t\tid: string,\n\t\t\tcallback: (newValue: T, previousValue: T | undefined) => void,\n\t\t\toptions?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n\t\t): () => void {\n\t\t\treturn engine.watch(id, callback, options);\n\t\t},\n\n\t\twhen(\n\t\t\tpredicate: (facts: Record<string, unknown>) => boolean,\n\t\t\toptions?: { timeout?: number },\n\t\t): Promise<void> {\n\t\t\treturn engine.when(predicate, options);\n\t\t},\n\n\t\tonSettledChange: engine.onSettledChange.bind(engine),\n\t\tonTimeTravelChange: engine.onTimeTravelChange.bind(engine),\n\t\tinspect: engine.inspect.bind(engine),\n\t\tsettle: engine.settle.bind(engine),\n\t\texplain: engine.explain.bind(engine),\n\t\tgetSnapshot: engine.getSnapshot.bind(engine),\n\t\trestore: engine.restore.bind(engine),\n\t\tgetDistributableSnapshot: engine.getDistributableSnapshot.bind(engine),\n\t\twatchDistributableSnapshot: engine.watchDistributableSnapshot.bind(engine),\n\n\t\tregisterModule(moduleDef: ModuleDef<ModuleSchema>): void {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Engine registerModule type\n\t\t\t(engine as any).registerModule({\n\t\t\t\tid: moduleDef.id,\n\t\t\t\tschema: moduleDef.schema.facts,\n\t\t\t\trequirements: moduleDef.schema.requirements,\n\t\t\t\tinit: moduleDef.init,\n\t\t\t\tderive: moduleDef.derive,\n\t\t\t\tevents: moduleDef.events,\n\t\t\t\teffects: moduleDef.effects,\n\t\t\t\tconstraints: moduleDef.constraints,\n\t\t\t\tresolvers: moduleDef.resolvers,\n\t\t\t\thooks: moduleDef.hooks,\n\t\t\t\tsnapshotEvents: moduleDef.snapshotEvents,\n\t\t\t});\n\t\t},\n\t// biome-ignore lint/suspicious/noExplicitAny: Type narrowing\n\t} as any;\n\n\treturn system;\n}\n\n","/**\n * Builder Pattern API for Directive Modules\n *\n * An alternative, fluent API for creating modules that provides\n * a more declarative style for module definition.\n *\n * @example\n * ```typescript\n * import { module, t } from '@directive-run/core';\n *\n * const counter = module(\"counter\")\n * .schema({\n * facts: { count: t.number(), lastAction: t.string() },\n * derivations: { doubled: t.number(), isPositive: t.boolean() },\n * events: { increment: {}, decrement: {} },\n * requirements: {},\n * })\n * .init((facts) => {\n * facts.count = 0;\n * facts.lastAction = \"\";\n * })\n * .derive({\n * doubled: (facts) => facts.count * 2,\n * isPositive: (facts) => facts.count > 0,\n * })\n * .events({\n * increment: (facts) => {\n * facts.count += 1;\n * facts.lastAction = \"increment\";\n * },\n * decrement: (facts) => {\n * facts.count -= 1;\n * facts.lastAction = \"decrement\";\n * },\n * })\n * .build();\n * ```\n */\n\nimport type {\n\tModuleSchema,\n\tDerivationsSchema,\n\tFacts,\n\tEffectsDef,\n\tModuleDef,\n\tModuleHooks,\n} from \"./types.js\";\n\n// ============================================================================\n// Builder Types\n// ============================================================================\n\n/**\n * Module builder interface - provides fluent API for building modules.\n *\n * @typeParam M - The module schema type (set after calling `.schema()`)\n */\nexport interface ModuleBuilder<M extends ModuleSchema = ModuleSchema> {\n\t/**\n\t * Define the schema for this module (facts, derivations, events, requirements).\n\t */\n\tschema<NewM extends ModuleSchema>(schema: NewM): ModuleBuilder<NewM>;\n\n\t/**\n\t * Define the initialization function for this module.\n\t */\n\tinit(initFn: (facts: Facts<M[\"facts\"]>) => void): ModuleBuilder<M>;\n\n\t/**\n\t * Define derivation implementations for this module.\n\t * Keys must match those declared in schema.derivations.\n\t */\n\tderive<D extends Record<string, (facts: Facts<M[\"facts\"]>, derive: DeriveAccessor<M>) => unknown>>(\n\t\tderivations: D\n\t): ModuleBuilder<M>;\n\n\t/**\n\t * Define event handler implementations for this module.\n\t * Keys must match those declared in schema.events.\n\t */\n\tevents<E extends Record<string, (facts: Facts<M[\"facts\"]>, payload: unknown) => void>>(\n\t\tevents: E\n\t): ModuleBuilder<M>;\n\n\t/**\n\t * Define effects (side effects) for this module.\n\t */\n\teffects(effects: EffectsDef<M[\"facts\"]>): ModuleBuilder<M>;\n\n\t/**\n\t * Define constraints for this module.\n\t */\n\tconstraints<C extends Record<string, ConstraintDef<M>>>(constraints: C): ModuleBuilder<M>;\n\n\t/**\n\t * Define resolvers for this module.\n\t */\n\tresolvers<R extends Record<string, ResolverDef<M>>>(resolvers: R): ModuleBuilder<M>;\n\n\t/**\n\t * Define lifecycle hooks for this module.\n\t */\n\thooks(hooks: ModuleHooks<M>): ModuleBuilder<M>;\n\n\t/**\n\t * Build the module definition.\n\t */\n\tbuild(): ModuleDef<M>;\n}\n\n// ============================================================================\n// Helper Types\n// ============================================================================\n\n/**\n * Accessor for reading other derivations within a derivation function.\n */\ntype DeriveAccessor<M extends ModuleSchema> = M[\"derivations\"] extends DerivationsSchema\n\t? { readonly [K in keyof M[\"derivations\"]]: InferSchemaType<M[\"derivations\"][K]> }\n\t: Record<string, never>;\n\n/**\n * Infer the TypeScript type from a schema type definition.\n */\n// biome-ignore lint/suspicious/noExplicitAny: Type inference utility\ntype InferSchemaType<T> = T extends { _type: infer U } ? U : any;\n\n/**\n * Constraint definition for the builder.\n */\ninterface ConstraintDef<M extends ModuleSchema> {\n\twhen: (facts: Facts<M[\"facts\"]>) => boolean;\n\trequire:\n\t\t| { type: string; [key: string]: unknown }\n\t\t| ((facts: Facts<M[\"facts\"]>) => { type: string; [key: string]: unknown } | null);\n\tpriority?: number;\n}\n\n/**\n * Resolver definition for the builder.\n */\ninterface ResolverDef<M extends ModuleSchema> {\n\trequirement: string | ((req: { type: string; [key: string]: unknown }) => boolean);\n\tresolve: (\n\t\treq: { type: string; [key: string]: unknown },\n\t\tctx: { facts: Facts<M[\"facts\"]>; signal?: AbortSignal }\n\t) => void | Promise<void>;\n\tretry?: {\n\t\tattempts?: number;\n\t\tbackoff?: \"linear\" | \"exponential\";\n\t\tdelay?: number;\n\t};\n\ttimeout?: number;\n\tkey?: (req: { type: string; [key: string]: unknown }) => string;\n}\n\n// ============================================================================\n// Builder Implementation\n// ============================================================================\n\n/**\n * Create a new module builder.\n *\n * @param id - The unique identifier for this module\n * @returns A module builder\n */\nexport function module(id: string): ModuleBuilder<ModuleSchema> {\n\t// Internal state for building the module\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _schema: any = { facts: {}, derivations: {}, events: {}, requirements: {} };\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _init: any;\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _events: any;\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _derive: any;\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _effects: any;\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _constraints: any;\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _resolvers: any;\n\t// biome-ignore lint/suspicious/noExplicitAny: Internal state needs flexibility\n\tlet _hooks: any;\n\n\t// biome-ignore lint/suspicious/noExplicitAny: Builder needs flexibility for fluent API\n\tconst builder: ModuleBuilder<any> = {\n\t\tschema(schema) {\n\t\t\t_schema = schema;\n\t\t\treturn builder;\n\t\t},\n\n\t\tinit(initFn) {\n\t\t\t_init = initFn;\n\t\t\treturn builder;\n\t\t},\n\n\t\tderive(derivations) {\n\t\t\t_derive = derivations;\n\t\t\treturn builder;\n\t\t},\n\n\t\tevents(events) {\n\t\t\t_events = events;\n\t\t\treturn builder;\n\t\t},\n\n\t\teffects(effects) {\n\t\t\t_effects = effects;\n\t\t\treturn builder;\n\t\t},\n\n\t\tconstraints(constraints) {\n\t\t\t_constraints = constraints;\n\t\t\treturn builder;\n\t\t},\n\n\t\tresolvers(resolvers) {\n\t\t\t_resolvers = resolvers;\n\t\t\treturn builder;\n\t\t},\n\n\t\thooks(hooks) {\n\t\t\t_hooks = hooks;\n\t\t\treturn builder;\n\t\t},\n\n\t\tbuild() {\n\t\t\t// Validate schema is defined\n\t\t\tif (!_schema || !_schema.facts) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Module \"${id}\" requires a schema with at least facts defined. ` +\n\t\t\t\t\t\"Call .schema({ facts: { ... } }) before .build().\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Validate derivations match schema\n\t\t\tconst schemaDerivationKeys = Object.keys(_schema.derivations ?? {});\n\t\t\tconst deriveKeys = Object.keys(_derive ?? {});\n\t\t\tconst missingDerives = schemaDerivationKeys.filter(k => !deriveKeys.includes(k));\n\t\t\tif (missingDerives.length > 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Module \"${id}\" is missing derivation implementations: ${missingDerives.join(\", \")}. ` +\n\t\t\t\t\t\"All derivations declared in schema.derivations must have implementations in .derive().\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Validate events match schema\n\t\t\tconst schemaEventKeys = Object.keys(_schema.events ?? {});\n\t\t\tconst eventKeys = Object.keys(_events ?? {});\n\t\t\tconst missingEvents = schemaEventKeys.filter(k => !eventKeys.includes(k));\n\t\t\tif (missingEvents.length > 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[Directive] Module \"${id}\" is missing event handler implementations: ${missingEvents.join(\", \")}. ` +\n\t\t\t\t\t\"All events declared in schema.events must have implementations in .events().\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tid,\n\t\t\t\tschema: _schema,\n\t\t\t\tinit: _init,\n\t\t\t\tevents: _events,\n\t\t\t\tderive: _derive,\n\t\t\t\teffects: _effects,\n\t\t\t\tconstraints: _constraints,\n\t\t\t\tresolvers: _resolvers,\n\t\t\t\thooks: _hooks,\n\t\t\t};\n\t\t},\n\t};\n\n\treturn builder;\n}\n","/**\n * Constraint Builder API\n *\n * Fluent builders for creating typed constraint definitions.\n *\n * @example Full builder\n * ```typescript\n * import { constraint } from '@directive-run/core';\n *\n * const escalate = constraint<typeof schema>()\n * .when(f => f.confidence < 0.7)\n * .require({ type: 'ESCALATE' })\n * .priority(50)\n * .build();\n * ```\n *\n * @example Quick shorthand\n * ```typescript\n * import { when } from '@directive-run/core';\n *\n * const pause = when<typeof schema>(f => f.errors > 3)\n * .require({ type: 'PAUSE' });\n * ```\n */\n\nimport type { ModuleSchema, InferRequirements } from \"./types/schema.js\";\nimport type { Facts } from \"./types/facts.js\";\nimport type { TypedConstraintDef, RequirementOutput } from \"./types/module.js\";\n\n// ============================================================================\n// Builder Types\n// ============================================================================\n\ntype WhenFn<M extends ModuleSchema> = (facts: Facts<M[\"facts\"]>) => boolean | Promise<boolean>;\ntype RequireValue<M extends ModuleSchema> =\n\t| RequirementOutput<InferRequirements<M>>\n\t| ((facts: Facts<M[\"facts\"]>) => RequirementOutput<InferRequirements<M>>);\n\n/** Builder after constraint() — must call .when() first */\nexport interface ConstraintBuilderStart<M extends ModuleSchema> {\n\twhen(condition: WhenFn<M>): ConstraintBuilderWithWhen<M>;\n}\n\n/** Builder after .when() — must call .require() next */\nexport interface ConstraintBuilderWithWhen<M extends ModuleSchema> {\n\trequire(req: RequireValue<M>): ConstraintBuilderComplete<M>;\n}\n\n/** Builder after .require() — optional chaining + .build() */\nexport interface ConstraintBuilderComplete<M extends ModuleSchema> {\n\tpriority(n: number): ConstraintBuilderComplete<M>;\n\tafter(...ids: string[]): ConstraintBuilderComplete<M>;\n\tdeps(...keys: string[]): ConstraintBuilderComplete<M>;\n\ttimeout(ms: number): ConstraintBuilderComplete<M>;\n\tasync(value: boolean): ConstraintBuilderComplete<M>;\n\tbuild(): TypedConstraintDef<M>;\n}\n\n/** Result from when().require() — a valid constraint with optional immutable chaining */\nexport type WhenConstraint<M extends ModuleSchema> = TypedConstraintDef<M> & {\n\twithPriority(n: number): WhenConstraint<M>;\n\twithAfter(...ids: string[]): WhenConstraint<M>;\n\twithDeps(...keys: string[]): WhenConstraint<M>;\n\twithTimeout(ms: number): WhenConstraint<M>;\n\twithAsync(value: boolean): WhenConstraint<M>;\n};\n\n/** Result from when() — must call .require() */\nexport interface WhenBuilder<M extends ModuleSchema> {\n\trequire(req: RequireValue<M>): WhenConstraint<M>;\n}\n\n// ============================================================================\n// constraint() Builder\n// ============================================================================\n\n/**\n * Create a constraint using the full builder pattern.\n * Requires `.when()`, `.require()`, and `.build()`.\n *\n * @example\n * ```typescript\n * const c = constraint<typeof schema>()\n * .when(f => f.phase === \"red\")\n * .require({ type: \"TRANSITION\", to: \"green\" })\n * .priority(50)\n * .after(\"healthCheck\")\n * .build();\n * ```\n */\nexport function constraint<M extends ModuleSchema>(): ConstraintBuilderStart<M> {\n\treturn {\n\t\twhen(condition: WhenFn<M>): ConstraintBuilderWithWhen<M> {\n\t\t\treturn {\n\t\t\t\trequire(req: RequireValue<M>): ConstraintBuilderComplete<M> {\n\t\t\t\t\tlet _priority: number | undefined;\n\t\t\t\t\tlet _after: string[] | undefined;\n\t\t\t\t\tlet _deps: string[] | undefined;\n\t\t\t\t\tlet _timeout: number | undefined;\n\t\t\t\t\tlet _async: boolean | undefined;\n\n\t\t\t\t\tconst complete: ConstraintBuilderComplete<M> = {\n\t\t\t\t\t\tpriority(n) {\n\t\t\t\t\t\t\t_priority = n;\n\t\t\t\t\t\t\treturn complete;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tafter(...ids) {\n\t\t\t\t\t\t\t_after = _after ? [..._after, ...ids] : [...ids];\n\t\t\t\t\t\t\treturn complete;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdeps(...keys) {\n\t\t\t\t\t\t\t_deps = _deps ? [..._deps, ...keys] : [...keys];\n\t\t\t\t\t\t\treturn complete;\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttimeout(ms) {\n\t\t\t\t\t\t\t_timeout = ms;\n\t\t\t\t\t\t\treturn complete;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tasync(value) {\n\t\t\t\t\t\t\t_async = value;\n\t\t\t\t\t\t\treturn complete;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbuild(): TypedConstraintDef<M> {\n\t\t\t\t\t\t\tconst def: TypedConstraintDef<M> = {\n\t\t\t\t\t\t\t\twhen: condition,\n\t\t\t\t\t\t\t\trequire: req,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tif (_priority !== undefined) def.priority = _priority;\n\t\t\t\t\t\t\tif (_after !== undefined) def.after = _after;\n\t\t\t\t\t\t\tif (_deps !== undefined) def.deps = _deps;\n\t\t\t\t\t\t\tif (_timeout !== undefined) def.timeout = _timeout;\n\t\t\t\t\t\t\tif (_async !== undefined) def.async = _async;\n\t\t\t\t\t\t\treturn def;\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\n\t\t\t\t\treturn complete;\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\n// ============================================================================\n// when() Shorthand\n// ============================================================================\n\n/**\n * Create a WhenConstraint — an immutable, chainable object that produces\n * a plain TypedConstraintDef<M> when spread or assigned.\n */\nfunction createWhenConstraint<M extends ModuleSchema>(\n\tbase: TypedConstraintDef<M>,\n): WhenConstraint<M> {\n\tconst obj = { ...base } as WhenConstraint<M>;\n\n\tobj.withPriority = (n: number) =>\n\t\tcreateWhenConstraint<M>({ ...base, priority: n });\n\n\tobj.withAfter = (...ids: string[]) =>\n\t\tcreateWhenConstraint<M>({\n\t\t\t...base,\n\t\t\tafter: base.after ? [...base.after, ...ids] : [...ids],\n\t\t});\n\n\tobj.withDeps = (...keys: string[]) =>\n\t\tcreateWhenConstraint<M>({\n\t\t\t...base,\n\t\t\tdeps: base.deps ? [...base.deps, ...keys] : [...keys],\n\t\t});\n\n\tobj.withTimeout = (ms: number) =>\n\t\tcreateWhenConstraint<M>({ ...base, timeout: ms });\n\n\tobj.withAsync = (value: boolean) =>\n\t\tcreateWhenConstraint<M>({ ...base, async: value });\n\n\treturn obj;\n}\n\n/**\n * Quick shorthand for creating constraints.\n * Returns a valid constraint directly (no `.build()` needed).\n *\n * @example\n * ```typescript\n * const pause = when<typeof schema>(f => f.errors > 3)\n * .require({ type: 'PAUSE' });\n *\n * // With optional chaining (immutable — returns new constraint)\n * const halt = when<typeof schema>(f => f.errors > 10)\n * .require({ type: 'HALT' })\n * .withPriority(100)\n * .withAfter('healthCheck');\n * ```\n */\nexport function when<M extends ModuleSchema>(\n\tcondition: WhenFn<M>,\n): WhenBuilder<M> {\n\treturn {\n\t\trequire(req: RequireValue<M>): WhenConstraint<M> {\n\t\t\treturn createWhenConstraint<M>({ when: condition, require: req });\n\t\t},\n\t};\n}\n","/**\n * System Builder API\n *\n * Fluent builder for creating Directive systems.\n *\n * @example Single module\n * ```typescript\n * import { system } from '@directive-run/core';\n *\n * const sys = system()\n * .module(counterModule)\n * .plugins([loggingPlugin()])\n * .debug({ timeTravel: true })\n * .build();\n * ```\n *\n * @example Multiple modules\n * ```typescript\n * const sys = system()\n * .modules({ auth: authModule, cart: cartModule })\n * .plugins([loggingPlugin()])\n * .build();\n * ```\n */\n\nimport { createSystem } from \"./system.js\";\nimport type {\n\tModuleSchema,\n\tModuleDef,\n\tModulesMap,\n\tPlugin,\n\tDebugConfig,\n\tErrorBoundaryConfig,\n\tInferFacts,\n\tExtractSchema,\n\tSingleModuleSystem,\n\tNamespacedSystem,\n} from \"./types.js\";\n\n// ============================================================================\n// Builder Types\n// ============================================================================\n\n/** Initial builder — must choose .module() or .modules() */\nexport interface SystemBuilderStart {\n\tmodule<S extends ModuleSchema>(mod: ModuleDef<S>): SingleModuleSystemBuilder<S>;\n\tmodules<const Modules extends ModulesMap>(mods: Modules): NamespacedSystemBuilder<Modules>;\n}\n\n/** Builder for single-module system */\nexport interface SingleModuleSystemBuilder<S extends ModuleSchema> {\n\tplugins(plugins: Array<Plugin<ModuleSchema>>): SingleModuleSystemBuilder<S>;\n\tdebug(config: DebugConfig): SingleModuleSystemBuilder<S>;\n\terrorBoundary(config: ErrorBoundaryConfig): SingleModuleSystemBuilder<S>;\n\ttickMs(ms: number): SingleModuleSystemBuilder<S>;\n\tzeroConfig(enabled?: boolean): SingleModuleSystemBuilder<S>;\n\tinitialFacts(facts: Partial<InferFacts<S>>): SingleModuleSystemBuilder<S>;\n\tbuild(): SingleModuleSystem<S>;\n}\n\n/** Builder for namespaced multi-module system */\nexport interface NamespacedSystemBuilder<Modules extends ModulesMap> {\n\tplugins(plugins: Array<Plugin<ModuleSchema>>): NamespacedSystemBuilder<Modules>;\n\tdebug(config: DebugConfig): NamespacedSystemBuilder<Modules>;\n\terrorBoundary(config: ErrorBoundaryConfig): NamespacedSystemBuilder<Modules>;\n\ttickMs(ms: number): NamespacedSystemBuilder<Modules>;\n\tzeroConfig(enabled?: boolean): NamespacedSystemBuilder<Modules>;\n\tinitialFacts(facts: Partial<{\n\t\t[K in keyof Modules]: Partial<InferFacts<ExtractSchema<Modules[K]>>>;\n\t}>): NamespacedSystemBuilder<Modules>;\n\tinitOrder(order: \"auto\" | \"declaration\" | Array<keyof Modules & string>): NamespacedSystemBuilder<Modules>;\n\tbuild(): NamespacedSystem<Modules>;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Create a system using the fluent builder pattern.\n * Choose `.module()` for single-module or `.modules()` for namespaced.\n *\n * @example\n * ```typescript\n * const sys = system()\n * .module(counterModule)\n * .plugins([loggingPlugin()])\n * .build();\n * ```\n */\nexport function system(): SystemBuilderStart {\n\treturn {\n\t\tmodule<S extends ModuleSchema>(mod: ModuleDef<S>): SingleModuleSystemBuilder<S> {\n\t\t\treturn createSingleBuilder<S>(mod);\n\t\t},\n\t\tmodules<const Modules extends ModulesMap>(mods: Modules): NamespacedSystemBuilder<Modules> {\n\t\t\treturn createNamespacedBuilder<Modules>(mods);\n\t\t},\n\t};\n}\n\nfunction createSingleBuilder<S extends ModuleSchema>(\n\tmod: ModuleDef<S>,\n): SingleModuleSystemBuilder<S> {\n\tlet _plugins: Array<Plugin<ModuleSchema>> | undefined;\n\tlet _debug: DebugConfig | undefined;\n\tlet _errorBoundary: ErrorBoundaryConfig | undefined;\n\tlet _tickMs: number | undefined;\n\tlet _zeroConfig: boolean | undefined;\n\tlet _initialFacts: Partial<InferFacts<S>> | undefined;\n\n\tconst builder: SingleModuleSystemBuilder<S> = {\n\t\tplugins(plugins) {\n\t\t\t_plugins = plugins;\n\t\t\treturn builder;\n\t\t},\n\t\tdebug(config) {\n\t\t\t_debug = config;\n\t\t\treturn builder;\n\t\t},\n\t\terrorBoundary(config) {\n\t\t\t_errorBoundary = config;\n\t\t\treturn builder;\n\t\t},\n\t\ttickMs(ms) {\n\t\t\t_tickMs = ms;\n\t\t\treturn builder;\n\t\t},\n\t\tzeroConfig(enabled = true) {\n\t\t\t_zeroConfig = enabled;\n\t\t\treturn builder;\n\t\t},\n\t\tinitialFacts(facts) {\n\t\t\t_initialFacts = facts;\n\t\t\treturn builder;\n\t\t},\n\t\tbuild(): SingleModuleSystem<S> {\n\t\t\treturn createSystem<S>({\n\t\t\t\tmodule: mod,\n\t\t\t\tplugins: _plugins,\n\t\t\t\tdebug: _debug,\n\t\t\t\terrorBoundary: _errorBoundary,\n\t\t\t\ttickMs: _tickMs,\n\t\t\t\tzeroConfig: _zeroConfig,\n\t\t\t\tinitialFacts: _initialFacts,\n\t\t\t});\n\t\t},\n\t};\n\n\treturn builder;\n}\n\nfunction createNamespacedBuilder<Modules extends ModulesMap>(\n\tmods: Modules,\n): NamespacedSystemBuilder<Modules> {\n\tlet _plugins: Array<Plugin<ModuleSchema>> | undefined;\n\tlet _debug: DebugConfig | undefined;\n\tlet _errorBoundary: ErrorBoundaryConfig | undefined;\n\tlet _tickMs: number | undefined;\n\tlet _zeroConfig: boolean | undefined;\n\t// biome-ignore lint/suspicious/noExplicitAny: Partial namespaced facts typing\n\tlet _initialFacts: any;\n\tlet _initOrder: \"auto\" | \"declaration\" | Array<keyof Modules & string> | undefined;\n\n\tconst builder: NamespacedSystemBuilder<Modules> = {\n\t\tplugins(plugins) {\n\t\t\t_plugins = plugins;\n\t\t\treturn builder;\n\t\t},\n\t\tdebug(config) {\n\t\t\t_debug = config;\n\t\t\treturn builder;\n\t\t},\n\t\terrorBoundary(config) {\n\t\t\t_errorBoundary = config;\n\t\t\treturn builder;\n\t\t},\n\t\ttickMs(ms) {\n\t\t\t_tickMs = ms;\n\t\t\treturn builder;\n\t\t},\n\t\tzeroConfig(enabled = true) {\n\t\t\t_zeroConfig = enabled;\n\t\t\treturn builder;\n\t\t},\n\t\tinitialFacts(facts) {\n\t\t\t_initialFacts = facts;\n\t\t\treturn builder;\n\t\t},\n\t\tinitOrder(order) {\n\t\t\t_initOrder = order;\n\t\t\treturn builder;\n\t\t},\n\t\tbuild(): NamespacedSystem<Modules> {\n\t\t\treturn createSystem<Modules>({\n\t\t\t\tmodules: mods,\n\t\t\t\tplugins: _plugins,\n\t\t\t\tdebug: _debug,\n\t\t\t\terrorBoundary: _errorBoundary,\n\t\t\t\ttickMs: _tickMs,\n\t\t\t\tzeroConfig: _zeroConfig,\n\t\t\t\tinitialFacts: _initialFacts,\n\t\t\t\tinitOrder: _initOrder,\n\t\t\t});\n\t\t},\n\t};\n\n\treturn builder;\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\t/** Number of pending (unmet) requirements of this type */\n\tpending: number;\n\t/** Number of inflight (being resolved) requirements of this type */\n\tinflight: number;\n\t/** Number of failed requirements of this type */\n\tfailed: number;\n\t/** Whether any requirements of this type are loading (pending or inflight) */\n\tisLoading: boolean;\n\t/** Whether any requirements of this type have failed */\n\thasError: boolean;\n\t/** Last error for this type (if any) */\n\tlastError: Error | null;\n}\n\n/** Status tracking state */\ninterface StatusState {\n\tpending: Map<string, Set<string>>; // type -> set of requirement IDs\n\tinflight: Map<string, Set<string>>; // type -> set of requirement IDs\n\tfailed: Map<string, Set<string>>; // type -> set of requirement IDs\n\terrors: Map<string, Error>; // type -> last error\n\tlisteners: 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\tplugin: Plugin<never>;\n\tgetStatus: (type: string) => RequirementTypeStatus;\n\tgetAllStatus: () => Map<string, RequirementTypeStatus>;\n\tsubscribe: (listener: () => void) => () => void;\n\treset: () => void;\n} {\n\tconst state: StatusState = {\n\t\tpending: new Map(),\n\t\tinflight: new Map(),\n\t\tfailed: new Map(),\n\t\terrors: new Map(),\n\t\tlisteners: new Set(),\n\t};\n\n\t/** Notify all listeners */\n\tfunction notify(): void {\n\t\tfor (const listener of state.listeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n\n\t/** Get or create a set for a type in a map */\n\tfunction getOrCreateSet(map: Map<string, Set<string>>, type: string): Set<string> {\n\t\tlet set = map.get(type);\n\t\tif (!set) {\n\t\t\tset = new Set();\n\t\t\tmap.set(type, set);\n\t\t}\n\t\treturn set;\n\t}\n\n\t/** Get status for a requirement type */\n\tfunction getStatus(type: string): RequirementTypeStatus {\n\t\tconst pendingSet = state.pending.get(type) ?? new Set();\n\t\tconst inflightSet = state.inflight.get(type) ?? new Set();\n\t\tconst failedSet = state.failed.get(type) ?? new Set();\n\t\tconst lastError = state.errors.get(type) ?? null;\n\n\t\treturn {\n\t\t\tpending: pendingSet.size,\n\t\t\tinflight: inflightSet.size,\n\t\t\tfailed: failedSet.size,\n\t\t\tisLoading: pendingSet.size > 0 || inflightSet.size > 0,\n\t\t\thasError: failedSet.size > 0,\n\t\t\tlastError,\n\t\t};\n\t}\n\n\t/** Get status for all tracked types */\n\tfunction getAllStatus(): Map<string, RequirementTypeStatus> {\n\t\tconst allTypes = new Set([\n\t\t\t...state.pending.keys(),\n\t\t\t...state.inflight.keys(),\n\t\t\t...state.failed.keys(),\n\t\t]);\n\n\t\tconst result = new Map<string, RequirementTypeStatus>();\n\t\tfor (const type of allTypes) {\n\t\t\tresult.set(type, getStatus(type));\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Subscribe to status changes */\n\tfunction subscribe(listener: () => void): () => void {\n\t\tstate.listeners.add(listener);\n\t\treturn () => state.listeners.delete(listener);\n\t}\n\n\t/** Reset all status */\n\tfunction reset(): void {\n\t\tstate.pending.clear();\n\t\tstate.inflight.clear();\n\t\tstate.failed.clear();\n\t\tstate.errors.clear();\n\t\tnotify();\n\t}\n\n\tconst plugin: Plugin<never> = {\n\t\tname: \"requirement-status\",\n\n\t\tonRequirementCreated(req: RequirementWithId) {\n\t\t\tconst type = req.requirement.type;\n\t\t\tgetOrCreateSet(state.pending, type).add(req.id);\n\t\t\t// Clear from failed when a new requirement is created\n\t\t\tstate.failed.get(type)?.delete(req.id);\n\t\t\tnotify();\n\t\t},\n\n\t\tonResolverStart(_resolver: string, req: RequirementWithId) {\n\t\t\tconst type = req.requirement.type;\n\t\t\t// Move from pending to inflight\n\t\t\tstate.pending.get(type)?.delete(req.id);\n\t\t\tgetOrCreateSet(state.inflight, type).add(req.id);\n\t\t\tnotify();\n\t\t},\n\n\t\tonResolverComplete(_resolver: string, req: RequirementWithId) {\n\t\t\tconst type = req.requirement.type;\n\t\t\t// Remove from inflight\n\t\t\tstate.inflight.get(type)?.delete(req.id);\n\t\t\tstate.pending.get(type)?.delete(req.id);\n\t\t\tnotify();\n\t\t},\n\n\t\tonResolverError(_resolver: string, req: RequirementWithId, error: unknown) {\n\t\t\tconst type = req.requirement.type;\n\t\t\t// Move from inflight to failed\n\t\t\tstate.inflight.get(type)?.delete(req.id);\n\t\t\tgetOrCreateSet(state.failed, type).add(req.id);\n\t\t\tstate.errors.set(type, error instanceof Error ? error : new Error(String(error)));\n\t\t\tnotify();\n\t\t},\n\n\t\tonResolverCancel(_resolver: string, req: RequirementWithId) {\n\t\t\tconst type = req.requirement.type;\n\t\t\t// Remove from all tracking\n\t\t\tstate.pending.get(type)?.delete(req.id);\n\t\t\tstate.inflight.get(type)?.delete(req.id);\n\t\t\tnotify();\n\t\t},\n\n\t\tonRequirementMet(req: RequirementWithId) {\n\t\t\tconst type = req.requirement.type;\n\t\t\t// Clean up when requirement is met\n\t\t\tstate.pending.get(type)?.delete(req.id);\n\t\t\tstate.inflight.get(type)?.delete(req.id);\n\t\t\tnotify();\n\t\t},\n\t};\n\n\treturn {\n\t\tplugin,\n\t\tgetStatus,\n\t\tgetAllStatus,\n\t\tsubscribe,\n\t\treset,\n\t};\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\tstatusPlugin: ReturnType<typeof createRequirementStatusPlugin>,\n): (type: string) => RequirementTypeStatus {\n\t// This returns a function that can be used with useSyncExternalStore\n\t// The actual hook implementation would be in the React adapter\n\treturn (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\tModuleDef,\n\tPlugin,\n\tDebugConfig,\n\tErrorBoundaryConfig,\n\tModuleSchema,\n\tSingleModuleSystem,\n} from \"../core/types.js\";\nimport { createRequirementStatusPlugin } from \"./requirement-status.js\";\n\n/** Options for createSystemWithStatus */\nexport interface CreateSystemWithStatusOptions<M extends ModuleSchema> {\n\t/** The module to use for the system */\n\tmodule: ModuleDef<M>;\n\t/** Additional plugins to include alongside the status plugin */\n\t// biome-ignore lint/suspicious/noExplicitAny: Plugin generic contravariance issues\n\tplugins?: Plugin<any>[];\n\t/** Debug configuration */\n\tdebug?: DebugConfig;\n\t/** Error boundary configuration */\n\terrorBoundary?: ErrorBoundaryConfig;\n\t/** Tick interval in milliseconds */\n\ttickMs?: number;\n\t/** Enable zero-config mode */\n\tzeroConfig?: boolean;\n\t/** Initial facts to set on the system */\n\t// biome-ignore lint/suspicious/noExplicitAny: Facts type varies by module\n\tinitialFacts?: Record<string, any>;\n}\n\n/** Return type for createSystemWithStatus */\nexport interface SystemWithStatus<M extends ModuleSchema> {\n\t/**\n\t * The Directive system instance.\n\t * This is a SingleModuleSystem - use system.facts, system.dispatch(), etc.\n\t */\n\tsystem: SingleModuleSystem<M>;\n\t/** The status plugin for use with useRequirementStatus hooks */\n\tstatusPlugin: 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\toptions: CreateSystemWithStatusOptions<M>,\n): SystemWithStatus<M> {\n\t// Create the status plugin\n\tconst statusPlugin = createRequirementStatusPlugin();\n\n\t// Add the plugin to the options\n\tconst existingPlugins = options.plugins ?? [];\n\n\t// Create the system with the status plugin included\n\t// Use type assertion to bypass overload resolution issues\n\t// biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n\tconst allPlugins = [...existingPlugins, statusPlugin.plugin] as Plugin<any>[];\n\t// biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n\tconst system = createSystem({\n\t\tmodule: options.module,\n\t\tplugins: allPlugins,\n\t\tdebug: options.debug,\n\t\terrorBoundary: options.errorBoundary,\n\t\ttickMs: options.tickMs,\n\t\tzeroConfig: options.zeroConfig,\n\t\tinitialFacts: options.initialFacts,\n\t// biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n\t} as any);\n\n\treturn {\n\t\t// The system returned by createSystem with a single module is a SingleModuleSystem\n\t\tsystem: system as SingleModuleSystem<M>,\n\t\tstatusPlugin,\n\t};\n}\n","/**\n * Migration Utilities for Directive\n *\n * Helpers for migrating from Redux, Zustand, or XState to Directive.\n * These utilities help you understand your existing state management\n * and generate equivalent Directive module structures.\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Redux slice configuration (simplified) */\nexport interface ReduxSliceConfig {\n\tname: string;\n\tinitialState: Record<string, unknown>;\n\treducers: Record<string, (state: unknown, action?: { payload?: unknown }) => void>;\n}\n\n/** Zustand store configuration (simplified) */\nexport interface ZustandStoreConfig {\n\tstate: Record<string, unknown>;\n\tactions: Record<string, (...args: unknown[]) => void>;\n}\n\n/** XState machine configuration (simplified) */\nexport interface XStateMachineConfig {\n\tid: string;\n\tinitial: string;\n\tstates: Record<string, { on?: Record<string, string | { target: string }> }>;\n\tcontext?: Record<string, unknown>;\n}\n\n/** Generated Directive module structure */\nexport interface DirectiveModuleStructure {\n\tname: string;\n\tfacts: Record<string, string>;\n\tderivations: Record<string, string>;\n\tevents: Record<string, Record<string, string>>;\n\trequirements: Record<string, unknown>;\n\tinitCode: string;\n\tderiveCode: Record<string, string>;\n\teventsCode: Record<string, string>;\n}\n\n// ============================================================================\n// Redux Migration\n// ============================================================================\n\n/**\n * Analyze a Redux slice and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const reduxConfig = {\n * name: 'counter',\n * initialState: { value: 0, status: 'idle' },\n * reducers: {\n * increment: (state) => { state.value += 1; },\n * decrement: (state) => { state.value -= 1; },\n * },\n * };\n *\n * const structure = analyzeReduxSlice(reduxConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeReduxSlice(config: ReduxSliceConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze initial state to generate facts\n\tfor (const [key, value] of Object.entries(config.initialState)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze reducers to generate events\n\tfor (const reducerName of Object.keys(config.reducers)) {\n\t\t// Simple heuristic: if reducer name suggests payload, add it\n\t\tconst hasPayload = reducerName.includes(\"By\") || reducerName.includes(\"Set\") || reducerName.includes(\"With\");\n\t\tif (hasPayload) {\n\t\t\tevents[reducerName] = { payload: \"t.object()\" };\n\t\t\teventsCode[reducerName] = `(facts, { payload }) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t} else {\n\t\t\tevents[reducerName] = {};\n\t\t\teventsCode[reducerName] = `(facts) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.initialState)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: config.name,\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Zustand Migration\n// ============================================================================\n\n/**\n * Analyze a Zustand store and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const zustandConfig = {\n * state: { count: 0, loading: false },\n * actions: {\n * increment: () => {},\n * decrement: () => {},\n * setLoading: (loading: boolean) => {},\n * },\n * };\n *\n * const structure = analyzeZustandStore(zustandConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeZustandStore(config: ZustandStoreConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze state\n\tfor (const [key, value] of Object.entries(config.state)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze actions\n\tfor (const actionName of Object.keys(config.actions)) {\n\t\tevents[actionName] = {};\n\t\teventsCode[actionName] = `(facts) => {\\n // TODO: Implement ${actionName}\\n }`;\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.state)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: \"store\",\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// XState Migration\n// ============================================================================\n\n/**\n * Analyze an XState machine and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const xstateConfig = {\n * id: 'toggle',\n * initial: 'inactive',\n * states: {\n * inactive: { on: { TOGGLE: 'active' } },\n * active: { on: { TOGGLE: 'inactive' } },\n * },\n * };\n *\n * const structure = analyzeXStateMachine(xstateConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeXStateMachine(config: XStateMachineConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {\n\t\tstate: `t.string<${Object.keys(config.states).map(s => `'${s}'`).join(\" | \")}>()`,\n\t};\n\tconst derivations: Record<string, string> = {};\n\tconst deriveCode: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Add context to facts\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tfacts[key] = inferTypeString(value);\n\t\t}\n\t}\n\n\t// Generate state derivations (isActive, isInactive, etc.)\n\tfor (const stateName of Object.keys(config.states)) {\n\t\tconst derivationName = `is${capitalize(stateName)}`;\n\t\tderivations[derivationName] = \"t.boolean()\";\n\t\tderiveCode[derivationName] = `(facts) => facts.state === '${stateName}'`;\n\t}\n\n\t// Collect all events and their transitions\n\tconst eventTransitions = new Map<string, Map<string, string>>();\n\tfor (const [stateName, stateConfig] of Object.entries(config.states)) {\n\t\tif (!stateConfig.on) continue;\n\t\tfor (const [eventName, target] of Object.entries(stateConfig.on)) {\n\t\t\tif (!eventTransitions.has(eventName)) {\n\t\t\t\teventTransitions.set(eventName, new Map());\n\t\t\t}\n\t\t\tconst targetState = typeof target === \"string\" ? target : target.target;\n\t\t\teventTransitions.get(eventName)!.set(stateName, targetState);\n\t\t}\n\t}\n\n\t// Generate events and handlers\n\tfor (const [eventName, transitions] of eventTransitions) {\n\t\tevents[eventName] = {};\n\n\t\tif (transitions.size === 1) {\n\t\t\tconst firstEntry = [...transitions.entries()][0];\n\t\t\tconst toState = firstEntry ? firstEntry[1] : \"unknown\";\n\t\t\teventsCode[eventName] = `(facts) => {\\n facts.state = '${toState}';\\n }`;\n\t\t} else {\n\t\t\tconst cases = [...transitions.entries()]\n\t\t\t\t.map(([from, to]) => ` case '${from}': facts.state = '${to}'; break;`)\n\t\t\t\t.join(\"\\n\");\n\t\t\teventsCode[eventName] = `(facts) => {\\n switch (facts.state) {\\n${cases}\\n }\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = [` facts.state = '${config.initial}';`];\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tinitLines.push(` facts.${key} = ${JSON.stringify(value)};`);\n\t\t}\n\t}\n\tconst initCode = `(facts) => {\\n${initLines.join(\"\\n\")}\\n }`;\n\n\treturn {\n\t\tname: config.id,\n\t\tfacts,\n\t\tderivations,\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode,\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Code Generation\n// ============================================================================\n\n/**\n * Generate Directive module code from a structure.\n */\nexport function generateModuleCode(structure: DirectiveModuleStructure): string {\n\tconst lines: string[] = [\n\t\t`import { createModule, t } from '@directive-run/core';`,\n\t\t``,\n\t\t`const ${structure.name}Module = createModule('${structure.name}', {`,\n\t\t` schema: {`,\n\t\t` facts: {`,\n\t];\n\n\t// Facts\n\tfor (const [key, type] of Object.entries(structure.facts)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Derivations\n\tlines.push(` derivations: {`);\n\tfor (const [key, type] of Object.entries(structure.derivations)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Events\n\tlines.push(` events: {`);\n\tfor (const [key, schema] of Object.entries(structure.events)) {\n\t\tconst schemaStr = Object.entries(schema)\n\t\t\t.map(([k, v]) => `${k}: ${v}`)\n\t\t\t.join(\", \");\n\t\tlines.push(` ${key}: { ${schemaStr} },`);\n\t}\n\tlines.push(` },`);\n\n\t// Requirements\n\tlines.push(` requirements: {},`);\n\tlines.push(` },`);\n\n\t// Init\n\tlines.push(` init: ${structure.initCode},`);\n\n\t// Derive\n\tif (Object.keys(structure.deriveCode).length > 0) {\n\t\tlines.push(` derive: {`);\n\t\tfor (const [key, code] of Object.entries(structure.deriveCode)) {\n\t\t\tlines.push(` ${key}: ${code},`);\n\t\t}\n\t\tlines.push(` },`);\n\t}\n\n\t// Events handlers\n\tlines.push(` events: {`);\n\tfor (const [key, code] of Object.entries(structure.eventsCode)) {\n\t\tlines.push(` ${key}: ${code},`);\n\t}\n\tlines.push(` },`);\n\n\tlines.push(`});`);\n\tlines.push(``);\n\tlines.push(`export { ${structure.name}Module };`);\n\n\treturn lines.join(\"\\n\");\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Infer a t.* type string from a JavaScript value.\n */\nfunction inferTypeString(value: unknown): string {\n\tif (value === null) return \"t.object().nullable()\";\n\tif (value === undefined) return \"t.object().optional()\";\n\n\tswitch (typeof value) {\n\t\tcase \"number\":\n\t\t\treturn \"t.number()\";\n\t\tcase \"string\":\n\t\t\treturn \"t.string()\";\n\t\tcase \"boolean\":\n\t\t\treturn \"t.boolean()\";\n\t\tcase \"object\":\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\treturn \"t.array(t.object())\";\n\t\t\t}\n\t\t\treturn \"t.object()\";\n\t\tdefault:\n\t\t\treturn \"t.object()\";\n\t}\n}\n\n/**\n * Capitalize first letter.\n */\nfunction capitalize(str: string): string {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// ============================================================================\n// Migration Checklist Generator\n// ============================================================================\n\n/**\n * Generate a migration checklist for a given state management pattern.\n */\nexport function generateMigrationChecklist(\n\tsource: \"redux\" | \"zustand\" | \"xstate\",\n): string[] {\n\tconst common = [\n\t\t\"[ ] Install directive: pnpm add directive\",\n\t\t\"[ ] Create module file(s) for your state\",\n\t\t\"[ ] Define schema with facts, derivations, events\",\n\t\t\"[ ] Implement init function for initial state\",\n\t\t\"[ ] Implement event handlers\",\n\t\t\"[ ] Update imports in consuming code\",\n\t\t\"[ ] Test the new implementation\",\n\t\t\"[ ] Remove old state management code\",\n\t];\n\n\tconst sourceSpecific: Record<string, string[]> = {\n\t\tredux: [\n\t\t\t\"[ ] Convert reducers to event handlers\",\n\t\t\t\"[ ] Convert selectors to derivations\",\n\t\t\t\"[ ] Convert thunks to constraints + resolvers\",\n\t\t\t\"[ ] Update useSelector to useDerived\",\n\t\t\t\"[ ] Update useDispatch to system.dispatch\",\n\t\t],\n\t\tzustand: [\n\t\t\t\"[ ] Convert store state to facts\",\n\t\t\t\"[ ] Convert store actions to events\",\n\t\t\t\"[ ] Convert computed getters to derivations\",\n\t\t\t\"[ ] Update useStore hooks to useDirective hooks\",\n\t\t],\n\t\txstate: [\n\t\t\t\"[ ] Convert machine states to a 'state' fact\",\n\t\t\t\"[ ] Convert state checks to derivations (isActive, etc.)\",\n\t\t\t\"[ ] Convert events to Directive events\",\n\t\t\t\"[ ] Convert guards to constraint 'when' conditions\",\n\t\t\t\"[ ] Convert services/actors to constraints + resolvers\",\n\t\t\t\"[ ] Update useMachine to useDirective hooks\",\n\t\t],\n\t};\n\n\tconst specific = sourceSpecific[source] ?? [];\n\treturn [...specific, ...common];\n}\n","/**\n * @directive-run/core\n *\n * Constraint-driven runtime for TypeScript.\n *\n * Also available:\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 codemods\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\n// ============================================================================\n\nexport type {\n\t// Schema\n\tSchema,\n\tSchemaType,\n\tInferSchema,\n\tInferSchemaType,\n\t// Consolidated Module Schema\n\tModuleSchema,\n\tDerivationsSchema,\n\tEventsSchema,\n\tEventPayloadSchema,\n\tInferFacts,\n\tInferDerivations,\n\tInferSelectorState,\n\tInferEventPayloadFromSchema,\n\tInferEvents,\n\tInferRequirementPayloadFromSchema,\n\tInferRequirements,\n\tInferRequirementTypes,\n\t// Facts\n\tFacts,\n\tFactsSnapshot,\n\tFactsStore,\n\tFactChange,\n\t// Derivations\n\tDerivationsDef,\n\tDerivationState,\n\tDerivedValues,\n\tTypedDerivationsDef,\n\t// Effects\n\tEffectsDef,\n\tEffectCleanup,\n\t// Requirements\n\tRequirement,\n\tRequirementWithId,\n\tRequirementKeyFn,\n\tRequirementPayloadSchema,\n\tRequirementsSchema,\n\tRequirementOutput,\n\t// Constraints\n\tConstraintsDef,\n\tConstraintState,\n\tTypedConstraintDef,\n\tTypedConstraintsDef,\n\t// Resolvers\n\tResolversDef,\n\tResolverContext,\n\tResolverStatus,\n\tRetryPolicy,\n\tBatchConfig,\n\tBatchItemResult,\n\tBatchResolveResults,\n\tTypedResolverContext,\n\tTypedResolverDef,\n\tTypedResolversDef,\n\t// Plugins\n\tPlugin,\n\tReconcileResult,\n\tSnapshot,\n\tRecoveryStrategy,\n\t// Errors\n\tErrorSource,\n\tErrorBoundaryConfig,\n\tRetryLaterConfig,\n\tCircuitBreakerConfig,\n\tCircuitBreakerState,\n\t// Module\n\tModuleDef,\n\tModuleHooks,\n\tTypedEventsDef,\n\t// Events\n\tEventsDef,\n\tSystemEvent,\n\tEventsAccessorFromSchema,\n\tDispatchEventsFromSchema,\n\tFlexibleEventHandler,\n\t// System\n\tSystem,\n\tSystemConfig,\n\tSystemInspection,\n\tSystemSnapshot,\n\tDistributableSnapshotOptions,\n\tDistributableSnapshot,\n\tDebugConfig,\n\tTimeTravelAPI,\n\tTimeTravelState,\n\tSnapshotMeta,\n\tRequirementExplanation,\n\t// Accessors\n\tDeriveAccessor,\n\tEventsAccessor,\n\tFactKeys,\n\tFactReturnType,\n\tDerivationKeys,\n\tDerivationReturnType,\n\tObservableKeys,\n\t// Typed Helper Utilities\n\tTypedConstraint,\n\tTypedResolver,\n\t// Composition (Namespaced Multi-Module)\n\tModulesMap,\n\tNamespacedFacts,\n\tMutableNamespacedFacts,\n\tNamespacedDerivations,\n\tUnionEvents,\n\tNamespacedSystem,\n\tNamespacedEventsAccessor,\n\tCreateSystemOptionsNamed,\n\t// Single Module (no namespace)\n\tCreateSystemOptionsSingle,\n\tSingleModuleSystem,\n\t// Type Guards\n\tSystemMode,\n\tAnySystem,\n\t// Cross-Module Dependencies (for modules)\n\tCrossModuleDeps,\n\tCrossModuleFactsWithSelf,\n\tCrossModuleDerivationFn,\n\tCrossModuleDerivationsDef,\n\tCrossModuleConstraintDef,\n\tCrossModuleConstraintsDef,\n\tCrossModuleEffectDef,\n\tCrossModuleEffectsDef,\n} from \"./core/types.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 * Provides type-safe schema definitions with optional runtime validation:\n *\n * **Basic Types:**\n * - `t.string<T>()` - String type (with optional literal union)\n * - `t.number()` - Number type with `.min()` and `.max()` validation\n * - `t.boolean()` - Boolean type\n * - `t.bigint()` - BigInt type for large integers\n *\n * **Complex Types:**\n * - `t.array<T>()` - Array type with `.of()`, `.nonEmpty()`, `.minLength()`, `.maxLength()`\n * - `t.object<T>()` - Object type with `.shape()`, `.nonNull()`, `.hasKeys()`\n * - `t.record<V>(valueType)` - Record/map type `Record<string, V>`\n * - `t.tuple(types...)` - Fixed-length tuple type\n * - `t.union(types...)` - Union of multiple types\n *\n * **Literal & Enum Types:**\n * - `t.enum(...values)` - String enum from literal values\n * - `t.literal(value)` - Exact value matching (string, number, or boolean)\n *\n * **Wrappers:**\n * - `t.nullable(type)` - Nullable wrapper (`T | null`)\n * - `t.optional(type)` - Optional wrapper (`T | undefined`)\n *\n * **Validation Types:**\n * - `t.date()` - Date type\n * - `t.uuid()` - UUID string format\n * - `t.email()` - Email string format\n * - `t.url()` - URL string format\n *\n * **Chainable Methods (available on most types):**\n * - `.default(value)` - Set default value\n * - `.transform(fn)` - Transform values\n * - `.brand<B>()` - Add branded/nominal type\n * - `.describe(text)` - Add schema documentation\n * - `.refine(predicate, message)` - Custom validation with error message\n * - `.nullable()` - Make nullable (chainable alternative to `t.nullable()`)\n * - `.optional()` - Make optional (chainable alternative to `t.optional()`)\n * - `.validate(fn)` - Add custom validator\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().describe(\"User's display name\"),\n * status: t.enum(\"idle\", \"loading\", \"success\", \"error\"),\n * user: t.object<User>().nullable(),\n * config: t.object<Config>().optional(),\n * userId: t.string().brand<\"UserId\">(),\n * age: t.number().refine(n => n >= 0, \"Age must be non-negative\"),\n * },\n * derivations: {\n * doubled: t.number(),\n * },\n * events: {\n * increment: {},\n * setStatus: { status: t.enum(\"idle\", \"loading\", \"success\", \"error\") },\n * },\n * requirements: {},\n * };\n * ```\n */\nexport { t, type Branded, type ExtendedSchemaType, type ChainableSchemaType } from \"./core/facts.js\";\n\n// ============================================================================\n// Module & System\n// ============================================================================\n\nexport {\n\tcreateModule,\n\tcreateModuleFactory,\n\ttype ModuleConfig,\n\ttype ModuleConfigWithDeps,\n} from \"./core/module.js\";\nexport { createSystem } from \"./core/system.js\";\nexport {\n\tmodule,\n\ttype ModuleBuilder,\n} from \"./core/builder.js\";\nexport {\n\tconstraint,\n\twhen,\n\ttype ConstraintBuilderStart,\n\ttype ConstraintBuilderWithWhen,\n\ttype ConstraintBuilderComplete,\n\ttype WhenConstraint,\n\ttype WhenBuilder,\n} from \"./core/constraint-builders.js\";\nexport {\n\tsystem,\n\ttype SystemBuilderStart,\n\ttype SingleModuleSystemBuilder,\n\ttype NamespacedSystemBuilder,\n} from \"./core/system-builder.js\";\n\n// Convenience helper for status plugin setup\nexport { createSystemWithStatus } from \"./utils/system-with-status.js\";\n\n// Helper factory functions for external constraint/resolver definitions\nexport {\n\tconstraintFactory,\n\tresolverFactory,\n\ttypedConstraint,\n\ttypedResolver,\n} from \"./core/types.js\";\n\n// ============================================================================\n// Requirements Helpers\n// ============================================================================\n\nexport {\n\treq,\n\tforType,\n\tisRequirementType,\n\tgenerateRequirementId,\n\tRequirementSet,\n} from \"./core/requirements.js\";\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nexport {\n\tisSingleModuleSystem,\n\tisNamespacedSystem,\n} from \"./core/types/composition.js\";\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/**\n * Backoff strategy constants for retry policies.\n * Use for autocomplete when configuring resolver retry policies.\n *\n * @example\n * ```ts\n * import { Backoff } from '@directive-run/core';\n *\n * const resolver = {\n * requirement: \"FETCH_DATA\",\n * retry: {\n * attempts: 3,\n * backoff: Backoff.Exponential, // Autocomplete-friendly!\n * initialDelay: 100,\n * },\n * resolve: async (req, ctx) => { ... },\n * };\n * ```\n */\nexport const Backoff = {\n\t/** No delay between retries */\n\tNone: \"none\",\n\t/** Linear delay increase (initialDelay * attempt) */\n\tLinear: \"linear\",\n\t/** Exponential delay increase (initialDelay * 2^attempt) */\n\tExponential: \"exponential\",\n} as const;\n\n// ============================================================================\n// Lower-level APIs (for advanced use)\n// ============================================================================\n\nexport { createFacts, createFactsStore, createFactsProxy } from \"./core/facts.js\";\nexport { createDerivationsManager } from \"./core/derivations.js\";\nexport { createEffectsManager } from \"./core/effects.js\";\nexport { createConstraintsManager } from \"./core/constraints.js\";\nexport { createResolversManager, type InflightInfo } from \"./core/resolvers.js\";\nexport { createPluginManager } from \"./core/plugins.js\";\nexport {\n\tcreateErrorBoundaryManager,\n\tcreateRetryLaterManager,\n\ttype PendingRetry,\n} from \"./core/errors.js\";\nexport { createTimeTravelManager, createDisabledTimeTravel } from \"./utils/time-travel.js\";\nexport { createEngine } from \"./core/engine.js\";\n\n// ============================================================================\n// Tracking (for custom derivations)\n// ============================================================================\n\nexport {\n\tgetCurrentTracker,\n\tisTracking,\n\twithTracking,\n\twithoutTracking,\n\ttrackAccess,\n} from \"./core/tracking.js\";\n\n// ============================================================================\n// Requirement Status Utilities\n// ============================================================================\n\nexport {\n\tcreateRequirementStatusPlugin,\n\tcreateStatusHook,\n\ttype RequirementTypeStatus,\n} from \"./utils/requirement-status.js\";\n\n// ============================================================================\n// Distributable Snapshot Utilities\n// ============================================================================\n\nexport {\n\tshallowEqual,\n\tisSnapshotExpired,\n\tvalidateSnapshot,\n\tdiffSnapshots,\n\tsignSnapshot,\n\tverifySnapshotSignature,\n\tisSignedSnapshot,\n\ttype DistributableSnapshotLike,\n\ttype SnapshotDiff,\n\ttype SnapshotDiffEntry,\n\ttype SignedSnapshot,\n} from \"./utils/utils.js\";\n\n// ============================================================================\n// Migration Utilities\n// ============================================================================\n\nexport {\n\tanalyzeReduxSlice,\n\tanalyzeZustandStore,\n\tanalyzeXStateMachine,\n\tgenerateModuleCode,\n\tgenerateMigrationChecklist,\n\ttype ReduxSliceConfig,\n\ttype ZustandStoreConfig,\n\ttype XStateMachineConfig,\n\ttype DirectiveModuleStructure,\n} from \"./utils/migration.js\";\n"]}