@directive-run/core 0.8.7 → 0.8.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/adapter-utils.cjs +1 -1
  2. package/dist/adapter-utils.js +1 -1
  3. package/dist/{chunk-W4VP6SVP.cjs → chunk-CFSW3RP5.cjs} +3 -3
  4. package/dist/{chunk-W4VP6SVP.cjs.map → chunk-CFSW3RP5.cjs.map} +1 -1
  5. package/dist/{chunk-O75OISQ2.js → chunk-EFBBEXDA.js} +2 -2
  6. package/dist/{chunk-O75OISQ2.js.map → chunk-EFBBEXDA.js.map} +1 -1
  7. package/dist/chunk-ER6QUYTL.cjs +2 -0
  8. package/dist/{chunk-PK2EH26L.cjs.map → chunk-ER6QUYTL.cjs.map} +1 -1
  9. package/dist/chunk-ISYFVEHR.js +3 -0
  10. package/dist/chunk-ISYFVEHR.js.map +1 -0
  11. package/dist/chunk-L3SUAAPM.cjs +3 -0
  12. package/dist/chunk-L3SUAAPM.cjs.map +1 -0
  13. package/dist/{chunk-KXIHB2EB.js → chunk-LB6PNML4.js} +3 -3
  14. package/dist/{chunk-KXIHB2EB.js.map → chunk-LB6PNML4.js.map} +1 -1
  15. package/dist/index.cjs +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/internals.cjs +1 -1
  18. package/dist/internals.d.cts +4 -0
  19. package/dist/internals.d.ts +4 -0
  20. package/dist/internals.js +1 -1
  21. package/dist/system-3H5V4HJZ.js +2 -0
  22. package/dist/{system-QNIJLXKW.js.map → system-3H5V4HJZ.js.map} +1 -1
  23. package/dist/system-IJKVTF3C.cjs +2 -0
  24. package/dist/{system-HQCNSUY5.cjs.map → system-IJKVTF3C.cjs.map} +1 -1
  25. package/dist/testing.cjs +1 -1
  26. package/dist/testing.js +1 -1
  27. package/dist/worker.cjs +1 -1
  28. package/dist/worker.js +1 -1
  29. package/package.json +1 -1
  30. package/dist/chunk-FVPJU5F3.js +0 -3
  31. package/dist/chunk-FVPJU5F3.js.map +0 -1
  32. package/dist/chunk-PK2EH26L.cjs +0 -2
  33. package/dist/chunk-SGMWAVHO.cjs +0 -3
  34. package/dist/chunk-SGMWAVHO.cjs.map +0 -1
  35. package/dist/system-HQCNSUY5.cjs +0 -2
  36. package/dist/system-QNIJLXKW.js +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/types/errors.ts","../src/core/types/helpers.ts","../src/core/types/composition.ts","../src/utils/history.ts","../src/core/requirements.ts","../src/core/constraints.ts","../src/core/derivations.ts","../src/core/effects.ts","../src/core/errors.ts","../src/core/facts.ts","../src/core/plugins.ts","../src/core/resolvers.ts","../src/core/engine-accessors.ts","../src/core/engine-definitions.ts","../src/core/engine-trace.ts","../src/core/engine.ts"],"names":["DirectiveError","message","source","sourceId","context","recoverable","createConstraintFactory","constraint","createResolverFactory","resolver","typedConstraint","typedResolver","isSingleModuleSystem","system","isNamespacedSystem","resolveHistoryOption","option","createHistoryManager","options","historyOption","facts","store","onSnapshot","onHistoryChange","isEnabled","maxSnapshots","snapshots","currentIndex","nextId","paused","restoring","changesets","pendingChangesetLabel","pendingChangesetStart","getCurrentFacts","serializeFacts","factsObj","deserializeFacts","serialized","isPrototypeSafe","key","value","trigger","snapshot","steps","fromIndex","toIndex","cs","c","earlierCs","snapshotId","index","s","json","data","snap","error","label","createDisabledHistory","noopSnapshot","reqIdCache","generateRequirementId","req","keyFn","cached","type","rest","sortedRest","stableStringify","id","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","addReverseDep","depId","dependentId","buildReverseDependencyMap","def","topoVisit","path","visited","visiting","postOrder","cycleStart","cycle","detectCyclesAndComputeTopoOrder","warnUnknownAfterRefs","isAsyncConstraint","initState","isAsync","state","getState","depsEqual","a","b","dep","removeFromFactMap","deps","constraints","addToFactMap","clearConstraintDeps","clearReverseDeps","depSet","updateDependencies","newDeps","oldDeps","evaluateWhenPredicate","tracked","withTracking","recordConstraintResult","result","recordConstraintError","handleRuntimeAsyncResult","promise","asyncResult","evaluateSync","evaluateAsync","timeout","depsSet","resultPromise","withTimeout","MAX_REQUIREMENTS_WARNING_THRESHOLD","normalizeRequirements","output","constraintId","filtered","r","getRequirements","requireDef","mergeDependencies","additionalDeps","existingDeps","sortedConstraintIds","getSortedConstraintIds","stateA","priorityDiff","topoA","topoB","warnAsyncWithoutDeps","defs","isAfterDepSatisfied","areAfterDependenciesSatisfied","handleInactiveConstraint","whenDeps","updateConstraintDeps","requireDeps","combinedDeps","emitConstraintRequirements","reqs","requirements","reqsWithId","reqWithId","addCachedRequirements","processConstraintResult","active","partitionByReadiness","constraintIds","blocked","ready","lastReqs","evaluateSyncBatch","syncIds","unexpectedAsync","awaitAndProcess","pairs","results","evaluateConstraintBatch","syncConstraints","asyncConstraints","asyncPairs","collectAffectedByKeys","changedKeys","into","collectDirtyConstraints","computeAffectedConstraints","affected","carryForwardRequirements","allIds","allConstraintIds","constraintsToEvaluate","remainingToEvaluate","maxPasses","previousRemaining","factKey","dependentConstraints","dependents","newDefs","hasAfterDeps","merged","requirementType","createDerivationsManager","onCompute","onInvalidate","listeners","factToDerivedDeps","derivedToDerivedDeps","invalidationDepth","pendingNotifications","isFlushing","MAX_FLUSH_ITERATIONS","derivedProxy","removeDepLink","map","addDepLink","removeOwnDepLinks","invalidateDependentsOf","dependent","invalidateDerivation","purgeFromMaps","computeDerivation","oldValue","setsEqual","notifyListeners","ids","fns","listener","flushNotifications","iterations","remaining","enqueueDependents","queue","startId","_","prop","BLOCKED_PROPS","trackAccess","factKeys","idStr","listenerSet","fn","STABLE_THRESHOLD","createEffectsManager","onRun","previousSnapshot","stopped","createSnapshot","resetStability","hasOverlap","shouldRun","runCleanup","storeCleanup","runBatchedEffect","effectPromise","areDepsEqual","updateDepStability","trackedDeps","runAutoTrackedEffect","trackingResult","runEffect","effectsToRun","effectIds","createRetryLaterManager","config","delayMs","maxRetries","backoffMultiplier","maxDelayMs","pendingRetries","calculateDelay","attempt","delay","callback","entry","now","dueRetries","DEFAULT_STRATEGIES","createErrorBoundaryManager","onRecovery","errors","maxErrors","retryLaterManager","retryAttempts","MAX_RETRY_SOURCES","toDirectiveError","getStrategy","handler","e","recordAndNotifyError","directiveError","processRetryLater","oldest","strategy","safeStringify","maxLength","createFactsStore","schema","onChange","onBatch","isTypeAssertionSchema","validate","strictKeys","redactErrors","knownKeys","keyListeners","allListeners","batching","batchChanges","dirtyKeys","isNotifying","pendingNonBatchedChanges","MAX_NOTIFY_ITERATIONS","isZodSchema","getExpectedType","schemaType","st","formatValueForError","describeValueType","validateZod","valueType","valuePreview","errorMessage","expectedType","getIndexHint","hint","validateSchemaType","validators","i","validator","indexHint","validatorHint","validateUnknownKey","validateValue","notifyKey","notifyAll","notifyNonBatched","prev","drainDeferredNotifications","deferred","change","flush","keys","keyStr","set","newSchema","nestedProxyCache","wrapWithNestedWarning","obj","rootKey","target","wrapped","newValue","createFactsProxy","withoutTracking","createFacts","createPluginManager","plugins","safeCall","safeCallAsync","broadcast","hook","args","plugin","p","name","DEFAULT_RETRY","DEFAULT_BATCH","policy","backoff","initialDelay","maxDelay","validateDefinitions","createResolversManager","onStart","onComplete","onRetry","onCancel","onResolutionComplete","inflight","statuses","MAX_STATUSES","batches","resolversByType","MAX_RESOLVER_CACHE","cleanupStatuses","entriesToRemove","iterator","hasStringRequirement","hasFunctionRequirement","resolverHandles","findResolverInCache","reqType","cacheResolverForType","resolverId","findResolver","createContext","signal","handleRetryError","retryPolicy","controller","normalizedError","resolve","timeoutId","abortHandler","invokeResolve","resolvePromise","recordSuccess","startedAt","duration","recordError","attempts","updateInflightAttempt","reqId","processRetryError","notifyRetry","executeResolve","lastError","outcome","next","awaitWithTimeout","timeoutMessage","executeWithResults","reqPayloads","ctx","hasFailures","executeAllOrNothing","recordBatchErrors","executeBatchFallback","executeBatchAttempt","notifyBatchRetry","nextAttempt","runBatchRetryLoop","executeBatch","DEFAULT_MAX_QUEUE_SIZE","clearBatchTimer","batch","ensureBatch","addToBatch","batchConfig","effectiveMax","processBatch","requirementId","idx","status","createDeriveAccessor","mergedDerive","getDerivation","deriveMethods","createEventsAccessor","mergedEvents","dispatchEvent","payload","RESERVED_DERIVE_NAMES","createDefinitionsRegistry","mergedConstraints","mergedResolvers","mergedEffects","constraintsManager","resolversManager","derivationsManager","effectsManager","pluginManager","scheduleReconcile","maxDeferredRegistrations","dynamicIds","originals","deferredRegistrations","validateDerivationId","typeDescriptors","validateDefId","applyRegister","desc","applyAssign","original","applyUnregister","flushDeferred","ops","op","guardedOp","isDestroyed","isReconciling","createTraceManager","traceConfig","maxRuns","traceEntries","traceById","traceIdCounter","currentTrace","pendingFactChanges","resolverTraceMap","traceInflightCount","traceStartMs","traceCache","traceCacheVersion","currentCacheVersion","traceStats","finalizeTrace","traceId","startMs","buildCausalChain","updateTraceStats","decrementTraceInflightInternal","evictOldestTrace","evicted","rId","parts","fc","d","rs","resolverCount","factChangeCount","anomalies","pushTraceEntry","hasTraceActivity","reconcileStartMs","inflightCount","createEngine","mergedSchema","schemaOwners","definitionOwners","module","validateKeys","section","existingOwner","checkCollisions","owner","snapshotEventNames","m","mod","eventName","dispatchDepth","shouldTakeSnapshot","derivationNames","errorBoundary","retryLaterTimer","invalidateManyDerivations","historyRef","traceManager","traceEnabled","changes","syncResolverKeys","notifySettlementChange","historyListeners","notifyHistoryChange","historyManager","from","to","settlementListeners","MAX_RECONCILE_DEPTH","MAX_DEFERRED_REGISTRATIONS","reconcileDepth","reconcile","keysForConstraints","currentRequirements","currentSet","hitConstraintIds","cId","cState","cDeps","inflightNow","inflightById","info","inflightInfo","inflightMap","dispatchEventByName","deriveAccessor","eventsAccessor","intervalMs","event","derivationId","derivationIds","unsubs","u","isEqual","previousValue","old","predicate","reject","unsub","timer","cleanup","current","constraintState","resolverStatus","relevantFacts","lines","reqDetails","k","v","factEntries","prefix","valueStr","maxWait","isSettled","done","unsubscribe","details","unmet","includeDerivations","excludeDerivations","includeFacts","ttlSeconds","metadata","includeVersion","allDerivationKeys","allDerivationSet","derivationKeys","unknown","excludeSet","factsSnapshot","allFactKeys","createdAt","hashObject","previousVersion","registerModule","existingFactKeys"],"mappings":"qHA2CO,IAAMA,EAAAA,CAAN,cAA6B,KAAM,CACxC,YACEC,CAAAA,CACgBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAuB,IAAA,CACvC,CACA,KAAA,CAAMJ,CAAO,CAAA,CALG,IAAA,CAAA,MAAA,CAAAC,CAAAA,CACA,IAAA,CAAA,QAAA,CAAAC,EACA,IAAA,CAAA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAA,WAAA,CAAAC,CAAAA,CAGhB,IAAA,CAAK,IAAA,CAAO,iBACd,CACF,ECyFO,SAASC,EAAAA,EAA4C,CAC1D,OAAO,CAIL,MAAA,CACEC,CAAAA,CACuB,CACvB,OAAOA,CACT,CACF,CACF,CAmBO,SAASC,EAAAA,EAA0C,CACxD,OAAO,CAIL,MAAA,CACEC,CAAAA,CACqB,CACrB,OAAOA,CACT,CACF,CACF,CAkBO,SAASC,GAGdH,CAAAA,CAA0D,CAC1D,OAAOA,CACT,CAgBO,SAASI,EAAAA,CAGdF,CAAAA,CAAoD,CACpD,OAAOA,CACT,CCunBO,SAASG,EAAAA,CAAqBC,CAAAA,CAA4B,CAC/D,OAAOA,CAAAA,CAAO,KAAA,GAAU,QAC1B,CAgBO,SAASC,EAAAA,CAAmBD,EAA4B,CAC7D,OAAOA,EAAO,KAAA,GAAU,YAC1B,CCjxBA,SAASE,EAAAA,CAAqBC,CAAAA,CAG5B,CACA,OAAI,OAAOA,GAAW,SAAA,CACb,CAAE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G,CAAAA,CAAM,SAAA,GACRma,CAAAA,CAAO,KAAA,EAAO,OAAA,GAAU/gB,EAAM,CAAA,CAE9Bqd,EAAAA,EAAkB,EAEtB,CAGCrd,EAAAA,CAA8C,cAAA,CAC7C6mB,EAAAA,CAGFzJ,CAAAA,CAAc,QAAA,CAASpd,EAAM,CAAA,CAG7B,IAAA,IAAW+gB,CAAAA,IAAUjQ,CAAAA,CAAO,OAAA,CAC1BiQ,CAAAA,CAAO,KAAA,EAAO,MAAA,GAAS/gB,EAAM,CAAA,CAG/B,OAAOA,EACT","file":"chunk-SGMWAVHO.cjs","sourcesContent":["/**\n * Error Types - Type definitions for error handling\n */\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\n/** Error source types */\nexport type ErrorSource =\n | \"constraint\"\n | \"resolver\"\n | \"effect\"\n | \"derivation\"\n | \"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 constructor(\n message: string,\n public readonly source: ErrorSource,\n public readonly sourceId: string,\n public readonly context?: unknown,\n public readonly recoverable: boolean = true,\n ) {\n super(message);\n this.name = \"DirectiveError\";\n }\n}\n\n/** Recovery strategy for errors */\nexport type RecoveryStrategy =\n | \"skip\"\n | \"retry\"\n | \"retry-later\"\n | \"disable\"\n | \"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 /** Delay in milliseconds before retrying (default: 1000) */\n delayMs?: number;\n /** Maximum retries before giving up (default: 3) */\n maxRetries?: number;\n /** Backoff multiplier for each retry (default: 2) */\n backoffMultiplier?: number;\n /** Maximum delay in milliseconds (default: 30000) */\n maxDelayMs?: number;\n}\n\n/** Error boundary configuration */\nexport interface ErrorBoundaryConfig {\n onConstraintError?:\n | RecoveryStrategy\n // biome-ignore lint/suspicious/noConfusingVoidType: void semantics needed for implicit no-return\n | ((error: Error, constraint: string) => RecoveryStrategy | void);\n onResolverError?:\n | RecoveryStrategy\n // biome-ignore lint/suspicious/noConfusingVoidType: void semantics needed for implicit no-return\n | ((error: Error, resolver: string) => RecoveryStrategy | void);\n onEffectError?:\n | RecoveryStrategy\n // biome-ignore lint/suspicious/noConfusingVoidType: void semantics needed for implicit no-return\n | ((error: Error, effect: string) => RecoveryStrategy | void);\n onDerivationError?:\n | RecoveryStrategy\n // biome-ignore lint/suspicious/noConfusingVoidType: void semantics needed for implicit no-return\n | ((error: Error, derivation: string) => RecoveryStrategy | void);\n onError?: (error: DirectiveError) => void;\n\n /** Configuration for retry-later strategy */\n retryLater?: RetryLaterConfig;\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 { Facts } from \"./facts.js\";\nimport type { Requirement, RequirementOutput } from \"./requirements.js\";\nimport type { BatchConfig, ResolverContext, RetryPolicy } from \"./resolvers.js\";\nimport type { Schema } from \"./schema.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 S extends Schema,\n R extends Requirement = Requirement,\n> {\n /** Priority for ordering (higher runs first) */\n priority?: number;\n /** Mark this constraint as async (avoids runtime detection) */\n async?: boolean;\n /** Condition function (sync or async) */\n when: (facts: Facts<S>) => boolean | Promise<boolean>;\n /**\n * Requirement(s) to produce when condition is met.\n */\n require: RequirementOutput<R> | ((facts: Facts<S>) => RequirementOutput<R>);\n /** Timeout for async constraints (ms) */\n timeout?: number;\n /**\n * Constraint IDs whose resolvers must complete before this constraint is evaluated.\n * - If dependency's `when()` returns false, this constraint proceeds (nothing to wait for)\n * - If dependency's resolver fails, this constraint remains blocked until it succeeds\n * - Cross-module: use the constraint ID as it appears in the merged system\n */\n after?: 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 S extends Schema,\n R extends Requirement = Requirement,\n> {\n /**\n * Requirement type to handle.\n * - String: matches `req.type` directly (e.g., `requirement: \"FETCH_USER\"`)\n * - Function: type guard predicate (e.g., `requirement: (req) => req.type === \"FETCH_USER\"`)\n */\n requirement: R[\"type\"] | ((req: Requirement) => req is R);\n /** Custom key function for deduplication */\n key?: (req: R) => string;\n /** Retry policy */\n retry?: RetryPolicy;\n /** Timeout for resolver execution (ms) */\n timeout?: number;\n /** Batch configuration */\n batch?: BatchConfig;\n /** Resolve function for single requirement */\n resolve?: (req: R, ctx: ResolverContext<S>) => Promise<void>;\n /** Resolve function for batched requirements */\n resolveBatch?: (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 = createConstraintFactory<typeof schema>();\n *\n * const maxCountConstraint = factory.create({\n * when: (facts) => facts.count > facts.threshold,\n * require: { type: \"RESET\" },\n * });\n * ```\n */\nexport function createConstraintFactory<S extends Schema>() {\n return {\n /**\n * Create a typed constraint\n */\n create<R extends Requirement = Requirement>(\n constraint: TypedConstraint<S, R>,\n ): TypedConstraint<S, R> {\n return constraint;\n },\n };\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 = createResolverFactory<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 createResolverFactory<S extends Schema>() {\n return {\n /**\n * Create a typed resolver\n */\n create<R extends Requirement = Requirement>(\n resolver: TypedResolver<S, R>,\n ): TypedResolver<S, R> {\n return resolver;\n },\n };\n}\n\n// ============================================================================\n// Simple Helper Functions\n// ============================================================================\n\n/**\n * Type-safe constraint creator.\n * Simpler alternative to createConstraintFactory 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 S extends Schema,\n R extends Requirement = Requirement,\n>(constraint: TypedConstraint<S, R>): TypedConstraint<S, R> {\n return constraint;\n}\n\n/**\n * Type-safe resolver creator.\n * Simpler alternative to createResolverFactory 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 S extends Schema,\n R extends Requirement = Requirement,\n>(resolver: TypedResolver<S, R>): TypedResolver<S, R> {\n return 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 { ErrorBoundaryConfig } from \"./errors.js\";\nimport type { Facts } from \"./facts.js\";\nimport type { ModuleDef } from \"./module.js\";\nimport type { Plugin } from \"./plugins.js\";\nimport type {\n InferDerivations,\n InferEvents,\n InferFacts,\n ModuleSchema,\n} from \"./schema.js\";\nimport type {\n ConstraintsControl,\n DerivationsControl,\n DistributableSnapshot,\n DistributableSnapshotOptions,\n EffectsControl,\n HistoryAPI,\n HistoryOption,\n ResolversControl,\n SystemInspection,\n SystemSnapshot,\n TraceEntry,\n TraceOption,\n} from \"./system.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 [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 readonly [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 OwnSchema extends ModuleSchema,\n Deps extends CrossModuleDeps,\n> = { self: InferFacts<OwnSchema> } & {\n [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 readonly [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 [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 readonly [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 [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 /** Modules as object = namespaced access */\n modules: Modules;\n /** Plugins to register */\n plugins?: Array<Plugin<ModuleSchema>>;\n /** History configuration for snapshot-based state history */\n history?: HistoryOption;\n /** Trace: per-run reconciliation changelog */\n trace?: TraceOption;\n /** Error boundary configuration */\n errorBoundary?: ErrorBoundaryConfig;\n /**\n * Tick interval for time-based systems (ms).\n */\n tickMs?: number;\n /**\n * Enable zero-config mode with sensible defaults.\n */\n zeroConfig?: boolean;\n /**\n * Connect to Directive Cloud for remote traces, dashboards, and team collaboration.\n *\n * @see https://directive.run/pricing\n */\n cloud?: boolean | string;\n /**\n * Initial facts to set after module init (namespaced format).\n * Applied after all module `init()` functions but before reconciliation.\n *\n * @example\n * ```typescript\n * createSystem({\n * modules: { auth, data },\n * initialFacts: {\n * auth: { token: \"restored-token\", user: cachedUser },\n * data: { users: preloadedUsers },\n * },\n * });\n * ```\n */\n initialFacts?: Partial<{\n [K in keyof Modules]: Partial<InferFacts<ExtractSchema<Modules[K]>>>;\n }>;\n /**\n * Init order strategy:\n * - \"auto\" (default): Sort by crossModuleDeps topology\n * - \"declaration\": Use object key order (current behavior)\n * - string[]: Explicit order by namespace\n */\n initOrder?: \"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 /** System mode discriminator for type guards */\n readonly _mode: \"namespaced\";\n /** Namespaced facts accessor: system.facts.auth.token */\n readonly facts: MutableNamespacedFacts<Modules>;\n /** History API for undo/redo, rollback, audit trails (if enabled) */\n readonly history: HistoryAPI | null;\n /** Namespaced derivations accessor: system.derive.auth.status */\n readonly derive: NamespacedDerivations<Modules> & DerivationsControl;\n /** Events accessor (union of all module events) */\n readonly events: NamespacedEventsAccessor<Modules>;\n /** Runtime control for constraints (disable/enable/isDisabled + dynamic CRUD) */\n readonly constraints: ConstraintsControl;\n /** Runtime control for effects (disable/enable/isEnabled + dynamic CRUD) */\n readonly effects: EffectsControl;\n /** Runtime control for resolvers (dynamic CRUD) */\n readonly resolvers: ResolversControl;\n /** Per-run trace entries (null if trace is not enabled) */\n readonly trace: TraceEntry[] | null;\n\n /** Initialize facts and derivations without starting reconciliation. Safe for SSR. */\n initialize(): void;\n /** Start the system (initialize modules, begin reconciliation) */\n start(): void;\n /** Stop the system (cancel resolvers, stop reconciliation) */\n stop(): void;\n /** Destroy the system (stop and cleanup) */\n destroy(): void;\n\n /** Whether the system is currently running */\n readonly isRunning: boolean;\n /** Whether all resolvers have completed */\n readonly isSettled: boolean;\n /** Whether all modules have completed initialization */\n readonly isInitialized: boolean;\n /** Whether system has completed first reconciliation */\n readonly isReady: boolean;\n\n /** Wait for system to be fully ready (after first reconciliation) */\n whenReady(): Promise<void>;\n\n /**\n * Hydrate facts from async source (call before start).\n * Useful for restoring state from localStorage, API, etc.\n *\n * @example\n * ```typescript\n * const system = createSystem({ modules: { auth, data } });\n * await system.hydrate(async () => {\n * const stored = localStorage.getItem(\"app-state\");\n * return stored ? JSON.parse(stored) : {};\n * });\n * system.start();\n * ```\n */\n hydrate(\n loader: () =>\n | Promise<\n Partial<{\n [K in keyof Modules]: Partial<\n InferFacts<ExtractSchema<Modules[K]>>\n >;\n }>\n >\n | Partial<{\n [K in keyof Modules]: Partial<InferFacts<ExtractSchema<Modules[K]>>>;\n }>,\n ): Promise<void>;\n\n /** Dispatch an event (union of all module events) */\n dispatch(event: UnionEvents<Modules>): void;\n\n /** Batch multiple fact changes */\n batch(fn: () => void): void;\n\n /**\n * Subscribe to settlement state changes.\n * Called whenever the system's settled state may have changed\n * (resolver starts/completes, reconcile starts/ends).\n */\n onSettledChange(listener: () => void): () => void;\n\n /** Subscribe to history state changes (snapshot taken, navigation). */\n onHistoryChange(listener: () => void): () => void;\n\n /**\n * Read a derivation value by namespaced key.\n * Accepts \"namespace.key\" format (e.g., \"auth.status\").\n *\n * @example\n * system.read(\"auth.status\") // → \"authenticated\"\n * system.read(\"data.count\") // → 5\n */\n read<T = unknown>(derivationId: string): T;\n\n /**\n * Subscribe to fact or derivation changes using namespaced keys.\n * Keys are auto-detected — pass any mix of fact keys and derivation keys.\n * Accepts \"namespace.key\" format (e.g., \"auth.status\", \"auth.token\").\n * Supports wildcard \"namespace.*\" to subscribe to all keys in a module.\n *\n * @example\n * system.subscribe([\"auth.token\", \"data.count\"], () => {\n * console.log(\"Auth or data changed\");\n * });\n *\n * @example Wildcard\n * system.subscribe([\"game.*\"], () => render());\n */\n subscribe(ids: string[], listener: () => void): () => void;\n\n /**\n * Subscribe to ALL fact and derivation changes in a module namespace.\n * Shorthand for subscribing to every key in a module.\n *\n * @example\n * system.subscribeModule(\"game\", () => render());\n * system.subscribeModule(\"chat\", () => render());\n */\n subscribeModule(\n namespace: keyof Modules & string,\n listener: () => void,\n ): () => void;\n\n /**\n * Watch a fact or derivation for changes using namespaced key.\n * The key is auto-detected -- works with both fact keys and derivation keys.\n * Accepts \"namespace.key\" format (e.g., \"auth.status\", \"auth.token\").\n * Pass `options.equalityFn` for custom comparison (e.g., shallow equality for objects).\n *\n * @example\n * system.watch(\"auth.token\", (newVal, oldVal) => {\n * console.log(`Token changed from ${oldVal} to ${newVal}`);\n * });\n */\n watch<T = unknown>(\n id: string,\n callback: (newValue: T, previousValue: T | undefined) => void,\n options?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n ): () => void;\n\n /**\n * Returns a promise that resolves when the predicate becomes true.\n * The predicate is evaluated against current facts and re-evaluated on every change.\n * Uses namespaced facts: `facts.auth.token`, `facts.data.count`, etc.\n * Optionally pass a timeout in ms -- rejects with an error if exceeded.\n *\n * @example\n * await system.when((facts) => facts.auth.token !== null);\n * await system.when((facts) => facts.auth.token !== null, { timeout: 5000 });\n */\n when(\n predicate: (facts: Readonly<MutableNamespacedFacts<Modules>>) => boolean,\n options?: { timeout?: number },\n ): Promise<void>;\n\n /** Inspect system state */\n inspect(): SystemInspection;\n /** Wait for system to settle (all resolvers complete) */\n settle(maxWait?: number): Promise<void>;\n /** Explain why a requirement exists */\n explain(requirementId: string): string | null;\n /** Get serializable snapshot of system state */\n getSnapshot(): SystemSnapshot;\n /** Restore system state from snapshot */\n restore(snapshot: SystemSnapshot): void;\n\n /**\n * Register a new module into a running system.\n * The module is initialized, wired into constraint/resolver/derivation graphs,\n * and reconciliation is triggered.\n *\n * @example\n * ```typescript\n * // Lazy-load a module\n * const chatModule = await import('./modules/chat');\n * system.registerModule(\"chat\", chatModule.default);\n * ```\n */\n registerModule<S extends ModuleSchema>(\n namespace: string,\n moduleDef: ModuleDef<S>,\n ): void;\n\n /**\n * Get a distributable snapshot of computed derivations.\n * Use \"namespace.key\" format for derivation keys.\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({\n * includeDerivations: ['auth.effectivePlan', 'auth.canUseFeature'],\n * ttlSeconds: 3600,\n * });\n * await redis.setex(`entitlements:${userId}`, 3600, JSON.stringify(snapshot));\n * ```\n */\n getDistributableSnapshot<T = Record<string, unknown>>(\n options?: DistributableSnapshotOptions,\n ): DistributableSnapshot<T>;\n\n /**\n * Watch for changes to distributable snapshot derivations.\n * Calls the callback whenever any of the included derivations change.\n * Use \"namespace.key\" format for derivation keys.\n * Returns an unsubscribe function.\n *\n * @example\n * ```typescript\n * const unsubscribe = system.watchDistributableSnapshot(\n * { includeDerivations: ['auth.effectivePlan', 'auth.canUseFeature'] },\n * (snapshot) => {\n * await redis.setex(`entitlements:${userId}`, 3600, JSON.stringify(snapshot));\n * }\n * );\n * ```\n */\n watchDistributableSnapshot<T = Record<string, unknown>>(\n options: DistributableSnapshotOptions,\n callback: (snapshot: DistributableSnapshot<T>) => void,\n ): () => void;\n}\n\n/**\n * Events accessor that groups event dispatchers by module namespace.\n */\nexport type NamespacedEventsAccessor<Modules extends ModulesMap> = {\n readonly [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 ? S extends ModuleSchema\n ? S[\"events\"] extends Record<string, unknown>\n ? {\n [E in keyof S[\"events\"]]: S[\"events\"][E] extends Record<\n string,\n unknown\n >\n ? keyof S[\"events\"][E] extends never\n ? () => void\n : (payload: InferEventPayload<S[\"events\"][E]>) => void\n : () => void;\n }\n : Record<string, never>\n : Record<string, never>\n : Record<string, never>;\n\n/**\n * Infer event payload from event schema.\n */\ntype InferEventPayload<E> = E extends Record<string, unknown>\n ? { [K in keyof E]: E[K] extends { _type: infer T } ? T : E[K] }\n : 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 facts: MergeFactsWithPrefix<Modules>;\n derivations: MergeDerivationsWithPrefix<Modules>;\n events: MergeEventsWithPrefix<Modules>;\n requirements: MergeRequirementsWithPrefix<Modules>;\n};\n\ntype MergeFactsWithPrefix<Modules extends ModulesMap> = {\n [K in keyof Modules as `${K & string}::${keyof ExtractSchema<Modules[K]>[\"facts\"] & string}`]: ExtractSchema<\n Modules[K]\n >[\"facts\"][keyof ExtractSchema<Modules[K]>[\"facts\"]];\n};\n\ntype MergeDerivationsWithPrefix<Modules extends ModulesMap> = {\n [K in keyof Modules as ExtractSchema<\n Modules[K]\n >[\"derivations\"] extends Record<string, unknown>\n ? `${K & string}::${keyof ExtractSchema<Modules[K]>[\"derivations\"] & string}`\n : never]: ExtractSchema<Modules[K]>[\"derivations\"] extends Record<\n string,\n unknown\n >\n ? ExtractSchema<Modules[K]>[\"derivations\"][keyof ExtractSchema<\n Modules[K]\n >[\"derivations\"]]\n : never;\n};\n\ntype MergeEventsWithPrefix<Modules extends ModulesMap> = {\n [K in keyof Modules as ExtractSchema<Modules[K]>[\"events\"] extends Record<\n string,\n unknown\n >\n ? `${K & string}::${keyof ExtractSchema<Modules[K]>[\"events\"] & string}`\n : never]: ExtractSchema<Modules[K]>[\"events\"] extends Record<\n string,\n unknown\n >\n ? ExtractSchema<Modules[K]>[\"events\"][keyof ExtractSchema<\n Modules[K]\n >[\"events\"]]\n : never;\n};\n\ntype MergeRequirementsWithPrefix<Modules extends ModulesMap> = {\n [K in keyof Modules as ExtractSchema<\n Modules[K]\n >[\"requirements\"] extends Record<string, unknown>\n ? keyof ExtractSchema<Modules[K]>[\"requirements\"] & string\n : never]: ExtractSchema<Modules[K]>[\"requirements\"] extends Record<\n string,\n unknown\n >\n ? ExtractSchema<Modules[K]>[\"requirements\"][keyof ExtractSchema<\n Modules[K]\n >[\"requirements\"]]\n : 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 /** Single module = direct access (use `modules` for multiple) */\n module: ModuleDef<S>;\n /** Plugins to register */\n plugins?: Array<Plugin<ModuleSchema>>;\n /** History configuration for snapshot-based state history */\n history?: HistoryOption;\n /** Trace: per-run reconciliation changelog */\n trace?: TraceOption;\n /** Error boundary configuration */\n errorBoundary?: ErrorBoundaryConfig;\n /** Tick interval for time-based systems (ms) */\n tickMs?: number;\n /** Enable zero-config mode with sensible defaults */\n zeroConfig?: boolean;\n /**\n * Connect to Directive Cloud for remote traces, dashboards, and team collaboration.\n *\n * @see https://directive.run/pricing\n */\n cloud?: boolean | string;\n /**\n * Initial facts to set after module init.\n * Applied after module `init()` but before reconciliation.\n */\n initialFacts?: 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 /** System mode discriminator for type guards */\n readonly _mode: \"single\";\n /** Direct facts accessor: system.facts.count */\n readonly facts: Facts<S[\"facts\"]>;\n /** History API for undo/redo, rollback, audit trails (if enabled) */\n readonly history: HistoryAPI | null;\n /** Direct derivations accessor: system.derive.doubled */\n readonly derive: InferDerivations<S> & DerivationsControl<S>;\n /** Direct events accessor: system.events.increment() */\n readonly events: SingleModuleEvents<S>;\n /** Runtime control for constraints (disable/enable/isDisabled) */\n readonly constraints: ConstraintsControl<S>;\n /** Runtime control for effects (disable/enable/isEnabled) */\n readonly effects: EffectsControl<S>;\n /** Runtime control for resolvers (register/assign/unregister/call) */\n readonly resolvers: ResolversControl<S>;\n /** Per-run trace entries (null if trace is not enabled) */\n readonly trace: TraceEntry[] | null;\n\n /** Initialize facts and derivations without starting reconciliation. Safe for SSR. */\n initialize(): void;\n /** Start the system (initialize modules, begin reconciliation) */\n start(): void;\n /** Stop the system (cancel resolvers, stop reconciliation) */\n stop(): void;\n /** Destroy the system (stop and cleanup) */\n destroy(): void;\n\n /** Whether the system is currently running */\n readonly isRunning: boolean;\n /** Whether all resolvers have completed */\n readonly isSettled: boolean;\n /** Whether module has completed initialization */\n readonly isInitialized: boolean;\n /** Whether system has completed first reconciliation */\n readonly isReady: boolean;\n\n /** Wait for system to be fully ready (after first reconciliation) */\n whenReady(): Promise<void>;\n\n /**\n * Hydrate facts from async source (call before start).\n */\n hydrate(\n loader: () => Promise<Partial<InferFacts<S>>> | Partial<InferFacts<S>>,\n ): Promise<void>;\n\n /** Dispatch an event */\n dispatch(event: InferEvents<S>): void;\n\n /** Batch multiple fact changes */\n batch(fn: () => void): void;\n\n /**\n * Subscribe to settlement state changes.\n * Called whenever the system's settled state may have changed\n * (resolver starts/completes, reconcile starts/ends).\n */\n onSettledChange(listener: () => void): () => void;\n\n /** Subscribe to history state changes (snapshot taken, navigation). */\n onHistoryChange(listener: () => void): () => void;\n\n /**\n * Read a derivation value by key.\n * @example system.read(\"doubled\")\n */\n read<T = unknown>(derivationId: string): T;\n\n /**\n * Subscribe to fact or derivation changes.\n * Keys are auto-detected -- pass any mix of fact keys and derivation keys.\n * @example system.subscribe([\"count\", \"doubled\"], () => { ... })\n */\n subscribe(ids: string[], listener: () => void): () => void;\n\n /**\n * Watch a fact or derivation for value changes.\n * The key is auto-detected -- works with both fact keys and derivation keys.\n * Pass `options.equalityFn` for custom comparison (e.g., shallow equality for objects).\n * @example system.watch(\"count\", (newVal, oldVal) => { ... })\n * @example system.watch(\"derived\", cb, { equalityFn: shallowEqual })\n */\n watch<T = unknown>(\n id: string,\n callback: (newValue: T, previousValue: T | undefined) => void,\n options?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n ): () => void;\n\n /**\n * Returns a promise that resolves when the predicate becomes true.\n * The predicate is evaluated against current facts and re-evaluated on every change.\n * Optionally pass a timeout in ms -- rejects with an error if exceeded.\n *\n * @example\n * await system.when((facts) => facts.count > 10);\n * await system.when((facts) => facts.count > 10, { timeout: 5000 });\n */\n when(\n predicate: (facts: Readonly<InferFacts<S>>) => boolean,\n options?: { timeout?: number },\n ): Promise<void>;\n\n /** Inspect system state */\n inspect(): SystemInspection;\n /** Wait for system to settle (all resolvers complete) */\n settle(maxWait?: number): Promise<void>;\n /** Explain why a requirement exists */\n explain(requirementId: string): string | null;\n /** Get serializable snapshot of system state */\n getSnapshot(): SystemSnapshot;\n /** Restore system state from snapshot */\n restore(snapshot: SystemSnapshot): void;\n\n /**\n * Register a new module into a running system.\n * Module facts, derivations, effects, constraints, and resolvers are merged\n * into the existing engine and reconciliation is triggered.\n *\n * @example\n * ```typescript\n * const analyticsModule = await import('./modules/analytics');\n * system.registerModule(analyticsModule.default);\n * ```\n */\n registerModule<S2 extends ModuleSchema>(moduleDef: ModuleDef<S2>): void;\n\n /**\n * Get a distributable snapshot of computed derivations.\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({\n * includeDerivations: ['effectivePlan', 'canUseFeature'],\n * ttlSeconds: 3600,\n * });\n * await redis.setex(`entitlements:${userId}`, 3600, JSON.stringify(snapshot));\n * ```\n */\n getDistributableSnapshot<T = Record<string, unknown>>(\n options?: DistributableSnapshotOptions,\n ): DistributableSnapshot<T>;\n\n /**\n * Watch for changes to distributable snapshot derivations.\n * Calls the callback whenever any of the included derivations change.\n * Returns an unsubscribe function.\n *\n * @example\n * ```typescript\n * const unsubscribe = system.watchDistributableSnapshot(\n * { includeDerivations: ['effectivePlan', 'canUseFeature'] },\n * (snapshot) => {\n * await redis.setex(`entitlements:${userId}`, 3600, JSON.stringify(snapshot));\n * }\n * );\n * ```\n */\n watchDistributableSnapshot<T = Record<string, unknown>>(\n options: DistributableSnapshotOptions,\n callback: (snapshot: DistributableSnapshot<T>) => void,\n ): () => void;\n}\n\n/**\n * Events dispatcher for a single module (direct access).\n */\ntype SingleModuleEvents<S extends ModuleSchema> = S[\"events\"] extends Record<\n string,\n unknown\n>\n ? {\n [E in keyof S[\"events\"]]: S[\"events\"][E] extends Record<string, unknown>\n ? keyof S[\"events\"][E] extends never\n ? () => void\n : (payload: InferEventPayload<S[\"events\"][E]>) => void\n : () => void;\n }\n : 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 readonly _mode: SystemMode;\n readonly isRunning: boolean;\n readonly isSettled: boolean;\n readonly isInitialized: boolean;\n readonly isReady: boolean;\n initialize(): void;\n start(): void;\n stop(): void;\n destroy(): 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 return 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 return system._mode === \"namespaced\";\n}\n","/**\n * History — 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 {\n Facts,\n FactsStore,\n HistoryAPI,\n HistoryOption,\n Schema,\n Snapshot,\n} from \"../core/types.js\";\nimport { isPrototypeSafe } from \"./utils.js\";\n\n// ============================================================================\n// History Manager\n// ============================================================================\n\n/**\n * A changeset groups multiple snapshots into a single undo/redo unit.\n *\n * @remarks\n * Use {@link HistoryManager.beginChangeset} and\n * {@link HistoryManager.endChangeset} to create changesets. When navigating\n * with `goBack`/`goForward`, the entire changeset is traversed as one step.\n *\n * @internal\n */\nexport interface Changeset {\n label: string;\n startIndex: number;\n endIndex: number;\n}\n\n/**\n * Internal history manager that extends the public {@link HistoryAPI}\n * with snapshot capture, restoration, and pause/resume controls.\n *\n * @remarks\n * - `takeSnapshot(trigger)` records the current facts into the ring buffer.\n * - `restore(snapshot)` deserializes a snapshot back into the facts store,\n * setting `isRestoring = true` so the engine skips reconciliation.\n * - `pause()` / `resume()` temporarily suspend snapshot recording (e.g.,\n * during bulk imports or programmatic state resets).\n * - `beginChangeset(label)` / `endChangeset()` group consecutive snapshots\n * so `goBack`/`goForward` treat them as a single undo/redo unit.\n *\n * @typeParam _S - The schema type (unused at runtime but preserved for type safety).\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface HistoryManager<_S extends Schema> extends HistoryAPI {\n /** Take a snapshot of current state */\n takeSnapshot(trigger: string): Snapshot;\n /** Restore facts from a snapshot */\n restore(snapshot: Snapshot): void;\n /** Check if history is enabled */\n readonly isEnabled: boolean;\n /** True while restoring a snapshot (engine should skip reconciliation) */\n readonly isRestoring: boolean;\n /** Pause snapshot taking */\n pause(): void;\n /** Resume snapshot taking */\n resume(): void;\n}\n\n/**\n * Options for creating a history manager via {@link createHistoryManager}.\n *\n * @typeParam S - The facts schema type.\n *\n * @internal\n */\nexport interface CreateHistoryOptions<S extends Schema> {\n historyOption: HistoryOption;\n facts: Facts<S>;\n store: FactsStore<S>;\n /** Callback when a snapshot is taken */\n onSnapshot?: (snapshot: Snapshot) => void;\n /** Callback when history navigation occurs */\n onHistoryChange?: (from: number, to: number) => void;\n}\n\n/**\n * Resolve a HistoryOption (boolean | HistoryConfig) into concrete values.\n * @internal\n */\nfunction resolveHistoryOption(option: HistoryOption): {\n enabled: boolean;\n maxSnapshots: number;\n} {\n if (typeof option === \"boolean\") {\n return { enabled: option, maxSnapshots: 100 };\n }\n\n // Object config — presence implies enabled\n return {\n enabled: true,\n maxSnapshots: option.maxSnapshots ?? 100,\n };\n}\n\n/**\n * Create a snapshot-based history manager backed by a ring buffer.\n *\n * @remarks\n * Snapshots are taken automatically after fact changes (during reconciliation)\n * and can be navigated with `goBack`/`goForward`/`goTo`. Use\n * `beginChangeset(label)` and `endChangeset()` to group multiple snapshots\n * into a single undo/redo unit. The entire history can be exported to JSON\n * via `export()` and re-imported with `import()` for cross-session debugging.\n *\n * Call `pause()` to temporarily stop recording snapshots (e.g., during bulk\n * fact imports) and `resume()` to re-enable recording.\n *\n * @param options - History config, facts proxy, store, and optional snapshot/history callbacks.\n * @returns A {@link HistoryManager} with snapshot capture, navigation, changeset, and export/import methods.\n *\n * @internal\n */\nexport function createHistoryManager<S extends Schema>(\n options: CreateHistoryOptions<S>,\n): HistoryManager<S> {\n const { historyOption, facts, store, onSnapshot, onHistoryChange } = options;\n\n const { enabled: isEnabled, maxSnapshots } =\n resolveHistoryOption(historyOption);\n\n // Ring buffer of snapshots\n const snapshots: Snapshot[] = [];\n let currentIndex = -1;\n let nextId = 1;\n let paused = false;\n let restoring = false;\n\n // Changeset tracking\n const changesets: Changeset[] = [];\n let pendingChangesetLabel: string | null = null;\n let pendingChangesetStart = -1;\n\n /** Get current facts as a plain object */\n function getCurrentFacts(): Record<string, unknown> {\n return store.toObject();\n }\n\n /** Serialize facts to a snapshot-friendly format */\n function serializeFacts(): Record<string, unknown> {\n const factsObj = getCurrentFacts();\n\n // Deep clone to prevent mutation\n try {\n return structuredClone(factsObj);\n } catch {\n // Fallback for non-cloneable values (functions, DOM nodes, etc.)\n try {\n return JSON.parse(JSON.stringify(factsObj));\n } catch {\n return { ...factsObj };\n }\n }\n }\n\n /** Deserialize and restore facts from a snapshot */\n function deserializeFacts(serialized: Record<string, unknown>): void {\n // Validate entire object tree for prototype pollution\n if (!isPrototypeSafe(serialized)) {\n console.error(\n \"[Directive] Potential prototype pollution detected in snapshot data, skipping restore\",\n );\n return;\n }\n\n store.batch(() => {\n for (const [key, value] of Object.entries(serialized)) {\n // Prototype pollution protection (redundant but defensive)\n if (\n key === \"__proto__\" ||\n key === \"constructor\" ||\n key === \"prototype\"\n ) {\n console.warn(\n `[Directive] Skipping dangerous key \"${key}\" during fact restoration`,\n );\n continue;\n }\n // @ts-expect-error - dynamic key access\n facts[key] = value;\n }\n });\n }\n\n const manager: HistoryManager<S> = {\n get isEnabled() {\n return isEnabled;\n },\n\n get isRestoring() {\n return restoring;\n },\n\n get isPaused() {\n return paused;\n },\n\n get snapshots() {\n return [...snapshots];\n },\n\n get currentIndex() {\n return currentIndex;\n },\n\n takeSnapshot(trigger: string): Snapshot {\n if (!isEnabled || paused) {\n return { id: -1, timestamp: Date.now(), facts: {}, trigger };\n }\n\n const snapshot: Snapshot = {\n id: nextId++,\n timestamp: Date.now(),\n facts: serializeFacts(),\n trigger,\n };\n\n // If we're not at the end, truncate future snapshots\n if (currentIndex < snapshots.length - 1) {\n snapshots.splice(currentIndex + 1);\n }\n\n // Add new snapshot\n snapshots.push(snapshot);\n currentIndex = snapshots.length - 1;\n\n // Enforce max size (ring buffer)\n while (snapshots.length > maxSnapshots) {\n snapshots.shift();\n currentIndex--;\n }\n\n onSnapshot?.(snapshot);\n return snapshot;\n },\n\n restore(snapshot: Snapshot): void {\n if (!isEnabled) return;\n\n // Set restoring flag so the engine skips reconciliation scheduling.\n // The restored state is already \"reconciled\" — it was captured after\n // a complete reconcile cycle. Re-reconciling would create spurious\n // snapshots that break undo/redo navigation.\n paused = true;\n restoring = true;\n\n try {\n deserializeFacts(snapshot.facts);\n } finally {\n paused = false;\n restoring = false;\n }\n },\n\n goBack(steps = 1): void {\n if (!isEnabled || snapshots.length === 0) return;\n\n const fromIndex = currentIndex;\n\n // Check if we're inside a changeset — jump to its start\n let toIndex = currentIndex;\n const cs = changesets.find(\n (c) => currentIndex > c.startIndex && currentIndex <= c.endIndex,\n );\n if (cs) {\n toIndex = cs.startIndex;\n } else {\n // Check if we're at the end of a changeset — jump past its start\n const prevCs = changesets.find((c) => currentIndex === c.startIndex);\n if (prevCs) {\n // We're at the boundary. Look for the changeset before this one.\n const earlierCs = changesets.find(\n (c) =>\n c.endIndex < currentIndex && currentIndex - c.endIndex <= steps,\n );\n toIndex = earlierCs\n ? earlierCs.startIndex\n : Math.max(0, currentIndex - steps);\n } else {\n toIndex = Math.max(0, currentIndex - steps);\n }\n }\n\n if (fromIndex === toIndex) return;\n\n currentIndex = toIndex;\n const snapshot = snapshots[currentIndex];\n if (snapshot) {\n this.restore(snapshot);\n onHistoryChange?.(fromIndex, toIndex);\n }\n },\n\n goForward(steps = 1): void {\n if (!isEnabled || snapshots.length === 0) return;\n\n const fromIndex = currentIndex;\n\n // Check if we're inside or at the start of a changeset — jump to its end\n let toIndex = currentIndex;\n const cs = changesets.find(\n (c) => currentIndex >= c.startIndex && currentIndex < c.endIndex,\n );\n if (cs) {\n toIndex = cs.endIndex;\n } else {\n toIndex = Math.min(snapshots.length - 1, currentIndex + steps);\n }\n\n if (fromIndex === toIndex) return;\n\n currentIndex = toIndex;\n const snapshot = snapshots[currentIndex];\n if (snapshot) {\n this.restore(snapshot);\n onHistoryChange?.(fromIndex, toIndex);\n }\n },\n\n goTo(snapshotId: number): void {\n if (!isEnabled) return;\n\n const index = snapshots.findIndex((s) => s.id === snapshotId);\n if (index === -1) {\n console.warn(`[Directive] Snapshot ${snapshotId} not found`);\n return;\n }\n\n const fromIndex = currentIndex;\n currentIndex = index;\n const snapshot = snapshots[currentIndex];\n if (snapshot) {\n this.restore(snapshot);\n onHistoryChange?.(fromIndex, index);\n }\n },\n\n replay(): void {\n if (!isEnabled || snapshots.length === 0) return;\n\n // Start from the beginning\n currentIndex = 0;\n const snapshot = snapshots[0];\n if (snapshot) {\n this.restore(snapshot);\n }\n },\n\n export(): string {\n return JSON.stringify({\n version: 1,\n snapshots,\n currentIndex,\n });\n },\n\n import(json: string): void {\n if (!isEnabled) return;\n\n try {\n const data = JSON.parse(json);\n\n // Validate import data structure to prevent prototype pollution\n if (typeof data !== \"object\" || data === null) {\n throw new Error(\"[Directive] Invalid history data: expected object\");\n }\n if (data.version !== 1) {\n throw new Error(\n `[Directive] Unsupported history export version: ${data.version}`,\n );\n }\n if (!Array.isArray(data.snapshots)) {\n throw new Error(\"[Directive] Invalid history data: snapshots must be an array\");\n }\n if (typeof data.currentIndex !== \"number\") {\n throw new Error(\n \"Invalid history data: currentIndex must be a number\",\n );\n }\n\n // Validate each snapshot has required properties\n for (const snap of data.snapshots) {\n if (typeof snap !== \"object\" || snap === null) {\n throw new Error(\"[Directive] Invalid snapshot: expected object\");\n }\n if (\n typeof snap.id !== \"number\" ||\n typeof snap.timestamp !== \"number\" ||\n typeof snap.trigger !== \"string\" ||\n typeof snap.facts !== \"object\"\n ) {\n throw new Error(\"Invalid snapshot structure\");\n }\n // Deep check for prototype pollution attacks (including nested objects)\n if (!isPrototypeSafe(snap.facts)) {\n throw new Error(\n \"[Directive] Invalid fact data: potential prototype pollution detected in nested objects\",\n );\n }\n }\n\n snapshots.length = 0;\n snapshots.push(...data.snapshots);\n currentIndex = data.currentIndex;\n\n // Restore current state\n const snapshot = snapshots[currentIndex];\n if (snapshot) {\n this.restore(snapshot);\n }\n } catch (error) {\n console.error(\"[Directive] Failed to import history data:\", error);\n }\n },\n\n beginChangeset(label: string): void {\n if (!isEnabled) return;\n pendingChangesetLabel = label;\n pendingChangesetStart = currentIndex;\n },\n\n endChangeset(): void {\n if (!isEnabled || pendingChangesetLabel === null) return;\n if (currentIndex > pendingChangesetStart) {\n changesets.push({\n label: pendingChangesetLabel,\n startIndex: pendingChangesetStart,\n endIndex: currentIndex,\n });\n }\n pendingChangesetLabel = null;\n pendingChangesetStart = -1;\n },\n\n pause(): void {\n paused = true;\n },\n\n resume(): void {\n paused = false;\n },\n };\n\n return manager;\n}\n\n/**\n * Create a no-op history manager for use when history is disabled.\n *\n * @remarks\n * All methods are safe to call but perform no work. This avoids null-checks\n * throughout the engine -- callers can use the same {@link HistoryManager}\n * interface regardless of whether history is enabled.\n *\n * @returns A {@link HistoryManager} where every method is a no-op and `isEnabled` is `false`.\n *\n * @internal\n */\nexport function createDisabledHistory<S extends Schema>(): HistoryManager<S> {\n const noopSnapshot: Snapshot = {\n id: -1,\n timestamp: 0,\n facts: {},\n trigger: \"\",\n };\n\n return {\n isEnabled: false,\n isRestoring: false,\n isPaused: false,\n snapshots: [],\n currentIndex: -1,\n takeSnapshot: () => noopSnapshot,\n restore: () => {},\n goBack: () => {},\n goForward: () => {},\n goTo: () => {},\n replay: () => {},\n export: () => \"{}\",\n import: () => {},\n beginChangeset: () => {},\n endChangeset: () => {},\n pause: () => {},\n resume: () => {},\n };\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 { stableStringify } from \"../utils/utils.js\";\nimport type {\n Requirement,\n RequirementKeyFn,\n RequirementWithId,\n} from \"./types.js\";\n\n// ============================================================================\n// Requirement Identity\n// ============================================================================\n\n/**\n * Generate a stable identity string for a requirement.\n *\n * When no custom key function is provided, the ID is formed from the\n * requirement's `type` plus a deterministic JSON serialization of its\n * remaining properties. A custom {@link RequirementKeyFn} can override\n * this to control deduplication granularity.\n *\n * @param req - The requirement to generate an ID for.\n * @param keyFn - Optional custom key function that overrides the default identity logic.\n * @returns A stable string that uniquely identifies this requirement for deduplication.\n *\n * @public\n */\n/** Cache for default requirement IDs (no custom keyFn) to avoid repeated stableStringify */\nconst reqIdCache = new WeakMap<Requirement, string>();\n\nexport function generateRequirementId(\n req: Requirement,\n keyFn?: RequirementKeyFn,\n): string {\n // Use custom key function if provided\n if (keyFn) {\n return keyFn(req);\n }\n\n // Check cache first\n const cached = reqIdCache.get(req);\n if (cached !== undefined) {\n return cached;\n }\n\n // Default: type + stable JSON of other properties\n const { type, ...rest } = req;\n const sortedRest = stableStringify(rest);\n const id = `${type}:${sortedRest}`;\n\n reqIdCache.set(req, id);\n\n return id;\n}\n\n/**\n * Create a {@link RequirementWithId} by pairing a requirement with its\n * computed identity string and the constraint that produced it.\n *\n * @param requirement - The raw requirement object.\n * @param fromConstraint - Name of the constraint that emitted this requirement.\n * @param keyFn - Optional custom key function forwarded to {@link generateRequirementId}.\n * @returns A requirement bundled with its stable ID and originating constraint name.\n *\n * @public\n */\nexport function createRequirementWithId(\n requirement: Requirement,\n fromConstraint: string,\n keyFn?: RequirementKeyFn,\n): RequirementWithId {\n return {\n requirement,\n id: generateRequirementId(requirement, keyFn),\n fromConstraint,\n };\n}\n\n// ============================================================================\n// Requirement Helpers\n// ============================================================================\n\n/**\n * Create a typed requirement factory for a given requirement type string.\n *\n * Returns a function that, when called with a properties object, produces a\n * fully-typed {@link Requirement} whose `type` field is the literal `T`.\n * This is the recommended way to build requirements inside constraint\n * definitions because it keeps the type string in one place and gives you\n * full TypeScript inference on the payload.\n *\n * @param type - The requirement type string (e.g. `\"FETCH_USER\"`).\n * @returns A factory that merges `type` with arbitrary properties into a typed requirement.\n *\n * @example\n * ```typescript\n * const fetchUser = req(\"FETCH_USER\");\n *\n * // Use inside a module's constraint definition\n * constraints: {\n * needsUser: {\n * when: (facts) => facts.userId && !facts.user,\n * require: fetchUser({ userId: 123, priority: \"high\" }),\n * },\n * }\n *\n * // Produces: { type: \"FETCH_USER\", userId: 123, priority: \"high\" }\n * ```\n *\n * @public\n */\nexport function req<T extends string>(type: T) {\n return <P extends Record<string, unknown>>(props: P) =>\n ({\n type,\n ...props,\n }) as Requirement & { type: T } & P;\n}\n\n/**\n * Type-narrowing guard that checks whether a requirement's `type` matches the\n * given string literal.\n *\n * After this guard returns `true`, TypeScript narrows `req` to\n * `Requirement & { type: T }`, giving you access to type-specific fields.\n *\n * @param req - The requirement to test.\n * @param type - The expected type string to match against.\n * @returns `true` when `req.type === type`.\n *\n * @public\n */\nexport function isRequirementType<T extends string>(\n req: Requirement,\n type: T,\n): req is Requirement & { type: T } {\n return req.type === type;\n}\n\n/**\n * Create a type-guard function suitable for a resolver's `requirement`\n * predicate field.\n *\n * @remarks\n * The returned predicate narrows any {@link Requirement} to the concrete\n * type `R` (or `Requirement & { type: T }` when no explicit generic is\n * provided). This is a cleaner alternative to writing verbose inline type\n * guards in every resolver definition.\n *\n * @param type - The requirement type string to match.\n * @returns A predicate that returns `true` for requirements whose `type` matches, narrowing the value for downstream callbacks like `key` and `resolve`.\n *\n * @example\n * ```typescript\n * // With an explicit requirement interface (recommended for complex payloads)\n * interface FetchUserReq { type: \"FETCH_USER\"; userId: string }\n * requirement: forType<FetchUserReq>(\"FETCH_USER\"),\n * key: (req) => req.userId, // req is FetchUserReq\n *\n * // With a simple string literal\n * requirement: forType(\"FETCH_USER\"),\n * key: (req) => req.type, // req is Requirement & { type: \"FETCH_USER\" }\n * ```\n *\n * @public\n */\nexport function forType<R extends Requirement>(\n type: R[\"type\"],\n): (req: Requirement) => req is R;\nexport function forType<T extends string>(\n type: T,\n): (req: Requirement) => req is Requirement & { type: T };\n/** @internal Implementation overload — see public overloads above. */\nexport function forType<T extends string>(\n type: T,\n): (req: Requirement) => req is Requirement & { type: T } {\n return (req): req is Requirement & { type: T } => req.type === type;\n}\n\n// ============================================================================\n// Requirement Set Management\n// ============================================================================\n\n/**\n * A deduplicated collection of {@link RequirementWithId} entries keyed by\n * their identity string.\n *\n * @remarks\n * Requirements are uniquely identified by their ID (generated from type +\n * properties via {@link generateRequirementId}). When adding a requirement\n * whose ID already exists, the first entry wins and the duplicate is\n * silently ignored. The {@link RequirementSet.diff | diff} method computes\n * added, removed, and unchanged entries relative to another set, which the\n * engine uses during reconciliation.\n *\n * @example\n * ```typescript\n * const set = new RequirementSet();\n * set.add(createRequirementWithId({ type: \"FETCH_USER\", userId: 1 }, \"c1\"));\n * set.add(createRequirementWithId({ type: \"FETCH_USER\", userId: 1 }, \"c2\")); // ignored\n * console.log(set.size); // 1\n *\n * const next = new RequirementSet();\n * next.add(createRequirementWithId({ type: \"FETCH_USER\", userId: 2 }, \"c1\"));\n * const { added, removed } = next.diff(set);\n * // added has userId: 2, removed has userId: 1\n * ```\n *\n * @public\n */\nexport class RequirementSet {\n private map = new Map<string, RequirementWithId>();\n\n /**\n * Add a requirement to the set (first-wins deduplication).\n *\n * @param req - The requirement with its computed ID to insert.\n */\n add(req: RequirementWithId): void {\n // If already exists, keep the existing one (first wins)\n if (!this.map.has(req.id)) {\n this.map.set(req.id, req);\n }\n }\n\n /**\n * Remove a requirement by its identity string.\n *\n * @param id - The requirement identity string to remove.\n * @returns `true` if the requirement existed and was removed.\n */\n remove(id: string): boolean {\n return this.map.delete(id);\n }\n\n /**\n * Check whether a requirement with the given ID is in the set.\n *\n * @param id - The requirement identity string to look up.\n * @returns `true` if the set contains a requirement with this ID.\n */\n has(id: string): boolean {\n return this.map.has(id);\n }\n\n /**\n * Retrieve a requirement by its identity string.\n *\n * @param id - The requirement identity string to look up.\n * @returns The matching requirement, or `undefined` if not found.\n */\n get(id: string): RequirementWithId | undefined {\n return this.map.get(id);\n }\n\n /**\n * Return a snapshot array of all requirements in the set.\n *\n * @returns A new array containing every {@link RequirementWithId} in insertion order.\n */\n all(): RequirementWithId[] {\n return [...this.map.values()];\n }\n\n /**\n * Return a snapshot array of all requirement identity strings.\n *\n * @returns A new array of ID strings in insertion order.\n */\n ids(): string[] {\n return [...this.map.keys()];\n }\n\n /**\n * The number of requirements currently in the set.\n */\n get size(): number {\n return this.map.size;\n }\n\n /**\n * Remove all requirements from the set.\n */\n clear(): void {\n this.map.clear();\n }\n\n /**\n * Create a shallow copy of this set.\n *\n * @returns A new {@link RequirementSet} containing the same entries.\n */\n clone(): RequirementSet {\n const copy = new RequirementSet();\n for (const req of this.map.values()) {\n copy.add(req);\n }\n return copy;\n }\n\n /**\n * Compute the difference between this set and another.\n *\n * @param other - The previous set to compare against.\n * @returns An object with `added` (in this but not other), `removed` (in other but not this), and `unchanged` arrays.\n */\n diff(other: RequirementSet): {\n added: RequirementWithId[];\n removed: RequirementWithId[];\n unchanged: RequirementWithId[];\n } {\n const added: RequirementWithId[] = [];\n const removed: RequirementWithId[] = [];\n const unchanged: RequirementWithId[] = [];\n\n // Find added (in this but not in other)\n for (const req of this.map.values()) {\n if (!other.has(req.id)) {\n added.push(req);\n } else {\n unchanged.push(req);\n }\n }\n\n // Find removed (in other but not in this)\n for (const req of other.map.values()) {\n if (!this.map.has(req.id)) {\n removed.push(req);\n }\n }\n\n return { added, removed, unchanged };\n }\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 { withTimeout } from \"../utils/utils.js\";\nimport { RequirementSet, createRequirementWithId } from \"./requirements.js\";\nimport { withTracking } from \"./tracking.js\";\nimport type {\n ConstraintState,\n ConstraintsDef,\n Facts,\n Requirement,\n RequirementKeyFn,\n RequirementWithId,\n Schema,\n} from \"./types.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/**\n * Manager returned by {@link createConstraintsManager} that evaluates\n * constraint rules against the current facts and produces unmet\n * {@link RequirementWithId | requirements}.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ConstraintsManager<_S extends Schema> {\n /**\n * Evaluate all enabled constraints and return unmet requirements.\n *\n * @remarks\n * On the first call (or when `changedKeys` is empty), every enabled\n * constraint is evaluated. On subsequent calls, only constraints whose\n * tracked dependencies overlap with `changedKeys` are re-evaluated.\n * Sync constraints run first, async constraints run in parallel, and\n * `after` ordering is respected across multiple passes.\n *\n * @param changedKeys - Fact keys that changed since the last evaluation.\n * When omitted or empty, all constraints are evaluated.\n * @returns An array of {@link RequirementWithId} representing unmet requirements.\n */\n evaluate(changedKeys?: Set<string>): Promise<RequirementWithId[]>;\n /**\n * Get the current state of a constraint by its definition ID.\n *\n * @param id - The constraint definition ID.\n * @returns The {@link ConstraintState}, or `undefined` if the ID is unknown.\n */\n getState(id: string): ConstraintState | undefined;\n /**\n * Get the state of every registered constraint.\n *\n * @returns An array of all {@link ConstraintState} objects.\n */\n getAllStates(): ConstraintState[];\n /**\n * Disable a constraint so it is skipped during evaluation.\n *\n * @param id - The constraint definition ID.\n */\n disable(id: string): void;\n /**\n * Re-enable a previously disabled constraint.\n *\n * @param id - The constraint definition ID.\n */\n enable(id: string): void;\n /**\n * Mark all constraints that depend on `factKey` as dirty so they are\n * re-evaluated on the next {@link ConstraintsManager.evaluate | evaluate} call.\n *\n * @param factKey - The fact store key that changed.\n */\n invalidate(factKey: string): void;\n /**\n * Get the auto-tracked or explicit dependency set for a constraint.\n *\n * @param id - The constraint definition ID.\n * @returns A `Set` of fact keys, or `undefined` if no dependencies have been recorded.\n */\n getDependencies(id: string): Set<string> | undefined;\n /**\n * Record that a constraint's resolver completed successfully, unblocking\n * any constraints that list it in their `after` array.\n *\n * @param constraintId - The constraint definition ID whose resolver finished.\n */\n markResolved(constraintId: string): void;\n /**\n * Check whether a constraint is currently disabled.\n *\n * @param id - The constraint definition ID.\n * @returns `true` if the constraint has been disabled via {@link ConstraintsManager.disable | disable}.\n */\n isDisabled(id: string): boolean;\n /**\n * Check whether a constraint has been marked as resolved.\n *\n * @param constraintId - The constraint definition ID.\n * @returns `true` if {@link ConstraintsManager.markResolved | markResolved} was called for this constraint.\n */\n isResolved(constraintId: string): boolean;\n /**\n * Register additional constraint definitions at runtime (used for dynamic\n * module registration).\n *\n * @remarks\n * Rebuilds the topological order and reverse dependency map so new `after`\n * dependencies are validated for cycles and indexed.\n *\n * @param newDefs - New constraint definitions to merge into the manager.\n */\n registerDefinitions(newDefs: ConstraintsDef<Schema>): void;\n /**\n * Override an existing constraint definition.\n * Stores the original in an internal map for inspection.\n *\n * @param id - The constraint definition ID to override.\n * @param def - The new constraint definition.\n * @throws If no constraint with this ID exists.\n */\n assignDefinition(id: string, def: ConstraintsDef<Schema>[string]): void;\n /**\n * Remove a constraint definition and all its internal state.\n *\n * @param id - The constraint definition ID to remove.\n */\n unregisterDefinition(id: string): void;\n /**\n * Evaluate a single constraint and emit its requirement if active.\n * Props are merged into the requirement object.\n *\n * @param id - The constraint definition ID.\n * @param props - Optional properties to merge into the requirement.\n * @returns The emitted requirements (if any).\n */\n callOne(\n id: string,\n props?: Record<string, unknown>,\n ): Promise<RequirementWithId[]>;\n /**\n * Register a custom key function for a requirement type.\n * Used by the engine to forward resolver `key` functions to the\n * constraint manager for requirement deduplication.\n *\n * @param requirementType - The requirement type string (e.g. `\"FETCH_USER\"`).\n * @param keyFn - The key function that produces a deduplication string.\n */\n setRequirementKey(requirementType: string, keyFn: RequirementKeyFn): void;\n /**\n * Remove a previously registered requirement key function.\n *\n * @param requirementType - The requirement type string to remove.\n */\n removeRequirementKey(requirementType: string): void;\n}\n\n/**\n * Configuration options accepted by {@link createConstraintsManager}.\n *\n * @internal\n */\nexport interface CreateConstraintsOptions<S extends Schema> {\n /** Constraint definitions keyed by ID. */\n definitions: ConstraintsDef<S>;\n /** Proxy-based facts object used to evaluate `when()` predicates. */\n facts: Facts<S>;\n /** Custom key functions for requirement deduplication, keyed by requirement type. */\n requirementKeys?: Record<string, RequirementKeyFn>;\n /** Default timeout in milliseconds for async constraint evaluation (defaults to 5 000). */\n defaultTimeout?: number;\n /** Called after each constraint evaluation with the constraint ID and whether `when()` was active. */\n onEvaluate?: (id: string, active: boolean) => void;\n /** Called when a constraint's `when()` or `require()` throws. */\n onError?: (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 * @remarks\n * Constraints are evaluated in priority order (higher priority first), with\n * topological ordering for same-priority constraints connected by `after`\n * dependencies. The manager supports sync and async `when()` predicates,\n * incremental evaluation based on changed fact keys, and per-constraint\n * enable/disable toggling. Cycle detection runs eagerly at construction time\n * to prevent deadlocks in production.\n *\n * @param options - Configuration including constraint definitions, facts proxy,\n * custom requirement key functions, and lifecycle callbacks.\n * @returns A {@link ConstraintsManager} for evaluating, invalidating, and\n * managing constraint lifecycle.\n *\n * @example\n * ```typescript\n * const constraints = createConstraintsManager({\n * definitions: {\n * mustTransition: {\n * priority: 50,\n * when: (facts) => facts.phase === \"red\" && facts.elapsed > 30,\n * require: { type: \"TRANSITION\", to: \"green\" },\n * },\n * },\n * facts: factsProxy,\n * onEvaluate: (id, active) => console.log(id, active),\n * });\n *\n * const unmet = await constraints.evaluate();\n * ```\n *\n * @internal\n */\nexport function createConstraintsManager<S extends Schema>(\n options: CreateConstraintsOptions<S>,\n): ConstraintsManager<S> {\n const {\n definitions,\n facts,\n requirementKeys = {},\n defaultTimeout = DEFAULT_TIMEOUT,\n onEvaluate,\n onError,\n } = options;\n\n // Internal state for each constraint\n const states = new Map<string, ConstraintState>();\n const disabled = new Set<string>();\n\n // Track which constraints are async\n const asyncConstraintIds = new Set<string>();\n\n // Dependency tracking: which facts each constraint depends on\n const constraintDeps = new Map<string, Set<string>>();\n // Reverse mapping: which constraints depend on each fact\n const factToConstraints = new Map<string, Set<string>>();\n // Track which constraints need re-evaluation\n const dirtyConstraints = new Set<string>();\n // Cache latest when() deps so they can be combined with require() deps atomically\n const latestWhenDeps = new Map<string, Set<string>>();\n // Track last requirements for each constraint (for incremental updates)\n const lastRequirements = new Map<string, RequirementWithId[]>();\n // First evaluation flag\n let hasEvaluated = false;\n // Track resolved constraints (for `after` ordering)\n const resolvedConstraints = new Set<string>();\n // Track constraints that didn't fire (when() returned false) - they don't block\n const noFireConstraints = new Set<string>();\n // Reverse dependency map: which constraints depend on this one (for O(1) markResolved)\n const dependsOnMe = new Map<string, Set<string>>();\n // Topological order of constraints (dependencies before dependents)\n let topologicalOrder: string[] = [];\n // Cached topological index map for O(1) lookups during sorting\n let topologicalIndex: Map<string, number> = new Map();\n\n /** Register a single `after` dependency in the reverse map */\n function addReverseDep(depId: string, dependentId: string): void {\n if (!definitions[depId]) {\n return;\n }\n if (!dependsOnMe.has(depId)) {\n dependsOnMe.set(depId, new Set());\n }\n dependsOnMe.get(depId)!.add(dependentId);\n }\n\n /**\n * Build reverse dependency map for O(1) lookups in markResolved.\n * Maps each constraint ID to the set of constraints that depend on it via `after`.\n */\n function buildReverseDependencyMap(): void {\n dependsOnMe.clear();\n for (const [id, def] of Object.entries(definitions)) {\n if (!def.after) {\n continue;\n }\n for (const depId of def.after) {\n addReverseDep(depId, id);\n }\n }\n }\n\n /**\n * DFS visitor for cycle detection and topological ordering.\n * Throws on back edges (cycles). Appends to `postOrder` in post-order.\n */\n function topoVisit(\n id: string,\n path: string[],\n visited: Set<string>,\n visiting: Set<string>,\n postOrder: string[],\n ): void {\n if (visited.has(id)) {\n return;\n }\n\n if (visiting.has(id)) {\n const cycleStart = path.indexOf(id);\n const cycle = [...path.slice(cycleStart), id].join(\" \\u2192 \");\n throw new Error(\n `[Directive] Constraint cycle detected: ${cycle}. Remove one of the \\`after\\` dependencies to break the cycle.`,\n );\n }\n\n visiting.add(id);\n path.push(id);\n\n const def = definitions[id];\n if (def?.after) {\n for (const depId of def.after) {\n if (definitions[depId]) {\n topoVisit(depId, path, visited, visiting, postOrder);\n }\n }\n }\n\n path.pop();\n visiting.delete(id);\n visited.add(id);\n postOrder.push(id);\n }\n\n /**\n * Detect cycles in the constraint dependency graph and compute topological order.\n * Uses DFS to find back edges and post-order for topological sort.\n */\n function detectCyclesAndComputeTopoOrder(): void {\n const visited = new Set<string>();\n const visiting = new Set<string>();\n const postOrder: string[] = [];\n\n for (const id of Object.keys(definitions)) {\n topoVisit(id, [], visited, visiting, postOrder);\n }\n\n // Post-order with dependency-first traversal gives us topological order\n topologicalOrder = postOrder;\n\n // Build index map for O(1) lookups during sorting\n topologicalIndex = new Map(\n topologicalOrder.map((id, index) => [id, index]),\n );\n }\n\n // Validate constraint graph (always run - cycle in production would cause deadlock)\n // Also computes topological order for O(n) evaluation\n detectCyclesAndComputeTopoOrder();\n\n // Build reverse dependency map for O(1) markResolved lookups\n buildReverseDependencyMap();\n\n /** Warn about `after` references to non-existent constraints */\n function warnUnknownAfterRefs(): void {\n for (const [id, def] of Object.entries(definitions)) {\n if (!def.after) {\n continue;\n }\n for (const depId of def.after) {\n if (!definitions[depId]) {\n console.warn(\n `[Directive] Constraint \"${id}\" references unknown constraint \"${depId}\" in \\`after\\`. This dependency will be ignored. Check for typos or ensure the constraint exists.`,\n );\n }\n }\n }\n }\n\n // Validate `after` references in dev mode (catch typos early)\n if (process.env.NODE_ENV !== \"production\") {\n warnUnknownAfterRefs();\n }\n\n /**\n * Determine if a constraint is async.\n * Uses the explicit `async` flag if provided, otherwise falls back to runtime detection.\n * Runtime detection is only used on first evaluation and logs a dev warning.\n */\n function isAsyncConstraint(\n id: string,\n def: ConstraintsDef<S>[string],\n ): boolean {\n // Prefer explicit flag to avoid runtime detection side effects\n if (def.async !== undefined) {\n return def.async;\n }\n\n // Check if we've already detected this constraint as async\n if (asyncConstraintIds.has(id)) {\n return true;\n }\n\n // Runtime detection is deferred to first evaluation\n // We'll detect it in evaluateSync if it returns a Promise\n return false;\n }\n\n /** Initialize state for a constraint */\n function initState(id: string): ConstraintState {\n const def = definitions[id];\n if (!def) {\n throw new Error(`[Directive] Unknown constraint: ${id}`);\n }\n\n const isAsync = isAsyncConstraint(id, def);\n if (isAsync) {\n asyncConstraintIds.add(id);\n }\n\n const state: ConstraintState = {\n id,\n priority: def.priority ?? 0,\n isAsync,\n lastResult: null,\n isEvaluating: false,\n error: null,\n lastResolvedAt: null,\n after: def.after ?? [],\n hitCount: 0,\n lastActiveAt: null,\n };\n\n states.set(id, state);\n return state;\n }\n\n /** Get or create state for a constraint */\n function getState(id: string): ConstraintState {\n return states.get(id) ?? initState(id);\n }\n\n /** Check if two dependency sets are equal (returns false for empty sets) */\n function depsEqual(a: Set<string>, b: Set<string>): boolean {\n if (a.size !== b.size || a.size === 0) {\n return false;\n }\n for (const dep of b) {\n if (!a.has(dep)) {\n return false;\n }\n }\n\n return true;\n }\n\n /** Remove a constraint from the reverse fact-to-constraint map */\n function removeFromFactMap(id: string, deps: Set<string>): void {\n for (const dep of deps) {\n const constraints = factToConstraints.get(dep);\n if (!constraints) {\n continue;\n }\n constraints.delete(id);\n if (constraints.size === 0) {\n factToConstraints.delete(dep);\n }\n }\n }\n\n /** Add a constraint to the reverse fact-to-constraint map */\n function addToFactMap(id: string, deps: Set<string>): void {\n for (const dep of deps) {\n if (!factToConstraints.has(dep)) {\n factToConstraints.set(dep, new Set());\n }\n factToConstraints.get(dep)!.add(id);\n }\n }\n\n /** Remove a constraint from all dependency maps */\n function clearConstraintDeps(id: string): void {\n const deps = constraintDeps.get(id);\n if (deps) {\n removeFromFactMap(id, deps);\n constraintDeps.delete(id);\n }\n }\n\n /** Remove a constraint from the reverse dependency map (dependsOnMe) */\n function clearReverseDeps(id: string): void {\n dependsOnMe.delete(id);\n for (const depSet of dependsOnMe.values()) {\n depSet.delete(id);\n }\n }\n\n /** Update dependency tracking for a constraint */\n function updateDependencies(id: string, newDeps: Set<string>): void {\n const oldDeps = constraintDeps.get(id) ?? new Set();\n\n if (depsEqual(oldDeps, newDeps)) {\n return;\n }\n\n removeFromFactMap(id, oldDeps);\n addToFactMap(id, newDeps);\n constraintDeps.set(id, newDeps);\n }\n\n /** Track or evaluate the `when()` predicate, returning the result and recording deps */\n function evaluateWhenPredicate(\n id: string,\n def: ConstraintsDef<S>[string],\n ): boolean | Promise<boolean> {\n if (def.deps) {\n latestWhenDeps.set(id, new Set(def.deps));\n\n return def.when(facts);\n }\n\n // Track dependencies during evaluation\n const tracked = withTracking(() => def.when(facts));\n latestWhenDeps.set(id, tracked.deps);\n\n return tracked.value;\n }\n\n /** Update constraint state after a successful when() evaluation */\n function recordConstraintResult(\n id: string,\n state: ConstraintState,\n result: boolean,\n ): void {\n state.lastResult = result;\n if (result) {\n state.hitCount++;\n state.lastActiveAt = Date.now();\n }\n state.isEvaluating = false;\n onEvaluate?.(id, result);\n }\n\n /** Record a constraint evaluation error */\n function recordConstraintError(\n id: string,\n state: ConstraintState,\n error: unknown,\n ): void {\n state.error = error instanceof Error ? error : new Error(String(error));\n state.lastResult = false;\n state.isEvaluating = false;\n onError?.(id, error);\n }\n\n /** Handle runtime-detected async constraint: mark as async and return wrapped promise */\n function handleRuntimeAsyncResult(\n id: string,\n state: ConstraintState,\n promise: Promise<boolean>,\n ): Promise<boolean> {\n asyncConstraintIds.add(id);\n state.isAsync = true;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Directive] Constraint \"${id}\" returned a Promise but was not marked as async. Add \\`async: true\\` to the constraint definition to avoid this warning and improve performance.`,\n );\n }\n\n return promise\n .then((asyncResult) => {\n recordConstraintResult(id, state, asyncResult);\n\n return asyncResult;\n })\n .catch((error) => {\n recordConstraintError(id, state, error);\n\n return false;\n });\n }\n\n /** Evaluate a single sync constraint */\n function evaluateSync(id: string): boolean | Promise<boolean> {\n const def = definitions[id];\n if (!def) {\n return false;\n }\n\n const state = getState(id);\n state.isEvaluating = true;\n state.error = null;\n\n try {\n const result = evaluateWhenPredicate(id, def);\n\n // Runtime async detection: if this was thought to be sync but returns a Promise\n if (result instanceof Promise) {\n return handleRuntimeAsyncResult(id, state, result);\n }\n\n recordConstraintResult(id, state, result);\n\n return result;\n } catch (error) {\n recordConstraintError(id, state, error);\n\n return false;\n }\n }\n\n /** Evaluate a single async constraint with timeout */\n async function evaluateAsync(id: string): Promise<boolean> {\n const def = definitions[id];\n if (!def) {\n return false;\n }\n\n const state = getState(id);\n const timeout = def.timeout ?? defaultTimeout;\n\n state.isEvaluating = true;\n state.error = null;\n\n // Register explicit deps before await (auto-tracking can't work across async boundaries)\n if (def.deps?.length) {\n const depsSet = new Set(def.deps);\n updateDependencies(id, depsSet);\n latestWhenDeps.set(id, depsSet);\n }\n\n try {\n const resultPromise = def.when(facts) as Promise<boolean>;\n\n // Race against timeout (with proper cleanup)\n const result = await withTimeout(\n resultPromise,\n timeout,\n `Constraint \"${id}\" timed out after ${timeout}ms`,\n );\n\n state.lastResult = result;\n if (result) {\n state.hitCount++;\n state.lastActiveAt = Date.now();\n }\n state.isEvaluating = false;\n onEvaluate?.(id, result);\n return result;\n } catch (error) {\n state.error = error instanceof Error ? error : new Error(String(error));\n state.lastResult = false;\n state.isEvaluating = false;\n onError?.(id, error);\n return false;\n }\n }\n\n /** Max requirements per constraint before warning in dev mode */\n const MAX_REQUIREMENTS_WARNING_THRESHOLD = 10;\n\n /**\n * Normalize a requirement output to an array of requirements.\n * - null/undefined → []\n * - single requirement → [requirement]\n * - array → filtered to remove null/undefined\n */\n function normalizeRequirements(\n output: RequirementOutput,\n constraintId?: string,\n ): Requirement[] {\n if (output === null || output === undefined) {\n return [];\n }\n if (Array.isArray(output)) {\n // Filter out null/undefined from arrays\n const filtered = output.filter(\n (r): r is Requirement => r !== null && r !== undefined,\n );\n\n // Warn in dev mode if constraint produces many requirements\n if (\n process.env.NODE_ENV !== \"production\" &&\n filtered.length > MAX_REQUIREMENTS_WARNING_THRESHOLD &&\n constraintId\n ) {\n console.warn(\n `[Directive] Constraint \"${constraintId}\" produced ${filtered.length} requirements. Consider splitting into multiple constraints for better performance.`,\n );\n }\n\n return filtered;\n }\n return [output];\n }\n\n /** Get the requirements for a constraint, tracking dependencies if require is a function */\n function getRequirements(id: string): {\n requirements: Requirement[];\n deps: Set<string>;\n } {\n const def = definitions[id];\n if (!def) {\n return { requirements: [], deps: new Set() };\n }\n\n const requireDef = def.require;\n if (typeof requireDef === \"function\") {\n // Track dependencies when require is a function\n const { value: output, deps } = withTracking(() => requireDef(facts));\n const requirements = normalizeRequirements(\n output as RequirementOutput,\n id,\n );\n return { requirements, deps };\n }\n\n const requirements = normalizeRequirements(\n requireDef as RequirementOutput,\n id,\n );\n return { requirements, deps: new Set() };\n }\n\n /** Merge additional dependencies into existing constraint deps */\n function mergeDependencies(id: string, additionalDeps: Set<string>): void {\n if (additionalDeps.size === 0) {\n return;\n }\n\n const existingDeps = constraintDeps.get(id) ?? new Set();\n for (const dep of additionalDeps) {\n existingDeps.add(dep);\n }\n addToFactMap(id, additionalDeps);\n constraintDeps.set(id, existingDeps);\n }\n\n // Initialize all constraint states and cache sorted order\n let sortedConstraintIds: string[] | null = null;\n\n /**\n * Get constraint IDs sorted by:\n * 1. Priority (higher first)\n * 2. Topological order (dependencies before dependents) for same priority\n * This enables O(n) evaluation in the best case when priorities align with dependencies.\n *\n * Uses cached topologicalIndex for O(1) lookups during comparison.\n */\n function getSortedConstraintIds(): string[] {\n if (!sortedConstraintIds) {\n sortedConstraintIds = Object.keys(definitions).sort((a, b) => {\n const stateA = getState(a);\n const stateB = getState(b);\n\n // Primary sort: priority (higher first)\n const priorityDiff = stateB.priority - stateA.priority;\n if (priorityDiff !== 0) {\n return priorityDiff;\n }\n\n // Secondary sort: topological order (dependencies first)\n // Uses cached topologicalIndex for O(1) lookups\n const topoA = topologicalIndex.get(a) ?? 0;\n const topoB = topologicalIndex.get(b) ?? 0;\n return topoA - topoB;\n });\n }\n return sortedConstraintIds;\n }\n\n for (const id of Object.keys(definitions)) {\n initState(id);\n }\n\n /** Warn about async constraints without explicit deps (dev mode only) */\n function warnAsyncWithoutDeps(defs: ConstraintsDef<S>): void {\n for (const [id, def] of Object.entries(defs)) {\n if (def.async && !def.deps) {\n console.warn(\n `[Directive] Async constraint \"${id}\" has no \\`deps\\` declared. Auto-tracking cannot work across async boundaries. Add \\`deps: [\"key1\", \"key2\"]\\` to enable dependency tracking.`,\n );\n }\n }\n }\n\n // Dev-mode: warn about async constraints without explicit deps\n if (process.env.NODE_ENV !== \"production\") {\n warnAsyncWithoutDeps(definitions);\n }\n\n /**\n * Check if a single `after` dependency is satisfied (resolved, no-fire, disabled, or external).\n */\n function isAfterDepSatisfied(depId: string): boolean {\n // External deps (cross-module) are handled externally\n if (!definitions[depId]) {\n return true;\n }\n // Disabled deps can't fire\n if (disabled.has(depId)) {\n return true;\n }\n // Deps that didn't fire (when returned false) don't block\n if (noFireConstraints.has(depId)) {\n return true;\n }\n\n return resolvedConstraints.has(depId);\n }\n\n /**\n * Check if a constraint's `after` dependencies are satisfied.\n */\n function areAfterDependenciesSatisfied(id: string): boolean {\n const state = states.get(id);\n if (!state || state.after.length === 0) {\n return true;\n }\n\n for (const depId of state.after) {\n if (!isAfterDepSatisfied(depId)) {\n return false;\n }\n }\n\n return true;\n }\n\n /** Handle an inactive constraint: update deps and mark as no-fire */\n function handleInactiveConstraint(id: string): void {\n const whenDeps = latestWhenDeps.get(id);\n if (whenDeps !== undefined) {\n updateDependencies(id, whenDeps);\n }\n noFireConstraints.add(id);\n lastRequirements.set(id, []);\n }\n\n /** Update constraint deps atomically from when + require deps */\n function updateConstraintDeps(\n id: string,\n whenDeps: Set<string> | undefined,\n requireDeps: Set<string>,\n ): void {\n if (whenDeps !== undefined) {\n // Combine when() + require() deps atomically to prevent\n // require deps from being temporarily lost between updates\n const combinedDeps = new Set(whenDeps);\n for (const dep of requireDeps) {\n combinedDeps.add(dep);\n }\n updateDependencies(id, combinedDeps);\n } else {\n // Async constraint (no when deps tracked) — merge additively\n mergeDependencies(id, requireDeps);\n }\n }\n\n /** Emit requirements for an active constraint into the requirement set */\n function emitConstraintRequirements(\n id: string,\n reqs: Requirement[],\n requirements: RequirementSet,\n ): void {\n if (reqs.length === 0) {\n lastRequirements.set(id, []);\n\n return;\n }\n const reqsWithId = reqs.map((req) =>\n createRequirementWithId(req, id, requirementKeys[req.type]),\n );\n for (const reqWithId of reqsWithId) {\n requirements.add(reqWithId);\n }\n lastRequirements.set(id, reqsWithId);\n }\n\n /** Add cached requirements into the requirement set */\n function addCachedRequirements(\n reqs: RequirementWithId[],\n requirements: RequirementSet,\n ): void {\n for (const req of reqs) {\n requirements.add(req);\n }\n }\n\n /**\n * Process a constraint result: handle requirements and track no-fire state.\n * Extracted from evaluate() to reduce nesting-based cognitive complexity.\n */\n function processConstraintResult(\n id: string,\n active: boolean,\n requirements: RequirementSet,\n ): void {\n if (disabled.has(id)) {\n return;\n }\n\n if (!active) {\n handleInactiveConstraint(id);\n\n return;\n }\n\n // Remove from no-fire tracking since it fired\n noFireConstraints.delete(id);\n\n const whenDeps = latestWhenDeps.get(id);\n let reqs: Requirement[];\n let requireDeps: Set<string>;\n try {\n const result = getRequirements(id);\n reqs = result.requirements;\n requireDeps = result.deps;\n } catch (error) {\n onError?.(id, error);\n handleInactiveConstraint(id);\n\n return;\n }\n\n updateConstraintDeps(id, whenDeps, requireDeps);\n emitConstraintRequirements(id, reqs, requirements);\n }\n\n /** Partition constraint IDs into blocked and ready based on `after` deps */\n function partitionByReadiness(\n constraintIds: string[],\n requirements: RequirementSet,\n ): { blocked: string[]; ready: string[] } {\n const blocked: string[] = [];\n const ready: string[] = [];\n\n for (const id of constraintIds) {\n if (areAfterDependenciesSatisfied(id)) {\n ready.push(id);\n continue;\n }\n blocked.push(id);\n const lastReqs = lastRequirements.get(id);\n if (lastReqs) {\n addCachedRequirements(lastReqs, requirements);\n }\n }\n\n return { blocked, ready };\n }\n\n /** Evaluate sync constraints, returning any that turned out to be async at runtime */\n function evaluateSyncBatch(\n syncIds: string[],\n requirements: RequirementSet,\n ): Array<{ id: string; promise: Promise<boolean> }> {\n const unexpectedAsync: Array<{ id: string; promise: Promise<boolean> }> =\n [];\n\n for (const id of syncIds) {\n const result = evaluateSync(id);\n\n if (result instanceof Promise) {\n unexpectedAsync.push({ id, promise: result });\n continue;\n }\n\n processConstraintResult(id, result, requirements);\n }\n\n return unexpectedAsync;\n }\n\n /** Await an array of {id, promise} pairs and process each result */\n async function awaitAndProcess(\n pairs: Array<{ id: string; promise: Promise<boolean> }>,\n requirements: RequirementSet,\n ): Promise<void> {\n const results = await Promise.all(\n pairs.map(async ({ id, promise }) => ({\n id,\n active: await promise,\n })),\n );\n for (const { id, active } of results) {\n processConstraintResult(id, active, requirements);\n }\n }\n\n /**\n * Evaluate constraints, respecting `after` dependencies.\n * Returns list of constraints that are still blocked after this pass.\n */\n async function evaluateConstraintBatch(\n constraintIds: string[],\n requirements: RequirementSet,\n ): Promise<string[]> {\n const { blocked, ready } = partitionByReadiness(\n constraintIds,\n requirements,\n );\n\n if (ready.length === 0) {\n return blocked;\n }\n\n // Separate sync and async constraints from ready-to-evaluate\n const syncConstraints: string[] = [];\n const asyncConstraints: string[] = [];\n\n for (const id of ready) {\n if (getState(id).isAsync) {\n asyncConstraints.push(id);\n } else {\n syncConstraints.push(id);\n }\n }\n\n // Evaluate sync constraints first (some may turn out async at runtime)\n const unexpectedAsync = evaluateSyncBatch(syncConstraints, requirements);\n\n // Handle sync constraints that turned out to be async\n if (unexpectedAsync.length > 0) {\n await awaitAndProcess(unexpectedAsync, requirements);\n }\n\n // Evaluate async constraints in parallel\n if (asyncConstraints.length > 0) {\n const asyncPairs = asyncConstraints.map((id) => ({\n id,\n promise: evaluateAsync(id),\n }));\n await awaitAndProcess(asyncPairs, requirements);\n }\n\n return blocked;\n }\n\n /** Collect enabled constraint IDs affected by a set of changed fact keys */\n function collectAffectedByKeys(\n changedKeys: Set<string>,\n into: Set<string>,\n ): void {\n for (const key of changedKeys) {\n const deps = factToConstraints.get(key);\n if (!deps) {\n continue;\n }\n for (const id of deps) {\n if (!disabled.has(id)) {\n into.add(id);\n }\n }\n }\n }\n\n /** Collect enabled dirty constraints into a set */\n function collectDirtyConstraints(into: Set<string>): void {\n for (const id of dirtyConstraints) {\n if (!disabled.has(id)) {\n into.add(id);\n }\n }\n dirtyConstraints.clear();\n }\n\n /** Compute the set of affected constraint IDs from changed keys + dirty set */\n function computeAffectedConstraints(changedKeys: Set<string>): Set<string> {\n const affected = new Set<string>();\n collectAffectedByKeys(changedKeys, affected);\n collectDirtyConstraints(affected);\n\n return affected;\n }\n\n /** Carry forward cached requirements for constraints not being re-evaluated */\n function carryForwardRequirements(\n allIds: string[],\n affected: Set<string>,\n requirements: RequirementSet,\n ): void {\n for (const id of allIds) {\n if (affected.has(id)) {\n continue;\n }\n const lastReqs = lastRequirements.get(id);\n if (lastReqs) {\n addCachedRequirements(lastReqs, requirements);\n }\n }\n }\n\n const manager: ConstraintsManager<S> = {\n async evaluate(changedKeys?: Set<string>): Promise<RequirementWithId[]> {\n const requirements = new RequirementSet();\n\n // Note: resolvedConstraints persists across reconcile cycles intentionally.\n // `after` ordering means \"wait until dependency's resolver has completed\",\n // and that completion happens in a different cycle than the evaluation.\n // noFireConstraints is re-populated during each evaluation pass.\n noFireConstraints.clear();\n\n // Get all enabled constraints (use cached sort order)\n const allConstraintIds = getSortedConstraintIds().filter(\n (id) => !disabled.has(id),\n );\n\n // Determine which constraints to evaluate\n let constraintsToEvaluate: string[];\n\n if (!hasEvaluated || !changedKeys || changedKeys.size === 0) {\n // First evaluation or no specific changes: evaluate all\n constraintsToEvaluate = allConstraintIds;\n hasEvaluated = true;\n } else {\n const affected = computeAffectedConstraints(changedKeys);\n constraintsToEvaluate = [...affected];\n carryForwardRequirements(allConstraintIds, affected, requirements);\n }\n\n // Evaluate constraints in passes until no blocked constraints become unblocked\n let remainingToEvaluate = constraintsToEvaluate;\n let maxPasses = constraintsToEvaluate.length + 1; // Prevent infinite loops\n\n while (remainingToEvaluate.length > 0 && maxPasses > 0) {\n const previousRemaining = remainingToEvaluate.length;\n remainingToEvaluate = await evaluateConstraintBatch(\n remainingToEvaluate,\n requirements,\n );\n\n // If no progress was made (all still blocked), break\n if (remainingToEvaluate.length === previousRemaining) {\n break;\n }\n maxPasses--;\n }\n\n return requirements.all();\n },\n\n getState(id: string): ConstraintState | undefined {\n return states.get(id);\n },\n\n getDependencies(id: string): Set<string> | undefined {\n return constraintDeps.get(id);\n },\n\n getAllStates(): ConstraintState[] {\n return [...states.values()];\n },\n\n disable(id: string): void {\n if (!states.has(id)) {\n console.warn(\n `[Directive] constraints.disable(\"${id}\") — no such constraint`,\n );\n\n return;\n }\n disabled.add(id);\n // Invalidate cache when constraints change\n sortedConstraintIds = null;\n // Mark as dirty so it gets removed from requirements on next evaluate\n lastRequirements.delete(id);\n // Clean up dependency maps for disabled constraint\n clearConstraintDeps(id);\n latestWhenDeps.delete(id);\n },\n\n enable(id: string): void {\n if (!states.has(id)) {\n console.warn(\n `[Directive] constraints.enable(\"${id}\") — no such constraint`,\n );\n\n return;\n }\n disabled.delete(id);\n // Invalidate cache when constraints change\n sortedConstraintIds = null;\n // Mark as dirty so it gets evaluated on next cycle\n dirtyConstraints.add(id);\n },\n\n isDisabled(id: string): boolean {\n return disabled.has(id);\n },\n\n invalidate(factKey: string): void {\n // Mark all constraints that depend on this fact as dirty\n const dependentConstraints = factToConstraints.get(factKey);\n if (dependentConstraints) {\n for (const id of dependentConstraints) {\n dirtyConstraints.add(id);\n }\n }\n },\n\n markResolved(constraintId: string): void {\n resolvedConstraints.add(constraintId);\n const state = states.get(constraintId);\n if (state) {\n state.lastResolvedAt = Date.now();\n }\n\n // Mark all constraints that depend on this one (via `after`) as dirty\n // so they get re-evaluated on the next reconcile\n // Uses reverse dependency map for O(1) lookup instead of O(n*m) iteration\n const dependents = dependsOnMe.get(constraintId);\n if (dependents) {\n for (const id of dependents) {\n dirtyConstraints.add(id);\n }\n }\n },\n\n isResolved(constraintId: string): boolean {\n return resolvedConstraints.has(constraintId);\n },\n\n registerDefinitions(newDefs: ConstraintsDef<Schema>): void {\n let hasAfterDeps = false;\n for (const [key, def] of Object.entries(newDefs)) {\n (definitions as Record<string, unknown>)[key] = def;\n initState(key);\n dirtyConstraints.add(key);\n if (def.after?.length) {\n hasAfterDeps = true;\n }\n }\n // Invalidate cached sort order\n sortedConstraintIds = null;\n // Only rebuild topo order when new constraints have `after` dependencies\n if (hasAfterDeps) {\n detectCyclesAndComputeTopoOrder();\n }\n // Always rebuild reverse deps — existing constraints may reference\n // newly-added IDs in their `after` arrays (forward references)\n buildReverseDependencyMap();\n },\n\n assignDefinition(id: string, def: ConstraintsDef<Schema>[string]): void {\n if (!definitions[id]) {\n throw new Error(\n `[Directive] Cannot assign constraint \"${id}\" — it does not exist. Use register() to create it.`,\n );\n }\n\n // Replace definition\n (definitions as Record<string, unknown>)[id] = def;\n // Re-init state for the new definition\n initState(id);\n dirtyConstraints.add(id);\n // Invalidate cached sort order (priority may have changed)\n sortedConstraintIds = null;\n // Rebuild topo order + reverse deps in case `after` changed\n detectCyclesAndComputeTopoOrder();\n buildReverseDependencyMap();\n },\n\n unregisterDefinition(id: string): void {\n if (!definitions[id]) {\n return;\n }\n\n // Remove from all internal maps\n delete (definitions as Record<string, unknown>)[id];\n states.delete(id);\n disabled.delete(id);\n asyncConstraintIds.delete(id);\n dirtyConstraints.delete(id);\n noFireConstraints.delete(id);\n resolvedConstraints.delete(id);\n lastRequirements.delete(id);\n latestWhenDeps.delete(id);\n\n // Clean dependency and reverse dependency maps\n clearConstraintDeps(id);\n clearReverseDeps(id);\n\n // Invalidate cached sort order\n sortedConstraintIds = null;\n // Rebuild topo order\n detectCyclesAndComputeTopoOrder();\n buildReverseDependencyMap();\n },\n\n async callOne(\n id: string,\n props?: Record<string, unknown>,\n ): Promise<RequirementWithId[]> {\n const def = definitions[id];\n if (!def) {\n throw new Error(\n `[Directive] Cannot call constraint \"${id}\" — it does not exist.`,\n );\n }\n\n // Respect disabled state\n if (disabled.has(id)) {\n return [];\n }\n\n const state = getState(id);\n let active: boolean;\n\n if (state.isAsync) {\n active = await evaluateAsync(id);\n } else {\n const result = evaluateSync(id);\n active = result instanceof Promise ? await result : result;\n }\n\n if (!active) {\n return [];\n }\n\n // Get requirements and merge props if provided\n const { requirements: reqs } = getRequirements(id);\n if (reqs.length === 0) {\n return [];\n }\n\n const result: RequirementWithId[] = [];\n for (const req of reqs) {\n const merged = props ? { ...req, ...props } : req;\n result.push(\n createRequirementWithId(merged, id, requirementKeys[merged.type]),\n );\n }\n\n return result;\n },\n\n setRequirementKey(requirementType: string, keyFn: RequirementKeyFn): void {\n requirementKeys[requirementType] = keyFn;\n },\n\n removeRequirementKey(requirementType: string): void {\n delete requirementKeys[requirementType];\n },\n };\n\n return 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 { BLOCKED_PROPS, trackAccess, withTracking } from \"./tracking.js\";\nimport type {\n DerivationState,\n DerivationsDef,\n DerivedValues,\n Facts,\n Schema,\n} from \"./types.js\";\n\n// ============================================================================\n// Derivations Manager\n// ============================================================================\n\nexport interface DerivationsManager<\n S extends Schema,\n D extends DerivationsDef<S>,\n> {\n /** Get a derived value (computes if stale) */\n get<K extends keyof D>(id: K): ReturnType<D[K]>;\n /** Check if a derivation is stale */\n isStale(id: keyof D): boolean;\n /** Invalidate derivations that depend on a fact key */\n invalidate(factKey: string): void;\n /** Invalidate derivations for multiple fact keys, notifying listeners once at the end */\n invalidateMany(factKeys: Iterable<string>): void;\n /** Invalidate all derivations */\n invalidateAll(): void;\n /** Subscribe to derivation changes */\n subscribe(ids: Array<keyof D>, listener: () => void): () => void;\n /** Get the proxy for composition */\n getProxy(): DerivedValues<S, D>;\n /** Get dependencies for a derivation */\n getDependencies(id: keyof D): Set<string>;\n /** Register new derivation definitions (for dynamic module registration) */\n registerDefinitions(newDefs: DerivationsDef<S>): void;\n /** Override an existing derivation function */\n assignDefinition(\n id: string,\n fn: DerivationsDef<S>[keyof DerivationsDef<S>],\n ): void;\n /** Remove a derivation and clean up its state */\n unregisterDefinition(id: string): void;\n /** Compute a derivation immediately (ignores cache) */\n callOne(id: string): unknown;\n}\n\n/** Options for creating a derivations manager */\nexport interface CreateDerivationsOptions<\n S extends Schema,\n D extends DerivationsDef<S>,\n> {\n definitions: D;\n facts: Facts<S>;\n /** Callback when a derivation is computed */\n onCompute?: (\n id: string,\n value: unknown,\n oldValue: unknown,\n deps: string[],\n ) => void;\n /** Callback when a derivation is invalidated */\n onInvalidate?: (id: string) => void;\n /** Callback when a derivation errors */\n onError?: (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\n * lifecycle callbacks.\n * @returns A {@link DerivationsManager} for accessing, invalidating, and\n * subscribing to derived values.\n *\n * @internal\n */\nexport function createDerivationsManager<\n S extends Schema,\n D extends DerivationsDef<S>,\n>(options: CreateDerivationsOptions<S, D>): DerivationsManager<S, D> {\n const { definitions, facts, onCompute, onInvalidate, onError } = options;\n\n // Internal state for each derivation\n const states = new Map<string, DerivationState<unknown>>();\n const listeners = new Map<string, Set<() => void>>();\n\n // Track which derivations depend on which fact keys\n const factToDerivedDeps = new Map<string, Set<string>>();\n // Track which derivations depend on which other derivations\n const derivedToDerivedDeps = new Map<string, Set<string>>();\n\n // Deferred notification: during invalidation, collect IDs to notify.\n // Listeners fire AFTER all invalidations complete so they see consistent state.\n let invalidationDepth = 0;\n const pendingNotifications = new Set<string>();\n let isFlushing = false;\n const MAX_FLUSH_ITERATIONS = 100;\n\n // The proxy for composition (derivations accessing other derivations)\n // biome-ignore lint/style/useConst: Reassigned later in createDerivedProxy()\n let derivedProxy: DerivedValues<S, D>;\n\n // ---- Shared dependency-map helpers ----\n\n /**\n * Remove `id` from the dep-set keyed by `dep`. Deletes empty sets.\n * Uses `states.has(dep)` (not `definitions`) because during unregister\n * the definition may already be deleted while state still exists.\n */\n function removeDepLink(dep: string, id: string): void {\n const map = states.has(dep) ? derivedToDerivedDeps : factToDerivedDeps;\n const depSet = map.get(dep);\n depSet?.delete(id);\n if (depSet && depSet.size === 0) {\n map.delete(dep);\n }\n }\n\n /**\n * Add `id` to the dep-set keyed by `dep`, creating the set if needed.\n * Uses `definitions[dep]` (not `states`) because when adding a new link\n * the definition must exist — this is the forward path during recomputation.\n */\n function addDepLink(dep: string, id: string): void {\n const map = definitions[dep as keyof D]\n ? derivedToDerivedDeps\n : factToDerivedDeps;\n let depSet = map.get(dep);\n if (!depSet) {\n depSet = new Set();\n map.set(dep, depSet);\n }\n depSet.add(id);\n }\n\n /** Remove `id` from all dependency maps it participates in */\n function removeOwnDepLinks(id: string): void {\n const state = states.get(id);\n if (!state) {\n return;\n }\n for (const dep of state.dependencies) {\n removeDepLink(dep, id);\n }\n }\n\n /** Invalidate derivations that depend on `id`, then clean up its entry */\n function invalidateDependentsOf(id: string): void {\n const dependents = derivedToDerivedDeps.get(id);\n if (!dependents) {\n return;\n }\n\n invalidationDepth++;\n try {\n for (const dependent of dependents) {\n invalidateDerivation(dependent);\n }\n } finally {\n invalidationDepth--;\n }\n derivedToDerivedDeps.delete(id);\n }\n\n /** Remove a derivation from all internal maps */\n function purgeFromMaps(id: string): void {\n delete (definitions as Record<string, unknown>)[id];\n states.delete(id);\n listeners.delete(id);\n pendingNotifications.delete(id);\n }\n\n /** Initialize state for a derivation */\n function initState(id: string): DerivationState<unknown> {\n const def = definitions[id as keyof D];\n if (!def) {\n throw new Error(`[Directive] Unknown derivation: ${id}`);\n }\n\n const state: DerivationState<unknown> = {\n id,\n compute: () => computeDerivation(id),\n cachedValue: undefined,\n dependencies: new Set(),\n isStale: true,\n isComputing: false,\n };\n\n states.set(id, state);\n return state;\n }\n\n /** Get or create state for a derivation */\n function getState(id: string): DerivationState<unknown> {\n return states.get(id) ?? initState(id);\n }\n\n /** Compute a derivation and track its dependencies */\n function computeDerivation(id: string): unknown {\n const state = getState(id);\n const def = definitions[id as keyof D];\n\n if (!def) {\n throw new Error(`[Directive] Unknown derivation: ${id}`);\n }\n\n // Circular dependency detection\n if (state.isComputing) {\n throw new Error(\n `[Directive] Circular dependency detected in derivation: ${id}`,\n );\n }\n\n state.isComputing = true;\n\n try {\n // Capture old value before recomputation\n const oldValue = state.cachedValue;\n\n // Compute with tracking\n const { value, deps } = withTracking(() => def(facts, derivedProxy));\n\n // Update state\n state.cachedValue = value;\n state.isStale = false;\n\n // Update dependency tracking\n updateDependencies(id, deps);\n\n // Notify callback\n onCompute?.(id, value, oldValue, [...deps]);\n\n return value;\n } catch (error) {\n onError?.(id, error);\n throw error;\n } finally {\n state.isComputing = false;\n }\n }\n\n /** Check whether two Sets contain the same elements */\n function setsEqual(a: Set<string>, b: Set<string>): boolean {\n if (a.size !== b.size) {\n return false;\n }\n for (const dep of b) {\n if (!a.has(dep)) {\n return false;\n }\n }\n\n return true;\n }\n\n /** Update dependency tracking for a derivation */\n function updateDependencies(id: string, newDeps: Set<string>): void {\n const state = getState(id);\n const oldDeps = state.dependencies;\n\n if (setsEqual(oldDeps, newDeps)) {\n return;\n }\n\n for (const dep of oldDeps) {\n removeDepLink(dep, id);\n }\n for (const dep of newDeps) {\n addDepLink(dep, id);\n }\n\n state.dependencies = newDeps;\n }\n\n /** Notify all listeners for the given derivation ids */\n function notifyListeners(ids: string[]): void {\n for (const id of ids) {\n const fns = listeners.get(id);\n if (fns) {\n for (const listener of fns) {\n listener();\n }\n }\n }\n }\n\n /** Flush deferred notifications after all invalidations complete */\n function flushNotifications(): void {\n if (invalidationDepth > 0 || isFlushing) {\n return;\n }\n\n isFlushing = true;\n try {\n // Loop until no more pending — listeners may trigger new invalidations\n // that add to pendingNotifications via re-entrant invalidate() calls.\n let iterations = 0;\n while (pendingNotifications.size > 0) {\n if (++iterations > MAX_FLUSH_ITERATIONS) {\n const remaining = [...pendingNotifications];\n pendingNotifications.clear();\n throw new Error(\n `[Directive] Infinite derivation notification loop detected after ${MAX_FLUSH_ITERATIONS} iterations. Remaining: ${remaining.join(\", \")}. This usually means a derivation listener is mutating facts that re-trigger the same derivation.`,\n );\n }\n\n const ids = [...pendingNotifications];\n pendingNotifications.clear();\n notifyListeners(ids);\n }\n } finally {\n isFlushing = false;\n }\n }\n\n /** Enqueue transitive dependents of `id` into the work queue */\n function enqueueDependents(id: string, queue: string[]): void {\n const dependents = derivedToDerivedDeps.get(id);\n if (!dependents) {\n return;\n }\n for (const dependent of dependents) {\n queue.push(dependent);\n }\n }\n\n /**\n * Invalidate a derivation and its transitive dependents using iterative\n * traversal (work queue) to avoid stack overflow on deep chains.\n *\n * Accepts an optional shared `visited` Set so that `invalidateMany` can\n * coalesce multiple root invalidations into a single traversal.\n */\n function invalidateDerivation(\n startId: string,\n visited = new Set<string>(),\n ): void {\n const queue = [startId];\n\n while (queue.length > 0) {\n const id = queue.pop()!;\n if (visited.has(id)) {\n continue;\n }\n visited.add(id);\n\n const state = states.get(id);\n if (!state || state.isStale) {\n continue;\n }\n\n state.isStale = true;\n onInvalidate?.(id);\n\n // Defer listener notification until all invalidations complete.\n // This prevents listeners from observing partially-stale state and\n // avoids infinite loops from Set mutation during iteration (listeners\n // recompute derivations → updateDependencies → modify dep Sets).\n pendingNotifications.add(id);\n\n enqueueDependents(id, queue);\n }\n }\n\n // Create the proxy for composition\n derivedProxy = new Proxy({} as DerivedValues<S, D>, {\n get(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n\n // Return undefined for unknown derivation keys instead of throwing.\n // React 19 dev-mode traverses objects accessing $$typeof, toJSON, then, etc.\n if (!definitions[prop as keyof D]) {\n return undefined;\n }\n\n // Track this derivation access so the consuming derivation\n // records a dependency on it (enables composition invalidation)\n trackAccess(prop);\n\n const state = getState(prop);\n\n // Recompute if stale\n if (state.isStale) {\n computeDerivation(prop);\n }\n\n return state.cachedValue;\n },\n\n set() {\n return false;\n },\n\n deleteProperty() {\n return false;\n },\n\n defineProperty() {\n return false;\n },\n\n getPrototypeOf() {\n return null;\n },\n\n setPrototypeOf() {\n return false;\n },\n });\n\n // Note: Fact change invalidation is handled by the engine calling invalidate()\n\n const manager: DerivationsManager<S, D> = {\n get<K extends keyof D>(id: K): ReturnType<D[K]> {\n const state = getState(id as string);\n\n if (state.isStale) {\n computeDerivation(id as string);\n }\n\n return state.cachedValue as ReturnType<D[K]>;\n },\n\n isStale(id: keyof D): boolean {\n const state = states.get(id as string);\n return state?.isStale ?? true;\n },\n\n invalidate(factKey: string): void {\n const dependents = factToDerivedDeps.get(factKey);\n if (!dependents) return;\n\n invalidationDepth++;\n const visited = new Set<string>();\n try {\n for (const id of dependents) {\n invalidateDerivation(id, visited);\n }\n } finally {\n invalidationDepth--;\n flushNotifications();\n }\n },\n\n invalidateMany(factKeys: Iterable<string>): void {\n invalidationDepth++;\n // Share a single visited Set across all root invalidations so\n // transitive dependents are only processed once.\n const visited = new Set<string>();\n try {\n for (const factKey of factKeys) {\n const dependents = factToDerivedDeps.get(factKey);\n if (!dependents) continue;\n for (const id of dependents) {\n invalidateDerivation(id, visited);\n }\n }\n } finally {\n invalidationDepth--;\n flushNotifications();\n }\n },\n\n invalidateAll(): void {\n invalidationDepth++;\n try {\n for (const state of states.values()) {\n if (!state.isStale) {\n state.isStale = true;\n pendingNotifications.add(state.id);\n }\n }\n } finally {\n invalidationDepth--;\n flushNotifications();\n }\n },\n\n subscribe(ids: Array<keyof D>, listener: () => void): () => void {\n for (const id of ids) {\n const idStr = id as string;\n if (!listeners.has(idStr)) {\n listeners.set(idStr, new Set());\n }\n listeners.get(idStr)!.add(listener);\n }\n\n return () => {\n for (const id of ids) {\n const idStr = id as string;\n const listenerSet = listeners.get(idStr);\n listenerSet?.delete(listener);\n // Clean up empty Sets to prevent memory leaks\n if (listenerSet && listenerSet.size === 0) {\n listeners.delete(idStr);\n }\n }\n };\n },\n\n getProxy(): DerivedValues<S, D> {\n return derivedProxy;\n },\n\n getDependencies(id: keyof D): Set<string> {\n return getState(id as string).dependencies;\n },\n\n registerDefinitions(newDefs: DerivationsDef<S>): void {\n for (const [key, fn] of Object.entries(newDefs)) {\n (definitions as Record<string, unknown>)[key] = fn;\n initState(key);\n }\n },\n\n assignDefinition(\n id: string,\n fn: DerivationsDef<S>[keyof DerivationsDef<S>],\n ): void {\n if (!definitions[id as keyof D]) {\n throw new Error(\n `[Directive] Cannot assign derivation \"${id}\" — it does not exist. Use register() to create it.`,\n );\n }\n\n // Replace definition\n (definitions as Record<string, unknown>)[id] = fn;\n\n // Mark stale so it recomputes with the new function\n const state = states.get(id);\n if (state) {\n state.isStale = true;\n pendingNotifications.add(id);\n }\n\n flushNotifications();\n },\n\n unregisterDefinition(id: string): void {\n if (!definitions[id as keyof D]) {\n return;\n }\n\n removeOwnDepLinks(id);\n invalidateDependentsOf(id);\n purgeFromMaps(id);\n\n flushNotifications();\n },\n\n callOne(id: string): unknown {\n const def = definitions[id as keyof D];\n if (!def) {\n throw new Error(\n `[Directive] Cannot call derivation \"${id}\" — it does not exist.`,\n );\n }\n\n // Always recompute (call ignores cache)\n return computeDerivation(id);\n },\n };\n\n return 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 EffectsDef,\n Facts,\n FactsStore,\n InferSchema,\n Schema,\n} from \"./types.js\";\n\n// ============================================================================\n// Effects Manager\n// ============================================================================\n\n/**\n * Manager returned by {@link createEffectsManager} that runs fire-and-forget\n * side effects after facts stabilize.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface EffectsManager<_S extends Schema = Schema> {\n /**\n * Run all effects whose tracked dependencies overlap with `changedKeys`.\n *\n * @remarks\n * Effects with no recorded dependencies (first run or auto-tracked with no\n * reads) run on any change. After execution, a snapshot of current facts is\n * stored for the `prev` parameter on the next invocation.\n *\n * @param changedKeys - Fact keys that changed since the last run.\n */\n runEffects(changedKeys: Set<string>): Promise<void>;\n /**\n * Run every enabled effect unconditionally, regardless of dependencies.\n */\n runAll(): Promise<void>;\n /**\n * Disable an effect so it is skipped during subsequent runs.\n *\n * @param id - The effect definition ID.\n */\n disable(id: string): void;\n /**\n * Re-enable a previously disabled effect.\n *\n * @param id - The effect definition ID.\n */\n enable(id: string): void;\n /**\n * Check whether an effect is currently enabled.\n *\n * @param id - The effect definition ID.\n * @returns `true` if the effect has not been disabled.\n */\n isEnabled(id: string): boolean;\n /**\n * Invoke every stored cleanup function and mark the manager as stopped.\n *\n * @remarks\n * After this call, any cleanup functions returned by in-flight async effects\n * will be invoked immediately rather than stored.\n */\n cleanupAll(): void;\n /**\n * Register additional effect definitions at runtime (used for dynamic\n * module registration).\n *\n * @param newDefs - New effect definitions to merge into the manager.\n */\n registerDefinitions(newDefs: EffectsDef<Schema>): void;\n /**\n * Override an existing effect definition. Runs cleanup of the old effect first.\n *\n * @param id - The effect definition ID to override.\n * @param def - The new effect definition.\n * @throws If no effect with this ID exists.\n */\n assignDefinition(id: string, def: EffectsDef<Schema>[string]): void;\n /**\n * Remove an effect definition. Runs cleanup (try-catch) and removes from state.\n *\n * @param id - The effect definition ID to remove.\n */\n unregisterDefinition(id: string): void;\n /**\n * Execute an effect's `run()` function immediately.\n *\n * @param id - The effect definition ID.\n */\n callOne(id: string): Promise<void>;\n}\n\n/** Number of consecutive identical dep sets before skipping re-tracking */\nconst STABLE_THRESHOLD = 3;\n\n/** Internal effect state */\ninterface EffectState {\n id: string;\n enabled: boolean;\n hasExplicitDeps: boolean; // true = user-provided deps (fixed), false = auto-tracked (re-track every run)\n dependencies: Set<string> | null; // null = not yet tracked\n cleanup: (() => void) | null; // cleanup function returned by last run()\n /** How many consecutive runs produced the same deps (auto-tracked only) */\n stableRunCount: number;\n /** Once true, skip withTracking() overhead until a tracked fact mutates */\n depsStable: boolean;\n}\n\n/**\n * Configuration options accepted by {@link createEffectsManager}.\n *\n * @internal\n */\nexport interface CreateEffectsOptions<S extends Schema> {\n /** Effect definitions keyed by ID. */\n definitions: EffectsDef<S>;\n /** Proxy-based facts object passed to effect `run()` functions. */\n facts: Facts<S>;\n /** Underlying fact store used for `batch()` coalescing of mutations. */\n store: FactsStore<S>;\n /** Called when an effect executes, with the fact keys that triggered it. */\n onRun?: (id: string, deps: string[]) => void;\n /** Called when an effect's `run()` or cleanup function throws. */\n onError?: (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 * @remarks\n * Effects support two dependency modes:\n *\n * - **Auto-tracked** (no `deps`): Dependencies are re-tracked on every run\n * via {@link withTracking}, so conditional fact reads are always captured.\n * Only synchronous reads are tracked; reads after an `await` are invisible.\n *\n * - **Explicit `deps`**: A fixed array of fact keys declared on the definition.\n * Preferred for async effects where auto-tracking cannot cross `await`\n * boundaries.\n *\n * Each effect can return a cleanup function that runs before the next\n * execution or when {@link EffectsManager.cleanupAll | cleanupAll} is called.\n * Errors in effects are isolated via try-catch and never break the\n * reconciliation loop. Synchronous fact mutations inside effects are\n * coalesced with `store.batch()`.\n *\n * @param options - Configuration including effect definitions, facts proxy,\n * store, and lifecycle callbacks.\n * @returns An {@link EffectsManager} for running, enabling/disabling, and\n * cleaning up effects.\n *\n * @example\n * ```typescript\n * const effects = createEffectsManager({\n * definitions: {\n * logPhase: {\n * run: (facts, prev) => {\n * if (prev?.phase !== facts.phase) {\n * console.log(`Phase changed to ${facts.phase}`);\n * }\n * },\n * },\n * },\n * facts: factsProxy,\n * store: factsStore,\n * });\n *\n * await effects.runEffects(new Set([\"phase\"]));\n * ```\n *\n * @internal\n */\nexport function createEffectsManager<S extends Schema>(\n options: CreateEffectsOptions<S>,\n): EffectsManager<S> {\n const { definitions, facts, store, onRun, onError } = options;\n\n // Internal state for each effect\n const states = new Map<string, EffectState>();\n\n // Previous facts snapshot for comparison (plain object for bracket-style proxy access)\n let previousSnapshot: Record<string, unknown> | null = null;\n\n // Track whether cleanupAll has been called (system stopped/destroyed).\n // If an async effect resolves after stop, its cleanup is invoked immediately.\n let stopped = false;\n\n /** Initialize state for an effect */\n function initState(id: string): EffectState {\n const def = definitions[id];\n if (!def) {\n throw new Error(`[Directive] Unknown effect: ${id}`);\n }\n\n const state: EffectState = {\n id,\n enabled: true,\n hasExplicitDeps: !!def.deps,\n dependencies: def.deps ? new Set(def.deps as string[]) : null,\n cleanup: null,\n stableRunCount: 0,\n depsStable: false,\n };\n\n states.set(id, state);\n return state;\n }\n\n /** Get or create state for an effect */\n function getState(id: string): EffectState {\n return states.get(id) ?? initState(id);\n }\n\n /** Create a plain-object snapshot of current facts.\n * Effects receive `prev` through module-scoped proxies (system.ts) that use\n * bracket-style property access, so the snapshot must be a plain object —\n * NOT a FactsSnapshot (which only exposes .get()/.has()). */\n function createSnapshot(): Record<string, unknown> {\n return store.toObject();\n }\n\n /** Reset dep stability so the next run re-tracks via withTracking() */\n function resetStability(state: EffectState): void {\n state.depsStable = false;\n state.stableRunCount = 0;\n }\n\n /** Check whether any dependency overlaps with the changed keys */\n function hasOverlap(deps: Set<string>, changedKeys: Set<string>): boolean {\n for (const dep of deps) {\n if (changedKeys.has(dep)) {\n return true;\n }\n }\n\n return false;\n }\n\n /** Check if an effect should run based on changed keys */\n function shouldRun(id: string, changedKeys: Set<string>): boolean {\n const state = getState(id);\n if (!state.enabled) {\n return false;\n }\n\n // If effect has tracked deps (explicit or auto-tracked), check if any changed\n if (state.dependencies) {\n if (!hasOverlap(state.dependencies, changedKeys)) {\n return false;\n }\n\n // Reset dep stability when a tracked fact changes so the next run\n // re-tracks via withTracking() and can discover new conditional reads.\n if (state.depsStable) {\n resetStability(state);\n }\n\n return true;\n }\n\n // No deps yet (first run or auto-tracked with no reads) = run on any change\n return true;\n }\n\n /** Run cleanup for a single effect (safe — catches errors) */\n function runCleanup(state: EffectState): void {\n if (state.cleanup) {\n try {\n state.cleanup();\n } catch (error) {\n onError?.(state.id, error);\n console.error(\n `[Directive] Effect \"${state.id}\" cleanup threw an error:`,\n error,\n );\n }\n state.cleanup = null;\n }\n }\n\n /** Store a cleanup function if the effect returned one */\n function storeCleanup(state: EffectState, result: unknown): void {\n if (typeof result === \"function\") {\n if (stopped) {\n // System already stopped — invoke cleanup immediately so it's not lost\n try {\n (result as () => void)();\n } catch (error) {\n onError?.(state.id, error);\n console.error(\n `[Directive] Effect \"${state.id}\" cleanup threw an error:`,\n error,\n );\n }\n } else {\n state.cleanup = result as () => void;\n }\n }\n }\n\n /** Run the effect's `run()` inside a store.batch(), await if needed, and store cleanup */\n async function runBatchedEffect(\n state: EffectState,\n def: EffectsDef<S>[string],\n ): Promise<void> {\n let effectPromise: unknown;\n store.batch(() => {\n effectPromise = def.run(facts, previousSnapshot as InferSchema<S> | null);\n });\n if (effectPromise instanceof Promise) {\n const result = await effectPromise;\n storeCleanup(state, result);\n } else {\n storeCleanup(state, effectPromise);\n }\n }\n\n /** Check whether two dep sets are identical */\n function areDepsEqual(a: Set<string>, b: Set<string>): boolean {\n if (a.size !== b.size) {\n return false;\n }\n for (const dep of b) {\n if (!a.has(dep)) {\n return false;\n }\n }\n\n return true;\n }\n\n /** Check whether tracked deps match current deps and update stability counters */\n function updateDepStability(\n state: EffectState,\n trackedDeps: Set<string>,\n ): void {\n const same =\n state.dependencies && areDepsEqual(state.dependencies, trackedDeps);\n\n if (!same) {\n resetStability(state);\n\n return;\n }\n\n state.stableRunCount++;\n if (state.stableRunCount >= STABLE_THRESHOLD) {\n state.depsStable = true;\n }\n }\n\n /** Run an auto-tracked effect, re-tracking dependencies each time */\n async function runAutoTrackedEffect(\n state: EffectState,\n def: EffectsDef<S>[string],\n ): Promise<void> {\n // Deps have been stable — skip withTracking() overhead\n if (state.depsStable && state.dependencies) {\n await runBatchedEffect(state, def);\n\n return;\n }\n\n // Re-track dependencies so conditional reads are picked up\n let effectPromise: unknown;\n const trackingResult = withTracking(() => {\n store.batch(() => {\n effectPromise = def.run(\n facts,\n previousSnapshot as InferSchema<S> | null,\n );\n });\n return effectPromise;\n });\n const trackedDeps = trackingResult.deps;\n\n // If the effect is async, wait for it and capture cleanup\n let result = trackingResult.value;\n if (result instanceof Promise) {\n result = await result;\n }\n storeCleanup(state, result);\n\n updateDepStability(state, trackedDeps);\n\n // Update tracked dependencies\n state.dependencies = trackedDeps.size > 0 ? trackedDeps : null;\n }\n\n /** Run a single effect */\n async function runEffect(id: string): Promise<void> {\n const state = getState(id);\n const def = definitions[id];\n\n if (!state.enabled || !def) return;\n\n // Run previous cleanup before re-running\n runCleanup(state);\n\n onRun?.(id, state.dependencies ? [...state.dependencies] : []);\n\n try {\n if (!state.hasExplicitDeps) {\n await runAutoTrackedEffect(state, def);\n } else {\n await runBatchedEffect(state, def);\n }\n } catch (error) {\n // Effects are fire-and-forget - errors are reported but don't propagate\n onError?.(id, error);\n console.error(`[Directive] Effect \"${id}\" threw an error:`, error);\n // Reset dep stability — we don't know what the effect would have read\n if (!state.hasExplicitDeps) {\n resetStability(state);\n }\n }\n }\n\n // Initialize all effect states\n for (const id of Object.keys(definitions)) {\n initState(id);\n }\n\n const manager: EffectsManager<S> = {\n async runEffects(changedKeys: Set<string>): Promise<void> {\n const effectsToRun: string[] = [];\n\n for (const id of Object.keys(definitions)) {\n if (shouldRun(id, changedKeys)) {\n effectsToRun.push(id);\n }\n }\n\n // Run effects in parallel (they're independent)\n await Promise.all(effectsToRun.map(runEffect));\n\n // Update previous snapshot\n previousSnapshot = createSnapshot();\n },\n\n async runAll(): Promise<void> {\n const effectIds = Object.keys(definitions);\n await Promise.all(\n effectIds.map((id) => {\n const state = getState(id);\n if (state.enabled) {\n // Reset stability so runEffect re-tracks deps\n // (runAll bypasses shouldRun where the normal reset lives)\n resetStability(state);\n\n return runEffect(id);\n }\n return Promise.resolve();\n }),\n );\n\n // Update previous snapshot\n previousSnapshot = createSnapshot();\n },\n\n disable(id: string): void {\n const state = getState(id);\n state.enabled = false;\n },\n\n enable(id: string): void {\n const state = getState(id);\n state.enabled = true;\n },\n\n isEnabled(id: string): boolean {\n return getState(id).enabled;\n },\n\n cleanupAll(): void {\n stopped = true;\n for (const state of states.values()) {\n runCleanup(state);\n }\n },\n\n registerDefinitions(newDefs: EffectsDef<S>): void {\n for (const [key, def] of Object.entries(newDefs)) {\n (definitions as Record<string, unknown>)[key] = def;\n initState(key);\n }\n },\n\n assignDefinition(id: string, def: EffectsDef<S>[string]): void {\n if (!definitions[id]) {\n throw new Error(\n `[Directive] Cannot assign effect \"${id}\" — it does not exist. Use register() to create it.`,\n );\n }\n\n // Run cleanup of old effect before replacing\n const state = states.get(id);\n if (state) {\n runCleanup(state);\n }\n\n // Replace definition and re-init state\n (definitions as Record<string, unknown>)[id] = def;\n initState(id);\n },\n\n unregisterDefinition(id: string): void {\n if (!definitions[id]) {\n return;\n }\n\n // Run cleanup (try-catch inside runCleanup)\n const state = states.get(id);\n if (state) {\n runCleanup(state);\n }\n\n // Remove from all maps\n delete (definitions as Record<string, unknown>)[id];\n states.delete(id);\n },\n\n async callOne(id: string): Promise<void> {\n const def = definitions[id];\n if (!def) {\n throw new Error(\n `[Directive] Cannot call effect \"${id}\" — it does not exist.`,\n );\n }\n\n const state = getState(id);\n if (!state.enabled) {\n return;\n }\n\n // Run cleanup of previous run\n runCleanup(state);\n\n onRun?.(id, state.dependencies ? [...state.dependencies] : []);\n\n try {\n let effectPromise: unknown;\n store.batch(() => {\n effectPromise = def.run(\n facts,\n previousSnapshot as InferSchema<S> | null,\n );\n });\n if (effectPromise instanceof Promise) {\n const result = await effectPromise;\n storeCleanup(state, result);\n } else {\n storeCleanup(state, effectPromise);\n }\n } catch (error) {\n onError?.(id, error);\n console.error(`[Directive] Effect \"${id}\" threw an error:`, error);\n }\n },\n };\n\n return 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 DirectiveError,\n type ErrorBoundaryConfig,\n type ErrorSource,\n type RecoveryStrategy,\n type RetryLaterConfig,\n} from \"./types.js\";\n\n// ============================================================================\n// Retry-Later Queue\n// ============================================================================\n\n/**\n * A queued retry entry tracking its source, attempt count, and scheduled time.\n *\n * @internal\n */\nexport interface PendingRetry {\n source: ErrorSource;\n sourceId: string;\n context: unknown;\n attempt: number;\n nextRetryTime: number;\n callback?: () => void;\n}\n\n/**\n * Create a manager for deferred retry scheduling with exponential backoff.\n *\n * @remarks\n * Retries are stored in a Map keyed by source ID. Each entry tracks its\n * attempt number and the timestamp of the next eligible retry. When\n * {@link createRetryLaterManager | processDueRetries} is called (typically\n * during reconciliation), entries whose scheduled time has elapsed are\n * returned and removed from the queue. The delay grows exponentially:\n * `delayMs * backoffMultiplier^(attempt - 1)`, capped at `maxDelayMs`.\n *\n * @param config - Backoff configuration including `delayMs`, `maxRetries`, `backoffMultiplier`, and `maxDelayMs`.\n * @returns A manager exposing `scheduleRetry`, `getPendingRetries`, `processDueRetries`, `cancelRetry`, and `clearAll` methods.\n *\n * @internal\n */\nexport function createRetryLaterManager(config: RetryLaterConfig = {}): {\n /** Schedule a retry */\n scheduleRetry: (\n source: ErrorSource,\n sourceId: string,\n context: unknown,\n attempt: number,\n callback?: () => void,\n ) => PendingRetry | null;\n /** Get pending retries */\n getPendingRetries: () => PendingRetry[];\n /** Process due retries */\n processDueRetries: () => PendingRetry[];\n /** Cancel a retry */\n cancelRetry: (sourceId: string) => void;\n /** Clear all pending retries */\n clearAll: () => void;\n} {\n const {\n delayMs = 1000,\n maxRetries = 3,\n backoffMultiplier = 2,\n maxDelayMs = 30000,\n } = config;\n\n const pendingRetries: Map<string, PendingRetry> = new Map();\n\n function calculateDelay(attempt: number): number {\n const delay = delayMs * backoffMultiplier ** (attempt - 1);\n return Math.min(delay, maxDelayMs);\n }\n\n return {\n scheduleRetry(\n source: ErrorSource,\n sourceId: string,\n context: unknown,\n attempt: number,\n callback?: () => void,\n ): PendingRetry | null {\n // Check if max retries exceeded\n if (attempt > maxRetries) {\n return null;\n }\n\n const delay = calculateDelay(attempt);\n const entry: PendingRetry = {\n source,\n sourceId,\n context,\n attempt,\n nextRetryTime: Date.now() + delay,\n callback,\n };\n\n pendingRetries.set(sourceId, entry);\n return entry;\n },\n\n getPendingRetries(): PendingRetry[] {\n return Array.from(pendingRetries.values());\n },\n\n processDueRetries(): PendingRetry[] {\n const now = Date.now();\n const dueRetries: PendingRetry[] = [];\n\n for (const [sourceId, entry] of pendingRetries) {\n if (entry.nextRetryTime <= now) {\n dueRetries.push(entry);\n pendingRetries.delete(sourceId);\n }\n }\n\n return dueRetries;\n },\n\n cancelRetry(sourceId: string): void {\n pendingRetries.delete(sourceId);\n },\n\n clearAll(): void {\n pendingRetries.clear();\n },\n };\n}\n\n// ============================================================================\n// Error Boundary Manager\n// ============================================================================\n\n/**\n * Handle returned by {@link createErrorBoundaryManager} for routing errors\n * through configurable recovery strategies.\n *\n * @internal\n */\nexport interface ErrorBoundaryManager {\n /**\n * Route an error through the configured recovery strategy for its source.\n *\n * @param source - The subsystem that produced the error.\n * @param sourceId - Identifier of the specific constraint, resolver, effect, or derivation.\n * @param error - The thrown value (coerced to {@link DirectiveError} internally).\n * @param context - Optional context forwarded to callbacks and retry entries.\n * @returns The {@link RecoveryStrategy} that was applied.\n */\n handleError(\n source: ErrorSource,\n sourceId: string,\n error: unknown,\n context?: unknown,\n ): RecoveryStrategy;\n /**\n * Return the most recently recorded error, or `null` if none exist.\n *\n * @returns The last {@link DirectiveError}, or `null`.\n */\n getLastError(): DirectiveError | null;\n /**\n * Return a snapshot array of all recorded errors (up to the last 100).\n *\n * @returns A shallow copy of the internal error ring buffer.\n */\n getAllErrors(): DirectiveError[];\n /** Clear all recorded errors. */\n clearErrors(): void;\n /**\n * Access the underlying retry-later manager for advanced scheduling.\n *\n * @returns The {@link createRetryLaterManager} instance used internally.\n */\n getRetryLaterManager(): ReturnType<typeof createRetryLaterManager>;\n /**\n * Drain and return retry entries whose scheduled time has elapsed.\n *\n * @returns An array of {@link PendingRetry} entries that are now due.\n */\n processDueRetries(): PendingRetry[];\n /**\n * Reset retry attempt tracking for a source, typically after a successful resolution.\n *\n * @param sourceId - The source identifier whose retry counter should be cleared.\n */\n clearRetryAttempts(sourceId: string): void;\n}\n\n/**\n * Options accepted by {@link createErrorBoundaryManager}.\n *\n * @internal\n */\nexport interface CreateErrorBoundaryOptions {\n /** Per-source recovery strategies and retry-later tuning. */\n config?: ErrorBoundaryConfig;\n /** Invoked every time an error is recorded, before the recovery strategy runs. */\n onError?: (error: DirectiveError) => void;\n /** Invoked after a recovery strategy has been selected for an error. */\n onRecovery?: (error: DirectiveError, strategy: RecoveryStrategy) => void;\n}\n\n/** Default recovery strategies by source */\nconst DEFAULT_STRATEGIES: Record<ErrorSource, RecoveryStrategy> = {\n constraint: \"skip\",\n resolver: \"skip\",\n effect: \"skip\",\n derivation: \"skip\",\n system: \"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 * @remarks\n * Five recovery strategies are available:\n *\n * - `\"skip\"` -- Swallow the error and continue.\n * - `\"retry\"` -- Signal the caller to retry immediately.\n * - `\"retry-later\"` -- Enqueue a deferred retry with exponential backoff\n * (delegated to an internal {@link createRetryLaterManager}).\n * - `\"disable\"` -- Permanently disable the failing source.\n * - `\"throw\"` -- Re-throw the error as a {@link DirectiveError}.\n *\n * Recent errors are kept in a ring buffer (last 100) for inspection via\n * {@link ErrorBoundaryManager.getAllErrors | getAllErrors}. Each strategy\n * can be configured per source type (`onConstraintError`, `onResolverError`,\n * etc.) or as a callback that dynamically selects a strategy.\n *\n * @param options - Error boundary configuration, plus `onError` and `onRecovery` callbacks for plugin integration.\n * @returns An {@link ErrorBoundaryManager} for routing errors through the configured strategies.\n *\n * @internal\n */\nexport function createErrorBoundaryManager(\n options: CreateErrorBoundaryOptions = {},\n): ErrorBoundaryManager {\n const { config = {}, onError, onRecovery } = options;\n\n // Store errors for inspection\n const errors: DirectiveError[] = [];\n const maxErrors = 100; // Keep last 100 errors\n\n // Retry-later manager\n const retryLaterManager = createRetryLaterManager(config.retryLater);\n\n // Track retry attempts per source ID (capped to prevent unbounded growth)\n const retryAttempts = new Map<string, number>();\n const MAX_RETRY_SOURCES = 1000;\n\n /** Convert unknown error to DirectiveError */\n function toDirectiveError(\n source: ErrorSource,\n sourceId: string,\n error: unknown,\n context?: unknown,\n ): DirectiveError {\n if (error instanceof DirectiveError) {\n return error;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n const recoverable = source !== \"system\";\n\n return new DirectiveError(message, source, sourceId, context, recoverable);\n }\n\n /** Get recovery strategy for a source */\n function getStrategy(\n source: ErrorSource,\n sourceId: string,\n error: Error,\n ): RecoveryStrategy {\n // Get configured handler\n const handler = (() => {\n switch (source) {\n case \"constraint\":\n return config.onConstraintError;\n case \"resolver\":\n return config.onResolverError;\n case \"effect\":\n return config.onEffectError;\n case \"derivation\":\n return config.onDerivationError;\n default:\n return undefined;\n }\n })();\n\n // If handler is a function, call it — use returned strategy if provided, else \"skip\"\n if (typeof handler === \"function\") {\n try {\n const result = handler(error, sourceId);\n\n if (typeof result === \"string\") {\n return result as RecoveryStrategy;\n }\n } catch (e) {\n console.error(\"[Directive] Error in error handler callback:\", e);\n }\n\n return \"skip\";\n }\n\n // If handler is a strategy string, return it\n if (typeof handler === \"string\") {\n return handler;\n }\n\n // Return default strategy\n return DEFAULT_STRATEGIES[source];\n }\n\n /** Store error in ring buffer and notify error callbacks */\n function recordAndNotifyError(directiveError: DirectiveError): void {\n errors.push(directiveError);\n if (errors.length > maxErrors) {\n errors.shift();\n }\n\n try {\n onError?.(directiveError);\n } catch (e) {\n console.error(\"[Directive] Error in onError callback:\", e);\n }\n try {\n config.onError?.(directiveError);\n } catch (e) {\n console.error(\"[Directive] Error in config.onError callback:\", e);\n }\n }\n\n /** Process retry-later strategy: schedule retry or fall back to skip */\n function processRetryLater(\n source: ErrorSource,\n sourceId: string,\n context: unknown,\n ): RecoveryStrategy {\n const attempt = (retryAttempts.get(sourceId) ?? 0) + 1;\n retryAttempts.set(sourceId, attempt);\n\n // FIFO eviction to prevent unbounded growth\n if (retryAttempts.size > MAX_RETRY_SOURCES) {\n const oldest = retryAttempts.keys().next().value;\n if (oldest !== undefined) {\n retryAttempts.delete(oldest);\n }\n }\n\n const scheduled = retryLaterManager.scheduleRetry(\n source,\n sourceId,\n context,\n attempt,\n );\n\n if (scheduled) {\n return \"retry-later\";\n }\n\n // Max retries exceeded, fall back to skip\n retryAttempts.delete(sourceId);\n if (\n typeof process !== \"undefined\" &&\n process.env?.NODE_ENV !== \"production\"\n ) {\n console.warn(\n `[Directive] ${source} \"${sourceId}\" exceeded max retry-later attempts. Skipping.`,\n );\n }\n\n return \"skip\";\n }\n\n const manager: ErrorBoundaryManager = {\n handleError(\n source: ErrorSource,\n sourceId: string,\n error: unknown,\n context?: unknown,\n ): RecoveryStrategy {\n const directiveError = toDirectiveError(source, sourceId, error, context);\n\n recordAndNotifyError(directiveError);\n\n // Get recovery strategy\n let strategy = getStrategy(\n source,\n sourceId,\n error instanceof Error ? error : new Error(String(error)),\n );\n\n // Handle retry-later strategy\n if (strategy === \"retry-later\") {\n strategy = processRetryLater(source, sourceId, context);\n }\n\n // Notify recovery callback\n try {\n onRecovery?.(directiveError, strategy);\n } catch (e) {\n console.error(\"[Directive] Error in onRecovery callback:\", e);\n }\n\n // If strategy is throw, re-throw the error\n if (strategy === \"throw\") {\n throw directiveError;\n }\n\n return strategy;\n },\n\n getLastError(): DirectiveError | null {\n return errors[errors.length - 1] ?? null;\n },\n\n getAllErrors(): DirectiveError[] {\n return [...errors];\n },\n\n clearErrors(): void {\n errors.length = 0;\n },\n\n getRetryLaterManager() {\n return retryLaterManager;\n },\n\n processDueRetries(): PendingRetry[] {\n return retryLaterManager.processDueRetries();\n },\n\n clearRetryAttempts(sourceId: string): void {\n retryAttempts.delete(sourceId);\n retryLaterManager.cancelRetry(sourceId);\n },\n };\n\n return manager;\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 { BLOCKED_PROPS, trackAccess, withoutTracking } from \"./tracking.js\";\nimport type {\n Facts,\n FactsSnapshot,\n FactsStore,\n InferSchema,\n Schema,\n} from \"./types.js\";\n\n/** Safely stringify a value for error messages */\nfunction safeStringify(value: unknown, maxLength = 100): string {\n try {\n return JSON.stringify(value)?.slice(0, maxLength) ?? String(value);\n } catch {\n return \"[circular or non-serializable]\";\n }\n}\n\n// ============================================================================\n// Facts Store Implementation\n// ============================================================================\n\n/** Options for creating a facts store */\nexport interface CreateFactsStoreOptions<S extends Schema> {\n schema: S;\n /** Validate values against schema (default: process.env.NODE_ENV !== 'production') */\n validate?: boolean;\n /** Throw on unknown schema keys (default: true in dev mode) */\n strictKeys?: boolean;\n /** Redact sensitive values in error messages */\n redactErrors?: boolean;\n /** Callback when facts change (for plugin hooks) */\n onChange?: (key: string, value: unknown, prev: unknown) => void;\n /** Callback for batch changes */\n onBatch?: (\n changes: Array<{\n key: string;\n value: unknown;\n prev: unknown;\n type: \"set\" | \"delete\";\n }>,\n ) => 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 * @remarks\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 {@link FactsStore} 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 *\n * @internal\n */\nexport function createFactsStore<S extends Schema>(\n options: CreateFactsStoreOptions<S>,\n): FactsStore<S> {\n const { schema, onChange, onBatch } = options;\n\n // Detect if this is a type assertion schema (empty object with no keys)\n const schemaKeys = Object.keys(schema);\n const isTypeAssertionSchema = schemaKeys.length === 0;\n\n // Default strictKeys to false for type assertion schemas (they have no runtime keys)\n const validate = options.validate ?? process.env.NODE_ENV !== \"production\";\n const strictKeys =\n options.strictKeys ??\n (process.env.NODE_ENV !== \"production\" && !isTypeAssertionSchema);\n const redactErrors = options.redactErrors ?? false;\n\n const map = new Map<string, unknown>();\n const knownKeys = new Set<string>(); // Track all keys that have been set\n const keyListeners = new Map<string, Set<() => void>>();\n const allListeners = new Set<() => void>();\n\n let batching = 0;\n const batchChanges: Array<{\n key: string;\n value: unknown;\n prev: unknown;\n type: \"set\" | \"delete\";\n }> = [];\n const dirtyKeys = new Set<string>();\n\n // Notification coalescing: when notifyKey/notifyAll fires a listener that\n // calls store.set(), defer the new notification until the current cycle completes.\n let isNotifying = false;\n const pendingNonBatchedChanges: Array<{\n key: string;\n value: unknown;\n prev: unknown;\n }> = [];\n const MAX_NOTIFY_ITERATIONS = 100;\n\n /** Check if a value is a Zod schema (robust detection) */\n function isZodSchema(v: unknown): v is {\n safeParse: (v: unknown) => {\n success: boolean;\n error?: { message?: string; issues?: Array<{ message: string }> };\n };\n _def: unknown;\n parse: unknown;\n } {\n return (\n v !== null &&\n typeof v === \"object\" &&\n \"safeParse\" in v &&\n typeof (v as Record<string, unknown>).safeParse === \"function\" &&\n \"_def\" in v &&\n \"parse\" in v &&\n typeof (v as Record<string, unknown>).parse === \"function\"\n );\n }\n\n /** Get expected type name from schema */\n function getExpectedType(schemaType: unknown): string {\n // Check for our SchemaType with _typeName\n const st = schemaType as { _typeName?: string };\n if (st._typeName) {\n return st._typeName;\n }\n\n // Check for Zod schema\n if (isZodSchema(schemaType)) {\n const def = (schemaType as { _def?: { typeName?: string } })._def;\n if (def?.typeName) {\n // Convert ZodString -> string, ZodNumber -> number, etc.\n return def.typeName.replace(/^Zod/, \"\").toLowerCase();\n }\n }\n\n return \"unknown\";\n }\n\n /** Format value for error message, respecting redactErrors option */\n function formatValueForError(value: unknown): string {\n if (redactErrors) {\n return \"[redacted]\";\n }\n return safeStringify(value);\n }\n\n /** Get a human-readable type label for a value */\n function describeValueType(value: unknown): string {\n if (value === null) {\n return \"null\";\n }\n if (Array.isArray(value)) {\n return \"array\";\n }\n\n return typeof value;\n }\n\n /** Validate a value against a Zod schema */\n function validateZod(\n key: string,\n value: unknown,\n schemaType: ReturnType<\n typeof isZodSchema extends (v: unknown) => v is infer R ? () => R : never\n >,\n ): void {\n const result = (\n schemaType as {\n safeParse: (v: unknown) => {\n success: boolean;\n error?: { message?: string; issues?: Array<{ message: string }> };\n };\n }\n ).safeParse(value);\n if (result.success) {\n return;\n }\n\n const valueType = describeValueType(value);\n const valuePreview = formatValueForError(value);\n const errorMessage =\n result.error?.message ??\n result.error?.issues?.[0]?.message ??\n \"Validation failed\";\n const expectedType = getExpectedType(schemaType);\n throw new Error(\n `[Directive] Validation failed for \"${key}\": expected ${expectedType}, got ${valueType} ${valuePreview}. ${errorMessage}`,\n );\n }\n\n /** Build the index hint string for array validation failures */\n function getIndexHint(st: { _lastFailedIndex?: number }): string {\n if (typeof st._lastFailedIndex === \"number\" && st._lastFailedIndex >= 0) {\n const hint = ` (element at index ${st._lastFailedIndex} failed)`;\n st._lastFailedIndex = -1; // Reset for next validation\n return hint;\n }\n\n return \"\";\n }\n\n /** Validate a value against our SchemaType validators */\n function validateSchemaType(\n key: string,\n value: unknown,\n st: {\n _validators?: unknown;\n _typeName?: string;\n _lastFailedIndex?: number;\n },\n ): void {\n const validators = st._validators;\n\n // Ensure validators is an array before iterating\n if (!validators || !Array.isArray(validators) || validators.length === 0) {\n return; // type assertion or empty validators - no validation\n }\n\n const expectedType = st._typeName ?? \"unknown\";\n\n for (let i = 0; i < validators.length; i++) {\n const validator = validators[i];\n if (typeof validator !== \"function\") continue;\n if (validator(value as never)) continue;\n\n const valueType = describeValueType(value);\n const valuePreview = formatValueForError(value);\n const indexHint = getIndexHint(st);\n const validatorHint = i === 0 ? \"\" : ` (validator ${i + 1} failed)`;\n throw new Error(\n `[Directive] Validation failed for \"${key}\": expected ${expectedType}, got ${valueType} ${valuePreview}${validatorHint}${indexHint}`,\n );\n }\n }\n\n /** Validate unknown schema key */\n function validateUnknownKey(key: string): void {\n if (strictKeys) {\n throw new Error(\n `[Directive] Unknown fact key: \"${key}\". Key not defined in schema.`,\n );\n }\n console.warn(`[Directive] Unknown fact key: \"${key}\"`);\n }\n\n /** Validate a value against the schema */\n function validateValue(key: string, value: unknown): void {\n if (!validate) {\n return;\n }\n\n const schemaType = schema[key];\n if (!schemaType) {\n validateUnknownKey(key);\n return;\n }\n\n if (isZodSchema(schemaType)) {\n validateZod(key, value, schemaType);\n return;\n }\n\n validateSchemaType(\n key,\n value,\n schemaType as {\n _validators?: unknown;\n _typeName?: string;\n _lastFailedIndex?: number;\n },\n );\n }\n\n /** Notify listeners for a specific key */\n function notifyKey(key: string): void {\n keyListeners.get(key)?.forEach((listener) => listener());\n }\n\n /** Notify all listeners */\n function notifyAll(): void {\n allListeners.forEach((listener) => listener());\n }\n\n /**\n * Run non-batched notifications with coalescing.\n * If a listener calls store.set(), the change is deferred and processed\n * after the current notification cycle completes.\n */\n function notifyNonBatched(key: string, value: unknown, prev: unknown): void {\n if (isNotifying) {\n // Re-entrant: defer to after current notification cycle\n pendingNonBatchedChanges.push({ key, value, prev });\n return;\n }\n\n isNotifying = true;\n try {\n // Fire onChange, notifyKey, notifyAll for the initial change\n onChange?.(key, value, prev);\n notifyKey(key);\n notifyAll();\n\n // Process any changes that were deferred during notification\n drainDeferredNotifications(\n \". A listener is repeatedly mutating facts that re-trigger notifications\",\n );\n } finally {\n isNotifying = false;\n }\n }\n\n /**\n * Drain deferred notifications that accumulated during a notification cycle.\n * Must be called while isNotifying is true.\n */\n function drainDeferredNotifications(context: string): void {\n let iterations = 0;\n while (pendingNonBatchedChanges.length > 0) {\n if (++iterations > MAX_NOTIFY_ITERATIONS) {\n pendingNonBatchedChanges.length = 0;\n throw new Error(\n `[Directive] Infinite notification loop detected after ${MAX_NOTIFY_ITERATIONS} iterations${context}.`,\n );\n }\n\n const deferred = [...pendingNonBatchedChanges];\n pendingNonBatchedChanges.length = 0;\n\n for (const change of deferred) {\n onChange?.(change.key, change.value, change.prev);\n notifyKey(change.key);\n }\n notifyAll();\n }\n }\n\n /** Flush batched changes and notify */\n function flush(): void {\n if (batching > 0) {\n return;\n }\n\n // Notify batch callback\n if (onBatch && batchChanges.length > 0) {\n onBatch([...batchChanges]);\n }\n\n // Notify key-specific listeners (within coalescing guard)\n if (dirtyKeys.size > 0) {\n isNotifying = true;\n try {\n for (const key of dirtyKeys) {\n notifyKey(key);\n }\n notifyAll();\n drainDeferredNotifications(\" during flush\");\n } finally {\n isNotifying = false;\n }\n }\n\n // Clear batch state\n batchChanges.length = 0;\n dirtyKeys.clear();\n }\n\n const store: FactsStore<S> = {\n get<K extends keyof InferSchema<S>>(key: K): InferSchema<S>[K] | undefined {\n // Track access for auto-tracking\n trackAccess(key as string);\n return map.get(key as string) as InferSchema<S>[K] | undefined;\n },\n\n has(key: keyof InferSchema<S>): boolean {\n // Track access for auto-tracking\n trackAccess(key as string);\n return map.has(key as string);\n },\n\n set<K extends keyof InferSchema<S>>(\n key: K,\n value: InferSchema<S>[K],\n ): void {\n validateValue(key as string, value);\n\n const prev = map.get(key as string);\n\n // Skip if value hasn't changed (prevents unnecessary cascade)\n if (Object.is(prev, value)) return;\n\n map.set(key as string, value);\n knownKeys.add(key as string); // Track known keys for serialization\n\n // Record change\n if (batching > 0) {\n batchChanges.push({ key: key as string, value, prev, type: \"set\" });\n dirtyKeys.add(key as string);\n } else {\n notifyNonBatched(key as string, value, prev);\n }\n },\n\n delete(key: keyof InferSchema<S>): void {\n const prev = map.get(key as string);\n map.delete(key as string);\n knownKeys.delete(key as string); // Remove from known keys\n\n // Record change\n if (batching > 0) {\n batchChanges.push({\n key: key as string,\n value: undefined,\n prev,\n type: \"delete\",\n });\n dirtyKeys.add(key as string);\n } else {\n notifyNonBatched(key as string, undefined, prev);\n }\n },\n\n batch(fn: () => void): void {\n batching++;\n try {\n fn();\n } finally {\n batching--;\n flush();\n }\n },\n\n subscribe(\n keys: Array<keyof InferSchema<S>>,\n listener: () => void,\n ): () => void {\n for (const key of keys) {\n const keyStr = key as string;\n if (!keyListeners.has(keyStr)) {\n keyListeners.set(keyStr, new Set());\n }\n keyListeners.get(keyStr)!.add(listener);\n }\n\n return () => {\n for (const key of keys) {\n const set = keyListeners.get(key as string);\n if (set) {\n set.delete(listener);\n if (set.size === 0) {\n keyListeners.delete(key as string);\n }\n }\n }\n };\n },\n\n subscribeAll(listener: () => void): () => void {\n allListeners.add(listener);\n return () => allListeners.delete(listener);\n },\n\n toObject(): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const key of knownKeys) {\n if (map.has(key)) {\n result[key] = map.get(key);\n }\n }\n return result;\n },\n };\n\n // Internal: clear all listeners on destroy to release resources immediately.\n // Not part of the public FactsStore interface — called by engine.destroy().\n (store as unknown as Record<string, unknown>).destroy = () => {\n keyListeners.clear();\n allListeners.clear();\n };\n\n // Internal: register new schema keys for dynamic module registration.\n // Not part of the public FactsStore interface — used by engine.registerModule().\n (store as unknown as Record<string, unknown>).registerKeys = (\n newSchema: Record<string, unknown>,\n ) => {\n for (const key of Object.keys(newSchema)) {\n // Defense-in-depth: skip prototype pollution keys\n if (BLOCKED_PROPS.has(key)) continue;\n // Add to schema for validation\n (schema as Record<string, unknown>)[key] = newSchema[key];\n knownKeys.add(key);\n }\n };\n\n return store;\n}\n\n// ============================================================================\n// Dev-mode nested mutation warning\n// ============================================================================\n\nconst nestedProxyCache = new WeakMap<object, object>();\n\n/**\n * Wrap an object in a Proxy that warns when properties are set.\n * Catches `facts.user.name = \"John\"` which silently skips reactivity.\n * Only used in dev mode — tree-shaken in production builds.\n */\nfunction wrapWithNestedWarning(\n obj: object,\n rootKey: string,\n path = rootKey,\n): object {\n return new Proxy(obj, {\n get(target, prop) {\n if (typeof prop === \"string\" && BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n const value = Reflect.get(target, prop);\n if (\n typeof prop === \"symbol\" ||\n typeof value !== \"object\" ||\n value === null\n ) {\n return value;\n }\n\n if (nestedProxyCache.has(value as object)) {\n return nestedProxyCache.get(value as object);\n }\n\n const wrapped = wrapWithNestedWarning(\n value as object,\n rootKey,\n `${path}.${String(prop)}`,\n );\n nestedProxyCache.set(value as object, wrapped);\n\n return wrapped;\n },\n set(target, prop, newValue) {\n if (typeof prop !== \"symbol\") {\n console.warn(\n `[Directive] Nested mutation on \"facts.${path}.${String(prop)}\" will not trigger reactivity. ` +\n `Use: facts.${rootKey} = { ...facts.${rootKey}, ... }`,\n );\n }\n\n return Reflect.set(target, prop, newValue);\n },\n });\n}\n\n// ============================================================================\n// Proxy-based Facts Accessor\n// ============================================================================\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 * @remarks\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 {@link Facts} proxy with property-style get/set and prototype pollution guards\n *\n * @example\n * ```ts\n * const store = createFactsStore({ schema: { phase: t.string() } });\n * const facts = createFactsProxy(store, { phase: t.string() });\n *\n * facts.phase = \"red\";\n * console.log(facts.phase); // \"red\"\n * ```\n *\n * @internal\n */\nexport function createFactsProxy<S extends Schema>(\n store: FactsStore<S>,\n schema: S,\n): Facts<S> {\n const snapshot = (): FactsSnapshot<S> => ({\n get: <K extends keyof InferSchema<S>>(key: K) =>\n withoutTracking(() => store.get(key)),\n has: (key: keyof InferSchema<S>) => withoutTracking(() => store.has(key)),\n });\n\n const proxy = new Proxy({} as Facts<S>, {\n get(_, prop: string | symbol) {\n if (prop === \"$store\") {\n return store;\n }\n if (prop === \"$snapshot\") {\n return snapshot;\n }\n\n // Special properties\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n\n // Prototype pollution protection\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n\n const value = store.get(prop as keyof InferSchema<S>);\n\n // Dev-mode: warn when users mutate nested objects (won't trigger reactivity)\n if (\n process.env.NODE_ENV !== \"production\" &&\n value !== null &&\n typeof value === \"object\"\n ) {\n return wrapWithNestedWarning(value as object, prop);\n }\n\n return value;\n },\n\n set(_, prop: string | symbol, value: unknown) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (prop === \"$store\" || prop === \"$snapshot\") {\n return false;\n }\n // Prototype pollution protection\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n // Validation is handled by store.set() when validate option is enabled\n store.set(\n prop as keyof InferSchema<S>,\n value as InferSchema<S>[keyof InferSchema<S>],\n );\n return true;\n },\n\n deleteProperty(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (prop === \"$store\" || prop === \"$snapshot\") {\n return false;\n }\n // Prototype pollution protection\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n store.delete(prop as keyof InferSchema<S>);\n return true;\n },\n\n has(_, prop: string | symbol) {\n if (prop === \"$store\" || prop === \"$snapshot\") {\n return true;\n }\n if (typeof prop === \"symbol\") {\n return false;\n }\n // Prototype pollution protection\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return store.has(prop as keyof InferSchema<S>);\n },\n\n ownKeys() {\n // Return schema keys dynamically so Object.keys(facts) reflects\n // keys added via registerKeys (dynamic module registration)\n return Object.keys(schema);\n },\n\n getOwnPropertyDescriptor(_, prop: string | symbol) {\n if (prop === \"$store\" || prop === \"$snapshot\") {\n return { configurable: true, enumerable: false, writable: false };\n }\n return { configurable: true, enumerable: true, writable: true };\n },\n\n defineProperty() {\n return false;\n },\n\n getPrototypeOf() {\n return null;\n },\n\n setPrototypeOf() {\n return false;\n },\n });\n\n return 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 * @remarks\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 *\n * @internal\n */\nexport function createFacts<S extends Schema>(\n options: CreateFactsStoreOptions<S>,\n): { store: FactsStore<S>; facts: Facts<S> } {\n const store = createFactsStore(options);\n const facts = createFactsProxy(store, options.schema);\n return { store, facts };\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 FactChange,\n FactsSnapshot,\n Plugin,\n ReconcileResult,\n RecoveryStrategy,\n RequirementWithId,\n Schema,\n Snapshot,\n System,\n TraceEntry,\n} from \"./types.js\";\nimport type { DirectiveError } from \"./types.js\";\n\n// ============================================================================\n// Plugin Manager\n// ============================================================================\n\n/**\n * Internal manager that broadcasts lifecycle events to registered {@link Plugin} instances.\n *\n * @remarks\n * PluginManager uses `Schema` (flat) internally because the engine works with\n * flat schemas. The public API uses `ModuleSchema` (consolidated), and the\n * conversion happens in `createSystem`.\n *\n * Plugins execute in registration order. All hook invocations are wrapped in\n * try-catch so a misbehaving plugin never breaks the engine. Duplicate plugin\n * names are detected and the older registration is replaced with a warning.\n *\n * Lifecycle hook categories:\n * - **System lifecycle:** `emitInit`, `emitStart`, `emitStop`, `emitDestroy`\n * - **Facts:** `emitFactSet`, `emitFactDelete`, `emitFactsBatch`\n * - **Derivations:** `emitDerivationCompute`, `emitDerivationInvalidate`\n * - **Reconciliation:** `emitReconcileStart`, `emitReconcileEnd`\n * - **Constraints:** `emitConstraintEvaluate`, `emitConstraintError`\n * - **Requirements:** `emitRequirementCreated`, `emitRequirementMet`, `emitRequirementCanceled`\n * - **Resolvers:** `emitResolverStart`, `emitResolverComplete`, `emitResolverError`, `emitResolverRetry`, `emitResolverCancel`\n * - **Effects:** `emitEffectRun`, `emitEffectError`\n * - **History:** `emitSnapshot`, `emitHistoryNavigate`\n * - **Errors:** `emitError`, `emitErrorRecovery`\n * - **Trace:** `emitTraceComplete`\n *\n * @typeParam _S - The flat schema type (unused at runtime).\n *\n * @internal\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 /** Register a plugin */\n // biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n register(plugin: Plugin<any>): void;\n /** Unregister a plugin by name */\n unregister(name: string): void;\n /** Get all registered plugins */\n // biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n getPlugins(): Plugin<any>[];\n\n // Lifecycle hooks\n // biome-ignore lint/suspicious/noExplicitAny: System type varies between internal/public API\n emitInit(system: System<any>): Promise<void>;\n // biome-ignore lint/suspicious/noExplicitAny: System type varies between internal/public API\n emitStart(system: System<any>): void;\n // biome-ignore lint/suspicious/noExplicitAny: System type varies between internal/public API\n emitStop(system: System<any>): void;\n // biome-ignore lint/suspicious/noExplicitAny: System type varies between internal/public API\n emitDestroy(system: System<any>): void;\n\n // Fact hooks\n emitFactSet(key: string, value: unknown, prev: unknown): void;\n emitFactDelete(key: string, prev: unknown): void;\n emitFactsBatch(changes: FactChange[]): void;\n\n // Derivation hooks\n emitDerivationCompute(id: string, value: unknown, deps: string[]): void;\n emitDerivationInvalidate(id: string): void;\n\n // Reconciliation hooks\n // biome-ignore lint/suspicious/noExplicitAny: Schema type varies\n emitReconcileStart(snapshot: FactsSnapshot<any>): void;\n emitReconcileEnd(result: ReconcileResult): void;\n\n // Constraint hooks\n emitConstraintEvaluate(id: string, active: boolean): void;\n emitConstraintError(id: string, error: unknown): void;\n\n // Requirement hooks\n emitRequirementCreated(req: RequirementWithId): void;\n emitRequirementMet(req: RequirementWithId, byResolver: string): void;\n emitRequirementCanceled(req: RequirementWithId): void;\n\n // Resolver hooks\n emitResolverStart(resolver: string, req: RequirementWithId): void;\n emitResolverComplete(\n resolver: string,\n req: RequirementWithId,\n duration: number,\n ): void;\n emitResolverError(\n resolver: string,\n req: RequirementWithId,\n error: unknown,\n ): void;\n emitResolverRetry(\n resolver: string,\n req: RequirementWithId,\n attempt: number,\n ): void;\n emitResolverCancel(resolver: string, req: RequirementWithId): void;\n\n // Effect hooks\n emitEffectRun(id: string): void;\n emitEffectError(id: string, error: unknown): void;\n\n // History hooks\n emitSnapshot(snapshot: Snapshot): void;\n emitHistoryNavigate(from: number, to: number): void;\n\n // Error boundary hooks\n emitError(error: DirectiveError): void;\n emitErrorRecovery(error: DirectiveError, strategy: RecoveryStrategy): void;\n\n // Dynamic definition hooks\n emitDefinitionRegister(type: string, id: string, def: unknown): void;\n emitDefinitionAssign(\n type: string,\n id: string,\n def: unknown,\n original: unknown,\n ): void;\n emitDefinitionUnregister(type: string, id: string): void;\n emitDefinitionCall(type: string, id: string, props?: unknown): void;\n\n // Trace hooks\n emitTraceComplete(run: TraceEntry): void;\n}\n\n/**\n * Create a {@link PluginManager} that broadcasts lifecycle events to registered plugins.\n *\n * @remarks\n * Plugins are called in registration order. All hook invocations are wrapped\n * in try-catch so a misbehaving plugin never breaks the engine. Duplicate\n * plugin names are detected and the older registration is replaced with a\n * console warning.\n *\n * @returns A {@link PluginManager} with `register`/`unregister`/`getPlugins` and `emit*` methods for every lifecycle event.\n *\n * @internal\n */\nexport function createPluginManager<\n // biome-ignore lint/suspicious/noExplicitAny: Internal - schema type varies\n S extends Schema = any,\n>(): PluginManager<S> {\n // biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n const plugins: Plugin<any>[] = [];\n\n /** Safe call - wraps plugin hook calls to prevent errors from breaking the system */\n function safeCall<T>(fn: (() => T) | undefined): T | undefined {\n if (!fn) {\n return undefined;\n }\n try {\n return fn();\n } catch (error) {\n console.error(\"[Directive] Plugin error:\", error);\n return undefined;\n }\n }\n\n /** Safe async call */\n async function safeCallAsync<T>(\n fn: (() => Promise<T>) | undefined,\n ): Promise<T | undefined> {\n if (!fn) {\n return undefined;\n }\n try {\n return await fn();\n } catch (error) {\n console.error(\"[Directive] Plugin error:\", error);\n return undefined;\n }\n }\n\n /** Create a sync broadcast function for a given plugin hook name */\n // biome-ignore lint/suspicious/noExplicitAny: Plugin hook signatures vary\n function broadcast<K extends keyof Plugin<any>>(hook: K) {\n return (...args: unknown[]) => {\n for (const plugin of plugins) {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic hook dispatch\n safeCall(() => (plugin as any)[hook]?.(...args));\n }\n };\n }\n\n const manager: PluginManager<S> = {\n // biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n register(plugin: Plugin<any>): void {\n // Check for duplicate names\n if (plugins.some((p) => p.name === plugin.name)) {\n console.warn(\n `[Directive] Plugin \"${plugin.name}\" is already registered, replacing...`,\n );\n this.unregister(plugin.name);\n }\n plugins.push(plugin);\n },\n\n unregister(name: string): void {\n const index = plugins.findIndex((p) => p.name === name);\n if (index !== -1) {\n plugins.splice(index, 1);\n }\n },\n\n // biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema\n getPlugins(): Plugin<any>[] {\n return [...plugins];\n },\n\n // Lifecycle hooks (emitInit is async, handled separately)\n // biome-ignore lint/suspicious/noExplicitAny: System type varies\n async emitInit(system: System<any>): Promise<void> {\n for (const plugin of plugins) {\n await safeCallAsync(() => plugin.onInit?.(system) as Promise<void>);\n }\n },\n emitStart: broadcast(\"onStart\"),\n emitStop: broadcast(\"onStop\"),\n emitDestroy: broadcast(\"onDestroy\"),\n\n // Fact hooks\n emitFactSet: broadcast(\"onFactSet\"),\n emitFactDelete: broadcast(\"onFactDelete\"),\n emitFactsBatch: broadcast(\"onFactsBatch\"),\n\n // Derivation hooks\n emitDerivationCompute: broadcast(\"onDerivationCompute\"),\n emitDerivationInvalidate: broadcast(\"onDerivationInvalidate\"),\n\n // Reconciliation hooks\n emitReconcileStart: broadcast(\"onReconcileStart\"),\n emitReconcileEnd: broadcast(\"onReconcileEnd\"),\n\n // Constraint hooks\n emitConstraintEvaluate: broadcast(\"onConstraintEvaluate\"),\n emitConstraintError: broadcast(\"onConstraintError\"),\n\n // Requirement hooks\n emitRequirementCreated: broadcast(\"onRequirementCreated\"),\n emitRequirementMet: broadcast(\"onRequirementMet\"),\n emitRequirementCanceled: broadcast(\"onRequirementCanceled\"),\n\n // Resolver hooks\n emitResolverStart: broadcast(\"onResolverStart\"),\n emitResolverComplete: broadcast(\"onResolverComplete\"),\n emitResolverError: broadcast(\"onResolverError\"),\n emitResolverRetry: broadcast(\"onResolverRetry\"),\n emitResolverCancel: broadcast(\"onResolverCancel\"),\n\n // Effect hooks\n emitEffectRun: broadcast(\"onEffectRun\"),\n emitEffectError: broadcast(\"onEffectError\"),\n\n // History hooks\n emitSnapshot: broadcast(\"onSnapshot\"),\n emitHistoryNavigate: broadcast(\"onHistoryNavigate\"),\n\n // Error boundary hooks\n emitError: broadcast(\"onError\"),\n emitErrorRecovery: broadcast(\"onErrorRecovery\"),\n\n // Dynamic definition hooks\n emitDefinitionRegister: broadcast(\"onDefinitionRegister\"),\n emitDefinitionAssign: broadcast(\"onDefinitionAssign\"),\n emitDefinitionUnregister: broadcast(\"onDefinitionUnregister\"),\n emitDefinitionCall: broadcast(\"onDefinitionCall\"),\n\n // Trace hooks\n emitTraceComplete: broadcast(\"onTraceComplete\"),\n } as PluginManager<S>;\n\n return 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 { withTimeout } from \"../utils/utils.js\";\nimport type {\n BatchConfig,\n BatchResolveResults,\n Facts,\n FactsSnapshot,\n FactsStore,\n Requirement,\n RequirementWithId,\n ResolverContext,\n ResolverStatus,\n ResolversDef,\n RetryPolicy,\n Schema,\n} from \"./types.js\";\n\n// ============================================================================\n// Resolvers Manager\n// ============================================================================\n\n/**\n * Summary of a resolver that is currently in flight.\n *\n * @internal\n */\nexport interface InflightInfo {\n /** The unique requirement ID being resolved. */\n id: string;\n /** The definition ID of the resolver handling this requirement. */\n resolverId: string;\n /** Epoch timestamp (ms) when resolution started. */\n startedAt: number;\n}\n\n/**\n * Manager returned by {@link createResolversManager} that matches\n * requirements to resolver handlers and manages their execution lifecycle.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ResolversManager<_S extends Schema> {\n /**\n * Start resolving a requirement by matching it to a resolver handler.\n *\n * @remarks\n * Duplicate in-flight requirements (same `req.id`) are silently ignored.\n * If the matched resolver has `batch.enabled`, the requirement is queued\n * for batch processing instead of being resolved immediately.\n *\n * @param req - The requirement (with a stable identity ID) to resolve.\n */\n resolve(req: RequirementWithId): void;\n /**\n * Cancel an in-flight or batch-queued resolver by requirement ID.\n *\n * @remarks\n * Aborts the `AbortController` for in-flight resolvers. For batch-queued\n * requirements, removes the requirement from the pending batch.\n *\n * @param requirementId - The unique requirement ID to cancel.\n */\n cancel(requirementId: string): void;\n /**\n * Cancel every in-flight resolver and flush all pending batch queues.\n */\n cancelAll(): void;\n /**\n * Get the current status of a resolver by requirement ID.\n *\n * @param requirementId - The unique requirement ID to look up.\n * @returns The {@link ResolverStatus} (idle, pending, running, success, error, or canceled).\n */\n getStatus(requirementId: string): ResolverStatus;\n /**\n * Get the requirement IDs of all currently in-flight resolvers.\n *\n * @returns An array of requirement ID strings.\n */\n getInflight(): string[];\n /**\n * Get detailed info for every in-flight resolver.\n *\n * @returns An array of {@link InflightInfo} objects.\n */\n getInflightInfo(): InflightInfo[];\n /**\n * Get the number of currently in-flight resolvers without allocating an array.\n *\n * @returns The count of in-flight resolvers.\n */\n getInflightCount(): number;\n /**\n * Check whether a requirement is currently being resolved.\n *\n * @param requirementId - The unique requirement ID to check.\n * @returns `true` if the requirement has an active in-flight resolver.\n */\n isResolving(requirementId: string): boolean;\n /**\n * Immediately flush all pending batch queues, executing their resolvers.\n */\n processBatches(): void;\n /**\n * Check whether any batch queues have requirements waiting to be processed.\n *\n * @returns `true` if at least one batch queue is non-empty.\n */\n hasPendingBatches(): boolean;\n /**\n * Register additional resolver definitions at runtime (used for dynamic\n * module registration).\n *\n * @remarks\n * Clears the resolver-by-type cache so newly registered resolvers are\n * discoverable on the next {@link ResolversManager.resolve | resolve} call.\n *\n * @param newDefs - New resolver definitions to merge into the manager.\n */\n registerDefinitions(newDefs: ResolversDef<Schema>): void;\n /**\n * Override an existing resolver definition.\n *\n * @param id - The resolver definition ID to override.\n * @param def - The new resolver definition.\n * @throws If no resolver with this ID exists.\n */\n assignDefinition(id: string, def: ResolversDef<Schema>[string]): void;\n /**\n * Remove a resolver definition. Cancels any inflight resolution.\n *\n * @param id - The resolver definition ID to remove.\n */\n unregisterDefinition(id: string): void;\n /**\n * Execute a resolver with a given requirement object.\n *\n * @param id - The resolver definition ID.\n * @param requirement - The requirement to resolve.\n */\n callOne(id: string, requirement: Requirement): Promise<void>;\n /**\n * Clean up all internal state. Called on system destroy.\n */\n destroy(): void;\n}\n\n/** Internal resolver state */\ninterface ResolverState {\n requirementId: string;\n resolverId: string;\n controller: AbortController;\n startedAt: number;\n attempt: number;\n status: ResolverStatus;\n /** Original requirement for proper cancel callback */\n originalRequirement: RequirementWithId;\n}\n\n/** Batch state for batched resolvers */\ninterface BatchState {\n resolverId: string;\n requirements: RequirementWithId[];\n timer: ReturnType<typeof setTimeout> | null;\n}\n\n/**\n * Configuration options accepted by {@link createResolversManager}.\n *\n * @internal\n */\nexport interface CreateResolversOptions<S extends Schema> {\n /** Resolver definitions keyed by ID. */\n definitions: ResolversDef<S>;\n /** Proxy-based facts object passed to resolver contexts. */\n facts: Facts<S>;\n /** Underlying fact store used for `batch()` coalescing of mutations. */\n store: FactsStore<S>;\n /** Called when a resolver begins execution. */\n onStart?: (resolver: string, req: RequirementWithId) => void;\n /** Called when a resolver completes successfully, with the wall-clock duration in ms. */\n onComplete?: (\n resolver: string,\n req: RequirementWithId,\n duration: number,\n ) => void;\n /** Called when a resolver exhausts all retry attempts. */\n onError?: (resolver: string, req: RequirementWithId, error: unknown) => void;\n /** Called before each retry attempt with the upcoming attempt number. */\n onRetry?: (resolver: string, req: RequirementWithId, attempt: number) => void;\n /** Called when a resolver is canceled via {@link ResolversManager.cancel | cancel}. */\n onCancel?: (resolver: string, req: RequirementWithId) => void;\n /** Called after any resolver finishes (success, error, or batch completion) to trigger reconciliation. */\n onResolutionComplete?: () => void;\n}\n\n/** Default retry policy */\nconst DEFAULT_RETRY: RetryPolicy = {\n attempts: 1,\n backoff: \"none\",\n initialDelay: 100,\n maxDelay: 30000,\n};\n\n/** Default batch config */\nconst DEFAULT_BATCH: BatchConfig = {\n enabled: false,\n windowMs: 50,\n};\n\n/**\n * Calculate delay for a retry attempt based on backoff policy.\n *\n * @param policy - Retry policy with backoff strategy and delay bounds\n * @param attempt - Current attempt number (1-based)\n * @returns Delay in milliseconds, clamped to maxDelay\n */\nfunction calculateDelay(policy: RetryPolicy, attempt: number): number {\n const { backoff, initialDelay = 100, maxDelay = 30000 } = policy;\n\n let delay: number;\n\n switch (backoff) {\n case \"none\":\n delay = initialDelay;\n break;\n case \"linear\":\n delay = initialDelay * attempt;\n break;\n case \"exponential\":\n delay = initialDelay * 2 ** (attempt - 1);\n break;\n default:\n delay = initialDelay;\n }\n\n // Ensure delay is at least 1ms to prevent busy loops\n return 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 * @remarks\n * Resolvers are matched by requirement type (string equality) or a predicate\n * function. Each resolution runs with an `AbortController` for cancellation\n * and configurable retry policies (none, linear, or exponential backoff).\n *\n * **Batching:** When a resolver sets `batch.enabled`, incoming requirements\n * are queued and flushed either when `batch.maxSize` is reached or after\n * `batch.windowMs` elapses, whichever comes first. Batch resolvers can use\n * `resolveBatch` (all-or-nothing) or `resolveBatchWithResults` (per-item\n * success/failure). If only `resolve` is provided with batching enabled, the\n * manager falls back to individual resolution calls.\n *\n * Duplicate in-flight requirements (same requirement ID) are automatically\n * deduplicated. Resolver-by-type lookups are cached with FIFO eviction at\n * 1 000 entries to handle dynamic requirement types.\n *\n * @param options - Configuration including resolver definitions, facts proxy,\n * store, and lifecycle callbacks.\n * @returns A {@link ResolversManager} for dispatching, canceling, and\n * inspecting requirement resolution.\n *\n * @example\n * ```typescript\n * const resolvers = createResolversManager({\n * definitions: {\n * transition: {\n * requirement: \"TRANSITION\",\n * retry: { attempts: 3, backoff: \"exponential\" },\n * resolve: async (req, context) => {\n * context.facts.phase = req.to;\n * context.facts.elapsed = 0;\n * },\n * },\n * },\n * facts: factsProxy,\n * store: factsStore,\n * onComplete: (id, req, ms) => console.log(`${id} resolved in ${ms}ms`),\n * });\n *\n * resolvers.resolve(requirementWithId);\n * ```\n *\n * @internal\n */\n/**\n * Validate resolver definitions in dev mode.\n * Ensures each resolver has resolve() or resolveBatch(), and warns\n * when batch.enabled is set without a batch handler.\n */\nfunction validateDefinitions<S extends Schema>(\n definitions: ResolversDef<S>,\n): void {\n if (process.env.NODE_ENV === \"production\") {\n return;\n }\n\n for (const [id, def] of Object.entries(definitions)) {\n if (!def.resolve && !def.resolveBatch && !def.resolveBatchWithResults) {\n throw new Error(\n `[Directive] Resolver \"${id}\" must define either resolve() or resolveBatch(). Add one of these methods to handle requirements.`,\n );\n }\n\n if (\n !def.batch?.enabled ||\n def.resolveBatch ||\n def.resolveBatchWithResults\n ) {\n continue;\n }\n\n if (def.resolve) {\n console.warn(\n `[Directive] Resolver \"${id}\" has batch.enabled but no resolveBatch(). Falling back to individual resolve() calls. Add resolveBatch() for true bulk operations.`,\n );\n } else {\n throw new Error(\n `[Directive] Resolver \"${id}\" has batch.enabled=true but no resolve(), resolveBatch(), or resolveBatchWithResults() method.`,\n );\n }\n }\n}\n\nexport function createResolversManager<S extends Schema>(\n options: CreateResolversOptions<S>,\n): ResolversManager<S> {\n const {\n definitions,\n facts,\n store,\n onStart,\n onComplete,\n onError,\n onRetry,\n onCancel,\n onResolutionComplete,\n } = options;\n\n validateDefinitions(definitions);\n\n // Active resolver states by requirement ID\n const inflight = new Map<string, ResolverState>();\n\n // Completed/failed statuses (kept for inspection) - LRU cleanup\n const statuses = new Map<string, ResolverStatus>();\n const MAX_STATUSES = 1000; // Limit to prevent memory leak\n\n // Batch states by resolver ID\n const batches = new Map<string, BatchState>();\n\n // Resolver index by requirement type for O(1) lookup (populated lazily)\n // Capped to prevent unbounded growth with dynamic requirement types (e.g., FETCH_USER_${id})\n const resolversByType = new Map<string, Set<string>>();\n const MAX_RESOLVER_CACHE = 1000;\n\n /** Cleanup old statuses to prevent memory leak */\n function cleanupStatuses(): void {\n if (statuses.size > MAX_STATUSES) {\n // Remove oldest entries (first inserted = first in iteration)\n const entriesToRemove = statuses.size - MAX_STATUSES;\n const iterator = statuses.keys();\n for (let i = 0; i < entriesToRemove; i++) {\n const key = iterator.next().value;\n if (key) statuses.delete(key);\n }\n }\n }\n\n /** Type guard for resolver with string `requirement` property */\n function hasStringRequirement(def: unknown): def is { requirement: string } {\n return (\n typeof def === \"object\" &&\n def !== null &&\n \"requirement\" in def &&\n typeof (def as { requirement: unknown }).requirement === \"string\"\n );\n }\n\n /** Type guard for resolver with function `requirement` property */\n function hasFunctionRequirement(\n def: unknown,\n ): def is { requirement: (req: Requirement) => boolean } {\n return (\n typeof def === \"object\" &&\n def !== null &&\n \"requirement\" in def &&\n typeof (def as { requirement: unknown }).requirement === \"function\"\n );\n }\n\n /**\n * Check if a resolver handles a requirement.\n * Supports:\n * - `requirement: \"TYPE\"` - string matching\n * - `requirement: (req) => req is T` - function type guard\n */\n function resolverHandles(\n def: ResolversDef<S>[string],\n req: Requirement,\n ): boolean {\n // Check string-based `requirement`\n if (hasStringRequirement(def)) {\n return req.type === def.requirement;\n }\n\n // Check function-based `requirement` (type guard)\n if (hasFunctionRequirement(def)) {\n return def.requirement(req);\n }\n\n return false;\n }\n\n /** Try to find a resolver from the LRU cache */\n function findResolverInCache(\n reqType: string,\n req: Requirement,\n ): string | null {\n const cached = resolversByType.get(reqType);\n if (!cached) {\n return null;\n }\n\n // Move to end of Map iteration order (LRU: least recently used is first)\n resolversByType.delete(reqType);\n resolversByType.set(reqType, cached);\n\n for (const id of cached) {\n const def = definitions[id];\n if (def && resolverHandles(def, req)) {\n return id;\n }\n }\n\n return null;\n }\n\n /** Add a resolver ID to the type cache, evicting if full */\n function cacheResolverForType(reqType: string, resolverId: string): void {\n if (!resolversByType.has(reqType)) {\n if (resolversByType.size >= MAX_RESOLVER_CACHE) {\n const oldest = resolversByType.keys().next().value;\n if (oldest !== undefined) {\n resolversByType.delete(oldest);\n }\n }\n resolversByType.set(reqType, new Set());\n }\n resolversByType.get(reqType)!.add(resolverId);\n }\n\n /** Find a resolver that handles a requirement */\n function findResolver(req: Requirement): string | null {\n const reqType = req.type;\n\n // Check cache first\n const cached = findResolverInCache(reqType, req);\n if (cached) {\n return cached;\n }\n\n // Fallback to full search and cache the result\n for (const [id, def] of Object.entries(definitions)) {\n if (resolverHandles(def, req)) {\n cacheResolverForType(reqType, id);\n\n return id;\n }\n }\n\n return null;\n }\n\n /** Create resolver context */\n function createContext(signal: AbortSignal): ResolverContext<S> {\n return {\n facts,\n signal,\n snapshot: () => facts.$snapshot() as FactsSnapshot<S>,\n };\n }\n\n /**\n * Shared retry catch-block logic: normalize error, check abort, check shouldRetry,\n * sleep with abort awareness. Returns \"abort\" if canceled, \"break\" if shouldRetry\n * returned false, or \"continue\" if the next attempt should proceed.\n */\n async function handleRetryError(\n error: unknown,\n attempt: number,\n retryPolicy: RetryPolicy & { attempts: number; backoff: string },\n controller: AbortController,\n ): Promise<{ action: \"abort\" | \"break\" | \"continue\"; error: Error }> {\n const normalizedError =\n error instanceof Error ? error : new Error(String(error));\n\n if (controller.signal.aborted) {\n return { action: \"abort\", error: normalizedError };\n }\n\n if (\n retryPolicy.shouldRetry &&\n !retryPolicy.shouldRetry(normalizedError, attempt)\n ) {\n return { action: \"break\", error: normalizedError };\n }\n\n if (attempt < retryPolicy.attempts) {\n if (controller.signal.aborted) {\n return { action: \"abort\", error: normalizedError };\n }\n\n const delay = calculateDelay(retryPolicy, attempt);\n\n await new Promise<void>((resolve) => {\n const timeoutId = setTimeout(resolve, delay);\n const abortHandler = () => {\n clearTimeout(timeoutId);\n resolve();\n };\n controller.signal.addEventListener(\"abort\", abortHandler, {\n once: true,\n });\n });\n\n if (controller.signal.aborted) {\n return { action: \"abort\", error: normalizedError };\n }\n }\n\n return { action: \"continue\", error: normalizedError };\n }\n\n /**\n * Invoke a resolver's resolve() function with optional timeout.\n *\n * The `store.batch()` here intentionally wraps only the synchronous start of\n * the async resolver — it coalesces all fact mutations that happen before the\n * first `await` into a single notification (one `onBatch` callback, one\n * `scheduleReconcile()`). After the first `await`, the batch has ended and\n * each subsequent fact mutation triggers its own `onChange` → reconcile cycle.\n *\n * This is correct: pre-await mutations typically set up transient state (e.g.\n * \"pending\" / \"fetching\" flags) and should be seen as one atomic change, while\n * post-await mutations represent real state transitions (e.g. \"success\" with\n * fetched data) that the constraint engine must evaluate independently.\n */\n async function invokeResolve(\n def: ResolversDef<S>[string],\n resolverId: string,\n req: RequirementWithId,\n signal: AbortSignal,\n ): Promise<void> {\n if (!def.resolve) {\n return;\n }\n\n // Batch wraps only the synchronous start — see JSDoc above.\n let resolvePromise!: Promise<void>;\n store.batch(() => {\n resolvePromise = def.resolve!(\n req.requirement as Parameters<NonNullable<typeof def.resolve>>[0],\n createContext(signal),\n ) as Promise<void>;\n });\n\n const timeout = def.timeout;\n if (timeout && timeout > 0) {\n await withTimeout(\n resolvePromise,\n timeout,\n `Resolver \"${resolverId}\" timed out after ${timeout}ms`,\n );\n\n return;\n }\n\n await resolvePromise;\n }\n\n /** Record a successful resolution */\n function recordSuccess(\n resolverId: string,\n req: RequirementWithId,\n startedAt: number,\n ): void {\n const duration = Date.now() - startedAt;\n statuses.set(req.id, {\n state: \"success\",\n requirementId: req.id,\n completedAt: Date.now(),\n duration,\n });\n cleanupStatuses();\n onComplete?.(resolverId, req, duration);\n }\n\n /** Record a failed resolution */\n function recordError(\n resolverId: string,\n req: RequirementWithId,\n error: Error,\n attempts: number,\n ): void {\n statuses.set(req.id, {\n state: \"error\",\n requirementId: req.id,\n error,\n failedAt: Date.now(),\n attempts,\n });\n cleanupStatuses();\n onError?.(resolverId, req, error);\n }\n\n /** Update inflight state for a new attempt */\n function updateInflightAttempt(\n reqId: string,\n attempt: number,\n startedAt: number,\n ): void {\n const state = inflight.get(reqId);\n if (state) {\n state.attempt = attempt;\n state.status = {\n state: \"running\",\n requirementId: reqId,\n startedAt,\n attempt,\n };\n }\n }\n\n /**\n * Handle the catch block of a retry attempt. Returns true if the loop\n * should continue to the next attempt, false if it should stop.\n */\n async function processRetryError(\n error: unknown,\n attempt: number,\n retryPolicy: RetryPolicy & { attempts: number; backoff: string },\n controller: AbortController,\n notifyRetry: (nextAttempt: number) => void,\n ): Promise<{ lastError: Error; shouldContinue: boolean }> {\n const result = await handleRetryError(\n error,\n attempt,\n retryPolicy,\n controller,\n );\n\n if (result.action === \"continue\" && attempt < retryPolicy.attempts) {\n notifyRetry(attempt + 1);\n }\n\n return {\n lastError: result.error,\n shouldContinue: result.action === \"continue\",\n };\n }\n\n /** Execute a single requirement resolution with retry */\n async function executeResolve(\n resolverId: string,\n req: RequirementWithId,\n controller: AbortController,\n ): Promise<void> {\n const def = definitions[resolverId];\n if (!def) {\n return;\n }\n\n const retryPolicy = { ...DEFAULT_RETRY, ...def.retry };\n let lastError: Error | null = null;\n const startedAt = inflight.get(req.id)?.startedAt ?? Date.now();\n\n for (let attempt = 1; attempt <= retryPolicy.attempts; attempt++) {\n if (controller.signal.aborted) {\n return;\n }\n\n updateInflightAttempt(req.id, attempt, startedAt);\n\n try {\n await invokeResolve(def, resolverId, req, controller.signal);\n recordSuccess(resolverId, req, startedAt);\n\n return;\n } catch (error) {\n const outcome = await processRetryError(\n error,\n attempt,\n retryPolicy,\n controller,\n (next) => onRetry?.(resolverId, req, next),\n );\n lastError = outcome.lastError;\n\n if (!outcome.shouldContinue) {\n break;\n }\n }\n }\n\n recordError(resolverId, req, lastError!, retryPolicy.attempts);\n }\n\n /** Await a promise with optional timeout */\n async function awaitWithTimeout<T>(\n promise: Promise<T>,\n timeout: number | undefined,\n timeoutMessage: string,\n ): Promise<T> {\n if (timeout && timeout > 0) {\n return withTimeout(promise, timeout, timeoutMessage);\n }\n\n return promise;\n }\n\n /**\n * Execute resolveBatchWithResults and process per-item results.\n * Returns \"done\" if no retry needed, or \"retry\" if all items failed.\n */\n async function executeWithResults(\n def: ResolversDef<S>[string],\n resolverId: string,\n requirements: RequirementWithId[],\n reqPayloads: Requirement[],\n ctx: ResolverContext<S>,\n timeout: number | undefined,\n startedAt: number,\n attempt: number,\n ): Promise<\"done\" | \"retry\"> {\n let resolvePromise!: Promise<BatchResolveResults>;\n store.batch(() => {\n // biome-ignore lint/suspicious/noExplicitAny: Requirement type varies\n resolvePromise = def.resolveBatchWithResults!(reqPayloads as any, ctx);\n });\n\n const results = await awaitWithTimeout(\n resolvePromise,\n timeout,\n `Batch resolver \"${resolverId}\" timed out after ${timeout}ms`,\n );\n\n if (results.length !== requirements.length) {\n throw new Error(\n `[Directive] Batch resolver \"${resolverId}\" returned ${results.length} results ` +\n `but expected ${requirements.length}. Results array must match input order.`,\n );\n }\n\n let hasFailures = false;\n\n for (let i = 0; i < requirements.length; i++) {\n const req = requirements[i]!;\n const result = results[i]!;\n\n if (result.success) {\n recordSuccess(resolverId, req, startedAt);\n continue;\n }\n\n hasFailures = true;\n const error = result.error ?? new Error(\"Batch item failed\");\n statuses.set(req.id, {\n state: \"error\",\n requirementId: req.id,\n error,\n failedAt: Date.now(),\n attempts: attempt,\n });\n onError?.(resolverId, req, error);\n }\n\n // No failures or partial success: done (don't retry partial)\n if (!hasFailures || requirements.some((_, i) => results[i]?.success)) {\n return \"done\";\n }\n\n // ALL failed: caller should retry\n return \"retry\";\n }\n\n /** Execute all-or-nothing resolveBatch and mark all as success */\n async function executeAllOrNothing(\n def: ResolversDef<S>[string],\n resolverId: string,\n requirements: RequirementWithId[],\n reqPayloads: Requirement[],\n ctx: ResolverContext<S>,\n timeout: number | undefined,\n startedAt: number,\n ): Promise<void> {\n let resolvePromise!: Promise<void>;\n store.batch(() => {\n resolvePromise = def.resolveBatch!(\n // biome-ignore lint/suspicious/noExplicitAny: Requirement type varies\n reqPayloads as any,\n ctx,\n ) as Promise<void>;\n });\n\n await awaitWithTimeout(\n resolvePromise,\n timeout,\n `Batch resolver \"${resolverId}\" timed out after ${timeout}ms`,\n );\n\n for (const req of requirements) {\n recordSuccess(resolverId, req, startedAt);\n }\n }\n\n /** Record errors for all requirements in a batch */\n function recordBatchErrors(\n resolverId: string,\n requirements: RequirementWithId[],\n error: Error,\n attempts: number,\n ): void {\n for (const req of requirements) {\n recordError(resolverId, req, error, attempts);\n }\n }\n\n /** Fall back to individual resolution when no batch handler is defined */\n async function executeBatchFallback(\n resolverId: string,\n requirements: RequirementWithId[],\n ): Promise<void> {\n await Promise.all(\n requirements.map((req) => {\n const controller = new AbortController();\n\n return executeResolve(resolverId, req, controller);\n }),\n );\n }\n\n /** Execute one attempt of a batch (with-results or all-or-nothing) */\n async function executeBatchAttempt(\n def: ResolversDef<S>[string],\n resolverId: string,\n requirements: RequirementWithId[],\n signal: AbortSignal,\n timeout: number | undefined,\n startedAt: number,\n attempt: number,\n ): Promise<\"done\" | \"retry\"> {\n const ctx = createContext(signal);\n const reqPayloads = requirements.map((r) => r.requirement);\n\n if (def.resolveBatchWithResults) {\n return executeWithResults(\n def,\n resolverId,\n requirements,\n reqPayloads,\n ctx,\n timeout,\n startedAt,\n attempt,\n );\n }\n\n await executeAllOrNothing(\n def,\n resolverId,\n requirements,\n reqPayloads,\n ctx,\n timeout,\n startedAt,\n );\n\n return \"done\";\n }\n\n /** Notify retry for all requirements in a batch */\n function notifyBatchRetry(\n resolverId: string,\n requirements: RequirementWithId[],\n nextAttempt: number,\n ): void {\n for (const req of requirements) {\n onRetry?.(resolverId, req, nextAttempt);\n }\n }\n\n /** Run the retry loop for a batch, returning the last error if all attempts fail */\n async function runBatchRetryLoop(\n def: ResolversDef<S>[string],\n resolverId: string,\n requirements: RequirementWithId[],\n retryPolicy: RetryPolicy & { attempts: number; backoff: string },\n timeout: number | undefined,\n ): Promise<Error | null> {\n const controller = new AbortController();\n const startedAt = Date.now();\n let lastError: Error | null = null;\n\n for (let attempt = 1; attempt <= retryPolicy.attempts; attempt++) {\n if (controller.signal.aborted) {\n return null;\n }\n\n try {\n const outcome = await executeBatchAttempt(\n def,\n resolverId,\n requirements,\n controller.signal,\n timeout,\n startedAt,\n attempt,\n );\n if (outcome === \"done\") {\n return null;\n }\n } catch (error) {\n const outcome = await processRetryError(\n error,\n attempt,\n retryPolicy,\n controller,\n (next) => notifyBatchRetry(resolverId, requirements, next),\n );\n lastError = outcome.lastError;\n\n if (!outcome.shouldContinue) {\n break;\n }\n }\n }\n\n return lastError;\n }\n\n /** Execute a batch of requirements with retry, timeout, and partial failure support */\n async function executeBatch(\n resolverId: string,\n requirements: RequirementWithId[],\n ): Promise<void> {\n const def = definitions[resolverId];\n if (!def) {\n return;\n }\n\n if (!def.resolveBatch && !def.resolveBatchWithResults) {\n await executeBatchFallback(resolverId, requirements);\n\n return;\n }\n\n const retryPolicy = { ...DEFAULT_RETRY, ...def.retry };\n const batchConfig = { ...DEFAULT_BATCH, ...def.batch };\n const timeout = batchConfig.timeoutMs ?? def.timeout;\n\n const lastError = await runBatchRetryLoop(\n def,\n resolverId,\n requirements,\n retryPolicy,\n timeout,\n );\n\n if (lastError) {\n recordBatchErrors(\n resolverId,\n requirements,\n lastError,\n retryPolicy.attempts,\n );\n }\n }\n\n /** Hard cap for batch queues without explicit maxSize — prevents OOM */\n const DEFAULT_MAX_QUEUE_SIZE = 10_000;\n\n /** Cancel a batch timer if active */\n function clearBatchTimer(batch: BatchState): void {\n if (batch.timer) {\n clearTimeout(batch.timer);\n batch.timer = null;\n }\n }\n\n /** Ensure a batch entry exists for a resolver */\n function ensureBatch(resolverId: string): BatchState {\n if (!batches.has(resolverId)) {\n batches.set(resolverId, {\n resolverId,\n requirements: [],\n timer: null,\n });\n }\n\n return batches.get(resolverId)!;\n }\n\n /** Add a requirement to a batch */\n function addToBatch(resolverId: string, req: RequirementWithId): void {\n const def = definitions[resolverId];\n if (!def) {\n return;\n }\n\n const batchConfig = { ...DEFAULT_BATCH, ...def.batch };\n const batch = ensureBatch(resolverId);\n\n // Enforce hard cap to prevent OOM from unbounded accumulation\n const effectiveMax = batchConfig.maxSize || DEFAULT_MAX_QUEUE_SIZE;\n if (batch.requirements.length >= effectiveMax) {\n clearBatchTimer(batch);\n processBatch(resolverId);\n }\n\n batch.requirements.push(req);\n\n // Flush immediately if maxSize reached\n if (\n batchConfig.maxSize &&\n batch.requirements.length >= batchConfig.maxSize\n ) {\n clearBatchTimer(batch);\n processBatch(resolverId);\n\n return;\n }\n\n // Start or reset timer\n clearBatchTimer(batch);\n batch.timer = setTimeout(() => {\n processBatch(resolverId);\n }, batchConfig.windowMs);\n }\n\n /** Process a single batch */\n function processBatch(resolverId: string): void {\n const batch = batches.get(resolverId);\n if (!batch || batch.requirements.length === 0) return;\n\n const requirements = [...batch.requirements];\n batch.requirements = [];\n batch.timer = null;\n\n // Execute batch\n executeBatch(resolverId, requirements).then(() => {\n onResolutionComplete?.();\n });\n }\n\n const manager: ResolversManager<S> = {\n resolve(req: RequirementWithId): void {\n // Already resolving?\n if (inflight.has(req.id)) {\n return;\n }\n\n // Find resolver\n const resolverId = findResolver(req.requirement);\n if (!resolverId) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Directive] No resolver found for requirement type \"${req.requirement.type}\" (id: ${req.id})`,\n );\n }\n return;\n }\n\n const def = definitions[resolverId];\n if (!def) return;\n\n // Check if this is a batched resolver\n if (def.batch?.enabled) {\n addToBatch(resolverId, req);\n return;\n }\n\n // Start resolution\n const controller = new AbortController();\n const startedAt = Date.now();\n\n const state: ResolverState = {\n requirementId: req.id,\n resolverId,\n controller,\n startedAt,\n attempt: 1,\n status: {\n state: \"pending\",\n requirementId: req.id,\n startedAt,\n },\n originalRequirement: req,\n };\n\n inflight.set(req.id, state);\n onStart?.(resolverId, req);\n\n // Execute asynchronously\n executeResolve(resolverId, req, controller).finally(() => {\n // Only fire onResolutionComplete if we're the first to clean up.\n // If cancel() already removed us from inflight, skip to avoid\n // spurious double-notifications.\n const wasInflight = inflight.delete(req.id);\n if (wasInflight) {\n onResolutionComplete?.();\n }\n });\n },\n\n cancel(requirementId: string): void {\n // Check inflight resolvers first\n const state = inflight.get(requirementId);\n if (state) {\n state.controller.abort();\n inflight.delete(requirementId);\n\n statuses.set(requirementId, {\n state: \"canceled\",\n requirementId,\n canceledAt: Date.now(),\n });\n cleanupStatuses();\n\n onCancel?.(state.resolverId, state.originalRequirement);\n\n return;\n }\n\n // Check pending batch queues\n for (const batch of batches.values()) {\n const idx = batch.requirements.findIndex((r) => r.id === requirementId);\n if (idx !== -1) {\n const [removed] = batch.requirements.splice(idx, 1);\n\n statuses.set(requirementId, {\n state: \"canceled\",\n requirementId,\n canceledAt: Date.now(),\n });\n cleanupStatuses();\n\n if (removed) {\n onCancel?.(batch.resolverId, removed);\n }\n\n return;\n }\n }\n },\n\n cancelAll(): void {\n const ids = [...inflight.keys()];\n for (const id of ids) {\n this.cancel(id);\n }\n\n // Cancel queued batch requirements\n for (const batch of batches.values()) {\n if (batch.timer) {\n clearTimeout(batch.timer);\n }\n for (const req of batch.requirements) {\n statuses.set(req.id, {\n state: \"canceled\",\n requirementId: req.id,\n canceledAt: Date.now(),\n });\n onCancel?.(batch.resolverId, req);\n }\n }\n batches.clear();\n cleanupStatuses();\n },\n\n getStatus(requirementId: string): ResolverStatus {\n // Check inflight first\n const state = inflight.get(requirementId);\n if (state) {\n return state.status;\n }\n\n // Check completed statuses\n const status = statuses.get(requirementId);\n if (status) {\n return status;\n }\n\n return { state: \"idle\" };\n },\n\n getInflight(): string[] {\n return [...inflight.keys()];\n },\n\n getInflightInfo(): InflightInfo[] {\n return [...inflight.values()].map((state) => ({\n id: state.requirementId,\n resolverId: state.resolverId,\n startedAt: state.startedAt,\n }));\n },\n\n getInflightCount(): number {\n return inflight.size;\n },\n\n isResolving(requirementId: string): boolean {\n return inflight.has(requirementId);\n },\n\n processBatches(): void {\n for (const resolverId of batches.keys()) {\n processBatch(resolverId);\n }\n },\n\n hasPendingBatches(): boolean {\n for (const batch of batches.values()) {\n if (batch.requirements.length > 0) {\n return true;\n }\n }\n\n return false;\n },\n\n registerDefinitions(newDefs: ResolversDef<Schema>): void {\n for (const [key, def] of Object.entries(newDefs)) {\n (definitions as Record<string, unknown>)[key] = def;\n }\n // Clear the resolver-by-type cache so new resolvers are discovered\n resolversByType.clear();\n },\n\n assignDefinition(id: string, def: ResolversDef<Schema>[string]): void {\n if (!definitions[id]) {\n throw new Error(\n `[Directive] Cannot assign resolver \"${id}\" — it does not exist. Use register() to create it.`,\n );\n }\n\n // Replace definition\n (definitions as Record<string, unknown>)[id] = def;\n // Clear cache so the new definition is discoverable\n resolversByType.clear();\n },\n\n unregisterDefinition(id: string): void {\n if (!definitions[id]) {\n return;\n }\n\n // Cancel any inflight resolutions using this resolver\n for (const [reqId, state] of inflight) {\n if (state.resolverId === id) {\n state.controller.abort();\n inflight.delete(reqId);\n statuses.set(reqId, {\n state: \"canceled\",\n requirementId: reqId,\n canceledAt: Date.now(),\n });\n onCancel?.(id, state.originalRequirement);\n }\n }\n\n // Remove from batch queues\n const batch = batches.get(id);\n if (batch) {\n if (batch.timer) {\n clearTimeout(batch.timer);\n }\n for (const req of batch.requirements) {\n statuses.set(req.id, {\n state: \"canceled\",\n requirementId: req.id,\n canceledAt: Date.now(),\n });\n onCancel?.(id, req);\n }\n batches.delete(id);\n }\n\n delete (definitions as Record<string, unknown>)[id];\n resolversByType.clear();\n cleanupStatuses();\n },\n\n async callOne(id: string, requirement: Requirement): Promise<void> {\n const def = definitions[id];\n if (!def) {\n throw new Error(\n `[Directive] Cannot call resolver \"${id}\" — it does not exist.`,\n );\n }\n\n const controller = new AbortController();\n const ctx = createContext(controller.signal);\n\n if (def.resolve) {\n // Batch wraps only the synchronous start — see invokeResolve JSDoc.\n let resolvePromise!: Promise<void>;\n store.batch(() => {\n resolvePromise = def.resolve!(\n requirement as Parameters<NonNullable<typeof def.resolve>>[0],\n ctx,\n ) as Promise<void>;\n });\n\n await resolvePromise;\n }\n },\n\n destroy(): void {\n this.cancelAll();\n statuses.clear();\n resolversByType.clear();\n },\n };\n\n return manager;\n}\n","/**\n * Proxy-based accessors for the engine's derive and events surfaces.\n *\n * Extracted from engine.ts to reduce file size. Pure proxy creation —\n * all state mutation is delegated to callbacks.\n *\n * @internal\n */\n\nimport type { DefinitionsRegistry } from \"./engine-definitions.js\";\nimport { BLOCKED_PROPS } from \"./tracking.js\";\n\n// ============================================================================\n// Derive Accessor\n// ============================================================================\n\n/**\n * Options for creating the derive accessor proxy.\n *\n * @internal\n */\nexport interface CreateDeriveAccessorOptions {\n /** Merged derivation definitions (mutable reference, checked for key existence) */\n mergedDerive: Record<string, unknown>;\n /** Retrieve a computed derivation value by key */\n getDerivation: (key: string) => unknown;\n /** Definitions registry for dynamic definition methods */\n definitions: DefinitionsRegistry;\n}\n\n/**\n * Create a proxy that provides `system.derive.key` access to derivation values\n * plus dynamic definition methods (register, assign, unregister, etc.).\n *\n * @param options - Derivation definitions, getter, and dynamic registry\n * @returns A proxy combining derivation value access with definition management\n *\n * @internal\n */\nexport function createDeriveAccessor(\n options: CreateDeriveAccessorOptions,\n): Record<string, unknown> {\n const { mergedDerive, getDerivation, definitions } = options;\n\n // Method properties for derive accessor (dynamic definitions API)\n const deriveMethods: Record<string, unknown> = {\n register: (id: string, fn: unknown) =>\n definitions.register(\"derivation\", id, fn),\n assign: (id: string, fn: unknown) =>\n definitions.assign(\"derivation\", id, fn),\n unregister: (id: string) => definitions.unregister(\"derivation\", id),\n call: (id: string) => definitions.call(\"derivation\", id),\n isDynamic: (id: string) => definitions.isDynamic(\"derivation\", id),\n listDynamic: () => definitions.listDynamic(\"derivation\"),\n };\n\n return new Proxy({} as Record<string, unknown>, {\n get(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n // Prototype pollution protection\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n // Check for method properties first (register, assign, etc.)\n if (prop in deriveMethods) {\n return deriveMethods[prop];\n }\n // Return undefined for unknown derivation keys instead of throwing.\n // React 19 dev-mode traverses objects accessing $$typeof, toJSON, then, etc.\n if (!(prop in mergedDerive)) {\n return undefined;\n }\n return getDerivation(prop);\n },\n has(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n // Prototype pollution protection\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n return prop in mergedDerive || prop in deriveMethods;\n },\n ownKeys() {\n return Object.keys(mergedDerive);\n },\n getOwnPropertyDescriptor(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n // Prototype pollution protection\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n if (prop in mergedDerive || prop in deriveMethods) {\n return { configurable: true, enumerable: true };\n }\n return undefined;\n },\n set() {\n return false;\n },\n defineProperty() {\n return false;\n },\n getPrototypeOf() {\n return null;\n },\n setPrototypeOf() {\n return false;\n },\n });\n}\n\n// ============================================================================\n// Events Accessor\n// ============================================================================\n\n/**\n * Options for creating the events accessor proxy.\n *\n * @internal\n */\nexport interface CreateEventsAccessorOptions {\n /** Merged event definitions (mutable reference, checked for key existence) */\n mergedEvents: Record<string, unknown>;\n /** Dispatch an event by name with optional payload */\n dispatchEvent: (eventName: string, payload?: Record<string, unknown>) => void;\n}\n\n/**\n * Create a proxy that provides `system.events.eventName(payload)` syntax.\n * Dispatching is delegated to the provided callback.\n *\n * @param options - Event definitions and dispatch callback\n * @returns A proxy that returns dispatch functions per event name\n *\n * @internal\n */\nexport function createEventsAccessor(\n options: CreateEventsAccessorOptions,\n): Record<string, (payload?: Record<string, unknown>) => void> {\n const { mergedEvents, dispatchEvent } = options;\n\n return new Proxy(\n {} as Record<string, (payload?: Record<string, unknown>) => void>,\n {\n get(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n // Prototype pollution protection\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n // Return a function that dispatches the event\n return (payload?: Record<string, unknown>) => {\n dispatchEvent(prop, payload);\n };\n },\n has(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n // Prototype pollution protection\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n return prop in mergedEvents;\n },\n ownKeys() {\n return Object.keys(mergedEvents);\n },\n getOwnPropertyDescriptor(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n // Prototype pollution protection\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n if (prop in mergedEvents) {\n return { configurable: true, enumerable: true };\n }\n return undefined;\n },\n set() {\n return false;\n },\n defineProperty() {\n return false;\n },\n getPrototypeOf() {\n return null;\n },\n setPrototypeOf() {\n return false;\n },\n },\n );\n}\n","/**\n * Dynamic definition registry for the engine.\n *\n * Extracted from engine.ts to reduce file size. Handles register, assign,\n * unregister, call, getOriginal, restoreOriginal, isDynamic, and listDynamic\n * for constraints, resolvers, derivations, and effects.\n *\n * @internal\n */\n\nimport type { ConstraintsManager } from \"./constraints.js\";\nimport type { DerivationsManager } from \"./derivations.js\";\nimport type { EffectsManager } from \"./effects.js\";\nimport type { PluginManager } from \"./plugins.js\";\nimport type { ResolversManager } from \"./resolvers.js\";\nimport { BLOCKED_PROPS } from \"./tracking.js\";\nimport type {\n ConstraintsDef,\n DerivationsDef,\n EffectsDef,\n ResolversDef,\n Schema,\n} from \"./types.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Definition type for dynamic registration */\nexport type DefType = \"constraint\" | \"resolver\" | \"derivation\" | \"effect\";\n\ntype DeferredOp =\n | { op: \"register\"; type: DefType; id: string; def: unknown }\n | { op: \"assign\"; type: DefType; id: string; def: unknown }\n | { op: \"unregister\"; type: DefType; id: string };\n\n// ============================================================================\n// DefinitionsRegistry Interface\n// ============================================================================\n\n/**\n * Registry for dynamic definition management (register, assign, unregister, call).\n *\n * @remarks\n * Handles deferral during reconciliation — operations queued while reconciling\n * are applied atomically after the cycle completes. Tracks which definitions\n * were dynamically registered vs. statically defined from module configs.\n *\n * @internal\n */\nexport interface DefinitionsRegistry {\n /**\n * Register a new definition. Deferred if called during reconciliation.\n *\n * @param type - The definition type\n * @param id - Unique definition identifier\n * @param def - The definition object\n * @throws If the definition already exists, or the ID is invalid\n */\n register(type: DefType, id: string, def: unknown): void;\n\n /**\n * Override an existing definition. Deferred if called during reconciliation.\n * Stores the original for later restoration.\n *\n * @param type - The definition type\n * @param id - Definition identifier to override\n * @param def - The replacement definition\n * @throws If the definition does not exist, or the ID is invalid\n */\n assign(type: DefType, id: string, def: unknown): void;\n\n /**\n * Remove a dynamically registered definition. Deferred if called during reconciliation.\n * Static (module-defined) definitions cannot be unregistered.\n *\n * @param type - The definition type\n * @param id - Definition identifier to remove\n */\n unregister(type: DefType, id: string): void;\n\n /**\n * Invoke a definition directly (evaluate constraint, run resolver, etc.).\n *\n * @param type - The definition type\n * @param id - Definition identifier to invoke\n * @param props - Optional properties/payload\n * @returns The invocation result\n */\n call(type: DefType, id: string, props?: unknown): unknown;\n\n /**\n * Check if a definition was dynamically registered.\n *\n * @param type - The definition type\n * @param id - Definition identifier\n */\n isDynamic(type: DefType, id: string): boolean;\n\n /**\n * List all dynamically registered definition IDs for a type.\n *\n * @param type - The definition type\n */\n listDynamic(type: DefType): string[];\n\n /**\n * Flush deferred registrations queued during reconciliation.\n */\n flushDeferred(): void;\n\n /**\n * Get the original definition before it was assigned/overridden.\n *\n * @param type - The definition type\n * @param id - Definition identifier\n * @returns The original definition, or undefined if not overridden\n */\n getOriginal(type: DefType, id: string): unknown | undefined;\n\n /**\n * Restore a definition to its original value (before assign).\n *\n * @param type - The definition type\n * @param id - Definition identifier\n * @returns true if restored, false if no original was found\n */\n restoreOriginal(type: DefType, id: string): boolean;\n\n /**\n * Clean up all dynamic definition state.\n */\n destroy(): void;\n}\n\n// ============================================================================\n// Factory Options\n// ============================================================================\n\n/**\n * Options for creating a definitions registry.\n *\n * @internal\n */\nexport interface CreateDefinitionsRegistryOptions<S extends Schema> {\n /** Merged constraint definitions (mutable reference) */\n mergedConstraints: ConstraintsDef<S>;\n /** Merged resolver definitions (mutable reference) */\n mergedResolvers: ResolversDef<S>;\n /** Merged derivation definitions (mutable reference) */\n mergedDerive: DerivationsDef<S>;\n /** Merged effect definitions (mutable reference) */\n mergedEffects: EffectsDef<S>;\n /** Constraints manager */\n constraintsManager: ConstraintsManager<S>;\n /** Resolvers manager */\n resolversManager: ResolversManager<S>;\n /** Derivations manager */\n derivationsManager: DerivationsManager<S, DerivationsDef<S>>;\n /** Effects manager */\n effectsManager: EffectsManager<S>;\n /** Plugin manager */\n pluginManager: PluginManager<S>;\n /** Getter for engine state flags */\n getState: () => { isDestroyed: boolean; isReconciling: boolean };\n /** Trigger reconciliation */\n scheduleReconcile: () => void;\n /** Max deferred registrations */\n maxDeferredRegistrations: number;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/** Reserved derive method names — derivation IDs cannot use these */\nconst RESERVED_DERIVE_NAMES = new Set([\n \"register\",\n \"assign\",\n \"unregister\",\n \"call\",\n \"isDynamic\",\n \"listDynamic\",\n]);\n\n/**\n * Per-type descriptor used by the dispatch map to collapse the switch\n * statements in applyRegister, applyAssign, and applyUnregister.\n */\ninterface TypeDescriptor {\n /** Human-readable label for error messages */\n label: string;\n /** The mutable merged definitions map for this type */\n mergedMap: Record<string, unknown>;\n /** The manager instance for this type */\n manager: {\n registerDefinitions(defs: Record<string, unknown>): void;\n assignDefinition(id: string, def: unknown): void;\n unregisterDefinition(id: string): void;\n };\n /** Set of dynamically registered IDs */\n dynamicSet: Set<string>;\n /** Map of originals for assigned definitions */\n originalsMap: Map<string, unknown>;\n /** Whether to call scheduleReconcile after register/assign/unregister */\n reconciles: boolean;\n /** Optional extra validation on the ID (e.g. reserved name check) */\n validateId?: (id: string) => void;\n}\n\n/**\n * Create a definitions registry for dynamic definition management.\n *\n * @remarks\n * Receives mutable references to the merged definition maps and manager\n * instances. Operations modify these references directly to maintain\n * atomicity with the engine's state.\n *\n * @param options - Managers, merged maps, and engine state accessors\n * @returns A {@link DefinitionsRegistry} instance\n *\n * @internal\n */\nexport function createDefinitionsRegistry<S extends Schema>(\n options: CreateDefinitionsRegistryOptions<S>,\n): DefinitionsRegistry {\n const {\n mergedConstraints,\n mergedResolvers,\n mergedDerive,\n mergedEffects,\n constraintsManager,\n resolversManager,\n derivationsManager,\n effectsManager,\n pluginManager,\n getState,\n scheduleReconcile,\n maxDeferredRegistrations,\n } = options;\n\n /** Track which definitions were dynamically registered */\n const dynamicIds = {\n constraints: new Set<string>(),\n resolvers: new Set<string>(),\n derivations: new Set<string>(),\n effects: new Set<string>(),\n };\n\n /** Originals map for assigned definitions */\n const originals = {\n constraints: new Map<string, unknown>(),\n resolvers: new Map<string, unknown>(),\n derivations: new Map<string, unknown>(),\n effects: new Map<string, unknown>(),\n };\n\n /** Deferred registrations queue */\n const deferredRegistrations: DeferredOp[] = [];\n\n /** Validate derivation ID is not a reserved derive method name */\n function validateDerivationId(id: string): void {\n if (RESERVED_DERIVE_NAMES.has(id)) {\n throw new Error(\n `[Directive] Derivation ID \"${id}\" conflicts with a reserved derive method name.`,\n );\n }\n }\n\n /** Per-type dispatch map — eliminates switch statements in apply* functions */\n const typeDescriptors: Record<DefType, TypeDescriptor> = {\n constraint: {\n label: \"Constraint\",\n mergedMap: mergedConstraints as Record<string, unknown>,\n // biome-ignore lint/suspicious/noExplicitAny: Manager type erasure for dispatch map\n manager: constraintsManager as any,\n dynamicSet: dynamicIds.constraints,\n originalsMap: originals.constraints,\n reconciles: true,\n },\n resolver: {\n label: \"Resolver\",\n mergedMap: mergedResolvers as Record<string, unknown>,\n // biome-ignore lint/suspicious/noExplicitAny: Manager type erasure for dispatch map\n manager: resolversManager as any,\n dynamicSet: dynamicIds.resolvers,\n originalsMap: originals.resolvers,\n reconciles: true,\n },\n derivation: {\n label: \"Derivation\",\n mergedMap: mergedDerive as Record<string, unknown>,\n // biome-ignore lint/suspicious/noExplicitAny: Manager type erasure for dispatch map\n manager: derivationsManager as any,\n dynamicSet: dynamicIds.derivations,\n originalsMap: originals.derivations,\n reconciles: false,\n validateId: validateDerivationId,\n },\n effect: {\n label: \"Effect\",\n mergedMap: mergedEffects as Record<string, unknown>,\n // biome-ignore lint/suspicious/noExplicitAny: Manager type erasure for dispatch map\n manager: effectsManager as any,\n dynamicSet: dynamicIds.effects,\n originalsMap: originals.effects,\n reconciles: false,\n },\n };\n\n /** Validate a definition ID for safety */\n function validateDefId(id: string): void {\n if (typeof id !== \"string\" || id.length === 0) {\n throw new Error(\n `[Directive] Definition ID must be a non-empty string. Received: ${String(id)}`,\n );\n }\n if (BLOCKED_PROPS.has(id)) {\n throw new Error(\n `[Directive] Security: Definition ID \"${id}\" is a blocked property.`,\n );\n }\n if (id.includes(\"::\")) {\n throw new Error(\n `[Directive] Definition ID \"${id}\" cannot contain \"::\". This separator is reserved for namespacing.`,\n );\n }\n }\n\n /** Apply a register operation immediately */\n function applyRegister(type: DefType, id: string, def: unknown): void {\n const desc = typeDescriptors[type];\n desc.validateId?.(id);\n\n if (id in desc.mergedMap) {\n throw new Error(\n `[Directive] ${desc.label} \"${id}\" already exists. Use assign() to override.`,\n );\n }\n\n desc.mergedMap[id] = def;\n desc.manager.registerDefinitions({ [id]: def });\n desc.dynamicSet.add(id);\n pluginManager.emitDefinitionRegister(type, id, def);\n\n if (desc.reconciles) {\n scheduleReconcile();\n }\n }\n\n /**\n * Apply an assign operation immediately.\n * Manager's assignDefinition() is called first (may validate/throw).\n * Only on success do we commit the original and update the merged map.\n */\n function applyAssign(type: DefType, id: string, def: unknown): void {\n const desc = typeDescriptors[type];\n desc.validateId?.(id);\n\n if (!(id in desc.mergedMap)) {\n throw new Error(\n `[Directive] ${desc.label} \"${id}\" does not exist. Use register() to create it.`,\n );\n }\n\n const original = desc.mergedMap[id];\n desc.manager.assignDefinition(id, def);\n desc.originalsMap.set(id, original);\n desc.mergedMap[id] = def;\n pluginManager.emitDefinitionAssign(type, id, def, original);\n\n if (desc.reconciles) {\n scheduleReconcile();\n }\n }\n\n /** Apply an unregister operation immediately */\n function applyUnregister(type: DefType, id: string): void {\n const desc = typeDescriptors[type];\n\n if (!desc.dynamicSet.has(id)) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Directive] Cannot unregister static ${type} \"${id}\". Only dynamically registered ${type}s can be removed.`,\n );\n }\n\n return;\n }\n\n desc.manager.unregisterDefinition(id);\n delete desc.mergedMap[id];\n desc.dynamicSet.delete(id);\n desc.originalsMap.delete(id);\n pluginManager.emitDefinitionUnregister(type, id);\n\n if (desc.reconciles) {\n scheduleReconcile();\n }\n }\n\n /** Flush deferred registrations after reconcile settles */\n function flushDeferred(): void {\n if (deferredRegistrations.length === 0) {\n return;\n }\n\n const ops = deferredRegistrations.splice(0);\n for (const op of ops) {\n try {\n switch (op.op) {\n case \"register\":\n applyRegister(op.type, op.id, op.def);\n break;\n case \"assign\":\n applyAssign(op.type, op.id, op.def);\n break;\n case \"unregister\":\n applyUnregister(op.type, op.id);\n break;\n }\n } catch (error) {\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\n `[Directive] Error in deferred ${op.op} for ${op.type} \"${op.id}\":`,\n error,\n );\n }\n }\n }\n }\n\n /** Enforce deferral or destroyed guards, then delegate */\n function guardedOp(\n op: \"register\" | \"assign\" | \"unregister\",\n type: DefType,\n id: string,\n def?: unknown,\n ): void {\n const { isDestroyed, isReconciling } = getState();\n\n if (isDestroyed) {\n throw new Error(\n `[Directive] Cannot ${op} ${type} \"${id}\" on a destroyed system.`,\n );\n }\n\n validateDefId(id);\n\n if (isReconciling) {\n if (deferredRegistrations.length >= maxDeferredRegistrations) {\n throw new Error(\n `[Directive] Too many deferred registrations (max ${maxDeferredRegistrations}). Avoid calling register/assign/unregister in resolver or effect callbacks during reconciliation.`,\n );\n }\n if (op === \"unregister\") {\n deferredRegistrations.push({ op, type, id });\n } else {\n deferredRegistrations.push({ op, type, id, def: def! });\n }\n\n return;\n }\n\n switch (op) {\n case \"register\":\n applyRegister(type, id, def!);\n break;\n case \"assign\":\n applyAssign(type, id, def!);\n break;\n case \"unregister\":\n applyUnregister(type, id);\n break;\n }\n }\n\n return {\n register(type: DefType, id: string, def: unknown) {\n guardedOp(\"register\", type, id, def);\n },\n\n assign(type: DefType, id: string, def: unknown) {\n guardedOp(\"assign\", type, id, def);\n },\n\n unregister(type: DefType, id: string) {\n guardedOp(\"unregister\", type, id);\n },\n\n call(type: DefType, id: string, props?: unknown): unknown {\n const { isDestroyed } = getState();\n if (isDestroyed) {\n throw new Error(\n `[Directive] Cannot call ${type} \"${id}\" on a destroyed system.`,\n );\n }\n\n validateDefId(id);\n pluginManager.emitDefinitionCall(type, id, props);\n\n switch (type) {\n case \"constraint\":\n return constraintsManager.callOne(\n id,\n props as Record<string, unknown> | undefined,\n );\n case \"resolver\":\n return resolversManager.callOne(\n id,\n props as { type: string; [key: string]: unknown },\n );\n case \"derivation\":\n return derivationsManager.callOne(id);\n case \"effect\":\n return effectsManager.callOne(id);\n }\n },\n\n isDynamic(type: DefType, id: string): boolean {\n switch (type) {\n case \"constraint\":\n return dynamicIds.constraints.has(id);\n case \"resolver\":\n return dynamicIds.resolvers.has(id);\n case \"derivation\":\n return dynamicIds.derivations.has(id);\n case \"effect\":\n return dynamicIds.effects.has(id);\n }\n },\n\n listDynamic(type: DefType): string[] {\n switch (type) {\n case \"constraint\":\n return [...dynamicIds.constraints];\n case \"resolver\":\n return [...dynamicIds.resolvers];\n case \"derivation\":\n return [...dynamicIds.derivations];\n case \"effect\":\n return [...dynamicIds.effects];\n }\n },\n\n flushDeferred,\n\n getOriginal(type: DefType, id: string): unknown | undefined {\n const typeMap: Record<string, Map<string, unknown>> = {\n constraint: originals.constraints,\n resolver: originals.resolvers,\n derivation: originals.derivations,\n effect: originals.effects,\n };\n const map = typeMap[type];\n\n if (!map) {\n return undefined;\n }\n\n return map.get(id);\n },\n\n restoreOriginal(type: DefType, id: string): boolean {\n const typeMap: Record<string, Map<string, unknown>> = {\n constraint: originals.constraints,\n resolver: originals.resolvers,\n derivation: originals.derivations,\n effect: originals.effects,\n };\n const map = typeMap[type];\n\n if (!map || !map.has(id)) {\n return false;\n }\n\n const original = map.get(id);\n guardedOp(\"assign\", type, id, original);\n map.delete(id);\n\n return true;\n },\n\n destroy() {\n deferredRegistrations.length = 0;\n dynamicIds.constraints.clear();\n dynamicIds.resolvers.clear();\n dynamicIds.derivations.clear();\n dynamicIds.effects.clear();\n originals.constraints.clear();\n originals.resolvers.clear();\n originals.derivations.clear();\n originals.effects.clear();\n },\n };\n}\n","/**\n * Trace management for the engine reconciliation loop.\n *\n * Extracted from engine.ts to reduce file size. Owns all trace state:\n * ring buffer, per-run entries, resolver attribution maps, anomaly stats,\n * and the cached snapshot array.\n *\n * @internal\n */\n\nimport type { PluginManager } from \"./plugins.js\";\nimport type { Schema, TraceEntry } from \"./types.js\";\n\n// ============================================================================\n// TraceManager Interface\n// ============================================================================\n\n/**\n * Manages per-run reconciliation traces for the engine.\n *\n * @remarks\n * Each reconcile cycle starts a new trace entry that accumulates fact changes,\n * derivation recomputations, constraint hits, requirement diffs, resolver\n * starts/completions/errors, and effect runs. Entries stay \"pending\" while\n * resolvers are inflight and finalize to \"settled\" when all complete.\n *\n * The ring buffer caps at `maxRuns` entries with FIFO eviction. A cached\n * snapshot array avoids re-spreading on every `system.trace` read.\n *\n * @internal\n */\nexport interface TraceManager {\n /** Whether tracing is enabled */\n readonly enabled: boolean;\n\n /**\n * Record a fact change (queued until the next reconcile starts).\n *\n * @param key - The fact key that changed\n * @param oldValue - Previous value\n * @param newValue - New value\n */\n recordFactChange(key: string, oldValue: unknown, newValue: unknown): void;\n\n /**\n * Start a new trace entry for the current reconcile run.\n * Drains pending fact changes into the new entry.\n *\n * @returns The start timestamp (performance.now()) for duration calculation\n */\n startRun(): number;\n\n /** The current in-progress trace entry, or null between reconcile runs */\n currentTrace: TraceEntry | null;\n\n /**\n * Get the cached trace entries array (returns null when tracing is disabled).\n * Re-builds the cache only when the version counter has changed.\n */\n getEntries(): TraceEntry[] | null;\n\n /**\n * Attribute a resolver start to the current trace entry.\n *\n * @param requirementId - The requirement being resolved\n */\n attributeResolverStart(requirementId: string): void;\n\n /**\n * Record a resolver completion on its originating trace entry.\n *\n * @param requirementId - The requirement that was resolved\n * @param resolver - The resolver ID\n * @param duration - Resolution time in ms\n */\n recordResolverComplete(\n requirementId: string,\n resolver: string,\n duration: number,\n ): void;\n\n /**\n * Record a resolver error on its originating trace entry.\n *\n * @param requirementId - The requirement that errored\n * @param resolver - The resolver ID\n * @param error - The error (stringified)\n */\n recordResolverError(\n requirementId: string,\n resolver: string,\n error: string,\n ): void;\n\n /**\n * Decrement inflight count for the trace associated with a requirement.\n * Finalizes the trace entry when all resolvers have settled.\n *\n * @param requirementId - The requirement whose resolver settled\n */\n decrementInflight(requirementId: string): void;\n\n /**\n * Finalize the current trace entry at the end of a reconcile cycle.\n * Determines whether the entry has activity, pushes it to the ring buffer,\n * and either settles immediately or leaves it pending for inflight resolvers.\n *\n * @param reconcileStartMs - The performance.now() timestamp from startRun()\n */\n finalizeCurrentRun(reconcileStartMs: number): void;\n\n /**\n * Drain any pending fact changes (e.g., on reconcile depth overflow).\n */\n drainPendingChanges(): void;\n\n /**\n * Clean up all trace state.\n */\n destroy(): void;\n}\n\n// ============================================================================\n// TraceManager Implementation\n// ============================================================================\n\n/**\n * Options for creating a trace manager.\n *\n * @internal\n */\nexport interface CreateTraceManagerOptions<S extends Schema> {\n /** Trace config from system options (true, object, or falsy) */\n traceConfig: boolean | { maxRuns?: number } | undefined;\n /** Plugin manager for emitting trace lifecycle events */\n pluginManager: PluginManager<S>;\n}\n\n/**\n * Create a trace manager that handles reconciliation trace lifecycle.\n *\n * @remarks\n * When tracing is disabled, returns a no-op manager with zero overhead.\n * When enabled, maintains a ring buffer of trace entries with FIFO eviction,\n * resolver attribution maps, anomaly detection statistics, and a cached\n * snapshot array.\n *\n * @param options - Trace configuration and plugin manager\n * @returns A {@link TraceManager} instance\n *\n * @internal\n */\nexport function createTraceManager<S extends Schema>(\n options: CreateTraceManagerOptions<S>,\n): TraceManager {\n const { traceConfig, pluginManager } = options;\n const enabled =\n traceConfig === true ||\n (typeof traceConfig === \"object\" && traceConfig !== null);\n\n if (!enabled) {\n // Return a no-op manager\n return {\n enabled: false,\n recordFactChange() {},\n startRun() {\n return 0;\n },\n currentTrace: null,\n getEntries() {\n return null;\n },\n attributeResolverStart() {},\n recordResolverComplete() {},\n recordResolverError() {},\n decrementInflight() {},\n finalizeCurrentRun() {},\n drainPendingChanges() {},\n destroy() {},\n };\n }\n\n const maxRuns =\n (typeof traceConfig === \"object\" && traceConfig !== null\n ? traceConfig.maxRuns\n : undefined) ?? 100;\n\n const traceEntries: TraceEntry[] = [];\n const traceById = new Map<number, TraceEntry>();\n let traceIdCounter = 0;\n let currentTrace: TraceEntry | null = null;\n const pendingFactChanges: Array<{\n key: string;\n oldValue: unknown;\n newValue: unknown;\n }> = [];\n\n // Async resolver attribution: requirementId → traceId\n const resolverTraceMap = new Map<string, number>();\n // Track inflight resolvers per trace: traceId → count of pending resolvers\n const traceInflightCount = new Map<number, number>();\n // Consistent duration: track start time per trace (performance.now() based)\n const traceStartMs = new Map<number, number>();\n\n // Cached trace getter: avoid spread on every access\n let traceCache: TraceEntry[] | null = null;\n let traceCacheVersion = 0;\n let currentCacheVersion = 0;\n\n // Anomaly detection statistics\n const traceStats = {\n count: 0,\n totalDuration: 0,\n avgDuration: 0,\n maxDuration: 0,\n avgResolverCount: 0,\n totalResolverCount: 0,\n avgFactChangeCount: 0,\n totalFactChangeCount: 0,\n };\n\n /** Finalize a trace entry when all its resolvers have settled */\n function finalizeTrace(traceId: number): void {\n const entry = traceById.get(traceId);\n if (entry && entry.status === \"pending\") {\n entry.status = \"settled\";\n // Consistent duration: use performance.now() when available\n const startMs = traceStartMs.get(traceId);\n entry.duration =\n startMs !== undefined\n ? performance.now() - startMs\n : Date.now() - entry.timestamp;\n traceStartMs.delete(traceId);\n traceInflightCount.delete(traceId);\n // Build causal chain on settlement\n entry.causalChain = buildCausalChain(entry);\n // Anomaly detection\n updateTraceStats(entry);\n currentCacheVersion++;\n pluginManager.emitTraceComplete(entry);\n }\n }\n\n /** Decrement inflight count for a trace entry and finalize if settled */\n function decrementTraceInflightInternal(requirementId: string): void {\n const traceId = resolverTraceMap.get(requirementId);\n resolverTraceMap.delete(requirementId);\n if (traceId !== undefined) {\n const remaining = (traceInflightCount.get(traceId) ?? 1) - 1;\n if (remaining <= 0) {\n finalizeTrace(traceId);\n } else {\n traceInflightCount.set(traceId, remaining);\n }\n }\n }\n\n /** Evict the oldest trace entry from the ring buffer */\n function evictOldestTrace(): void {\n const evicted = traceEntries.shift();\n if (evicted) {\n traceById.delete(evicted.id);\n traceStartMs.delete(evicted.id);\n if (evicted.status === \"pending\") {\n traceInflightCount.delete(evicted.id);\n for (const [reqId, rId] of resolverTraceMap) {\n if (rId === evicted.id) {\n resolverTraceMap.delete(reqId);\n }\n }\n }\n }\n }\n\n /** Build a human-readable causal chain summary from a trace entry */\n function buildCausalChain(entry: TraceEntry): string {\n const parts: string[] = [];\n\n for (const fc of entry.factChanges) {\n parts.push(`${fc.key} changed`);\n }\n\n for (const d of entry.derivationsRecomputed) {\n parts.push(`${d.id} recomputed`);\n }\n\n for (const c of entry.constraintsHit) {\n parts.push(`${c.id} constraint hit`);\n }\n\n for (const r of entry.requirementsAdded) {\n parts.push(`${r.type} requirement added`);\n }\n\n for (const rs of entry.resolversCompleted) {\n parts.push(`${rs.resolver} resolved (${rs.duration.toFixed(0)}ms)`);\n }\n\n for (const rs of entry.resolversErrored) {\n parts.push(`${rs.resolver} errored`);\n }\n\n for (const e of entry.effectsRun) {\n parts.push(`${e.id} effect ran`);\n }\n\n return parts.join(\" → \");\n }\n\n /** Update running statistics and flag anomalies on a finalized trace entry */\n function updateTraceStats(entry: TraceEntry): void {\n traceStats.count++;\n traceStats.totalDuration += entry.duration;\n traceStats.avgDuration = traceStats.totalDuration / traceStats.count;\n if (entry.duration > traceStats.maxDuration) {\n traceStats.maxDuration = entry.duration;\n }\n\n const resolverCount = entry.resolversStarted.length;\n traceStats.totalResolverCount += resolverCount;\n traceStats.avgResolverCount =\n traceStats.totalResolverCount / traceStats.count;\n\n const factChangeCount = entry.factChanges.length;\n traceStats.totalFactChangeCount += factChangeCount;\n traceStats.avgFactChangeCount =\n traceStats.totalFactChangeCount / traceStats.count;\n\n // Flag anomalies (only after enough data)\n const anomalies: string[] = [];\n if (traceStats.count > 3 && entry.duration > traceStats.avgDuration * 5) {\n anomalies.push(\n `Duration ${entry.duration.toFixed(0)}ms is 5x+ above average (${traceStats.avgDuration.toFixed(0)}ms)`,\n );\n }\n\n if (entry.resolversErrored.length > 0) {\n anomalies.push(`${entry.resolversErrored.length} resolver(s) errored`);\n }\n\n if (anomalies.length > 0) {\n entry.anomalies = anomalies;\n }\n }\n\n /** Push a trace entry to the ring buffer with FIFO eviction */\n function pushTraceEntry(entry: TraceEntry): void {\n traceEntries.push(entry);\n traceById.set(entry.id, entry);\n if (traceEntries.length > maxRuns) {\n evictOldestTrace();\n }\n currentCacheVersion++;\n }\n\n /** Check if a trace entry has any recorded activity */\n function hasTraceActivity(entry: TraceEntry): boolean {\n return (\n entry.factChanges.length > 0 ||\n entry.constraintsHit.length > 0 ||\n entry.requirementsAdded.length > 0 ||\n entry.effectsRun.length > 0\n );\n }\n\n const manager: TraceManager = {\n enabled: true,\n\n get currentTrace() {\n return currentTrace;\n },\n set currentTrace(value: TraceEntry | null) {\n currentTrace = value;\n },\n\n recordFactChange(key: string, oldValue: unknown, newValue: unknown) {\n pendingFactChanges.push({ key, oldValue, newValue });\n },\n\n startRun(): number {\n const startMs = performance.now();\n const traceId = ++traceIdCounter;\n traceStartMs.set(traceId, startMs);\n currentTrace = {\n id: traceId,\n timestamp: Date.now(),\n duration: 0,\n status: \"pending\",\n factChanges: pendingFactChanges.splice(0), // move + clear\n derivationsRecomputed: [],\n constraintsHit: [],\n requirementsAdded: [],\n requirementsRemoved: [],\n resolversStarted: [],\n resolversCompleted: [],\n resolversErrored: [],\n effectsRun: [],\n effectErrors: [],\n };\n\n return startMs;\n },\n\n getEntries(): TraceEntry[] | null {\n if (!traceCache || traceCacheVersion !== currentCacheVersion) {\n traceCache = [...traceEntries];\n traceCacheVersion = currentCacheVersion;\n }\n\n return traceCache;\n },\n\n attributeResolverStart(requirementId: string) {\n if (currentTrace) {\n resolverTraceMap.set(requirementId, currentTrace.id);\n }\n },\n\n recordResolverComplete(\n requirementId: string,\n resolver: string,\n duration: number,\n ) {\n const traceId = resolverTraceMap.get(requirementId);\n if (traceId !== undefined) {\n const entry = traceById.get(traceId);\n if (entry) {\n entry.resolversCompleted.push({\n resolver,\n requirementId,\n duration,\n });\n }\n }\n },\n\n recordResolverError(\n requirementId: string,\n resolver: string,\n error: string,\n ) {\n const traceId = resolverTraceMap.get(requirementId);\n if (traceId !== undefined) {\n const entry = traceById.get(traceId);\n if (entry) {\n entry.resolversErrored.push({\n resolver,\n requirementId,\n error,\n });\n }\n }\n },\n\n decrementInflight(requirementId: string) {\n decrementTraceInflightInternal(requirementId);\n },\n\n finalizeCurrentRun(reconcileStartMs: number) {\n if (!currentTrace) {\n return;\n }\n\n currentTrace.duration = performance.now() - reconcileStartMs;\n\n if (!hasTraceActivity(currentTrace)) {\n // Empty trace entry — clean up start time\n traceStartMs.delete(currentTrace.id);\n currentTrace = null;\n\n return;\n }\n\n const inflightCount = currentTrace.resolversStarted.length;\n if (inflightCount === 0) {\n // No resolvers — finalize immediately\n currentTrace.status = \"settled\";\n currentTrace.causalChain = buildCausalChain(currentTrace);\n updateTraceStats(currentTrace);\n pushTraceEntry(currentTrace);\n pluginManager.emitTraceComplete(currentTrace);\n } else {\n // Has resolvers — stays pending until they settle\n currentTrace.status = \"pending\";\n pushTraceEntry(currentTrace);\n traceInflightCount.set(currentTrace.id, inflightCount);\n }\n\n currentTrace = null;\n },\n\n drainPendingChanges() {\n pendingFactChanges.length = 0;\n },\n\n destroy() {\n traceEntries.length = 0;\n traceById.clear();\n resolverTraceMap.clear();\n traceInflightCount.clear();\n traceStartMs.clear();\n pendingFactChanges.length = 0;\n currentTrace = null;\n traceCache = null;\n },\n };\n\n return manager;\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 {\n type HistoryManager,\n createDisabledHistory,\n createHistoryManager,\n} from \"../utils/history.js\";\nimport { hashObject, isPrototypeSafe } from \"../utils/utils.js\";\nimport {\n type ConstraintsManager,\n createConstraintsManager,\n} from \"./constraints.js\";\nimport {\n type DerivationsManager,\n createDerivationsManager,\n} from \"./derivations.js\";\nimport { type EffectsManager, createEffectsManager } from \"./effects.js\";\nimport {\n createDeriveAccessor,\n createEventsAccessor,\n} from \"./engine-accessors.js\";\nimport { createDefinitionsRegistry } from \"./engine-definitions.js\";\nimport { createTraceManager } from \"./engine-trace.js\";\nimport {\n type ErrorBoundaryManager,\n createErrorBoundaryManager,\n} from \"./errors.js\";\nimport { createFacts } from \"./facts.js\";\nimport { type PluginManager, createPluginManager } from \"./plugins.js\";\nimport { RequirementSet } from \"./requirements.js\";\nimport { type ResolversManager, createResolversManager } from \"./resolvers.js\";\nimport { BLOCKED_PROPS } from \"./tracking.js\";\nimport type {\n ConstraintsDef,\n DerivationsDef,\n EffectsDef,\n EventsDef,\n FactsSnapshot,\n InferSchema,\n ReconcileResult,\n RequirementKeyFn,\n ResolversDef,\n Schema,\n System,\n SystemConfig,\n SystemEvent,\n SystemInspection,\n TraceEntry,\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 isRunning: boolean;\n isReconciling: boolean;\n reconcileScheduled: boolean;\n isInitializing: boolean;\n isInitialized: boolean;\n isReady: boolean;\n isDestroyed: boolean;\n changedKeys: Set<string>;\n previousRequirements: RequirementSet;\n readyPromise: Promise<void> | null;\n readyResolve: (() => void) | null;\n}\n\n/**\n * Create the core Directive reconciliation engine that wires facts, derivations,\n * effects, constraints, resolvers, plugins, error boundaries, and history\n * into a single reactive system.\n *\n * @remarks\n * This is the internal factory used by {@link createSystem}. Most users should\n * call `createSystem` instead, which provides a friendlier API and handles\n * module composition.\n *\n * @param config - Full system configuration including modules, plugins, error boundary settings, and debug options\n * @returns A {@link 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 * @internal\n */\n// biome-ignore lint/suspicious/noExplicitAny: Engine uses flat schema internally, public API uses ModuleSchema\nexport function createEngine<S extends Schema>(\n config: SystemConfig<any>,\n): System<any> {\n // Merge all module definitions with collision detection\n // Use Object.create(null) to prevent prototype chain traversal (e.g., \"toString\" in mergedEvents)\n const mergedSchema = Object.create(null) as S;\n const mergedEvents: EventsDef<S> = Object.create(null);\n const mergedDerive: DerivationsDef<S> = Object.create(null);\n const mergedEffects: EffectsDef<S> = Object.create(null);\n const mergedConstraints: ConstraintsDef<S> = Object.create(null);\n const mergedResolvers: ResolversDef<S> = Object.create(null);\n\n // Track which module defined each key for collision detection\n const schemaOwners = new Map<string, string>();\n const definitionOwners = new Map<string, string>();\n\n for (const module of config.modules) {\n // Security: Validate module definitions for dangerous keys\n // Always run in all environments — this is a security boundary, not a dev convenience\n const validateKeys = (obj: object | undefined, section: string) => {\n if (!obj) return;\n for (const key of Object.keys(obj)) {\n if (BLOCKED_PROPS.has(key)) {\n throw new Error(\n `[Directive] Security: Module \"${module.id}\" has dangerous key \"${key}\" in ${section}. ` +\n \"This could indicate a prototype pollution attempt.\",\n );\n }\n if (section === \"schema\" && key.startsWith(\"$\")) {\n throw new Error(\n `[Directive] Module \"${module.id}\" has schema key \"${key}\" starting with \"$\". ` +\n \"Keys starting with $ are reserved for internal accessors ($store, $snapshot).\",\n );\n }\n }\n };\n validateKeys(module.schema, \"schema\");\n validateKeys(module.events, \"events\");\n validateKeys(module.derive, \"derive\");\n validateKeys(module.effects, \"effects\");\n validateKeys(module.constraints, \"constraints\");\n validateKeys(module.resolvers, \"resolvers\");\n\n // Check for schema collisions (unconditional — data integrity, not dev convenience)\n for (const key of Object.keys(module.schema)) {\n const existingOwner = schemaOwners.get(key);\n if (existingOwner) {\n throw new Error(\n `[Directive] Schema collision: Fact \"${key}\" is defined in both module \"${existingOwner}\" and \"${module.id}\". ` +\n `Use namespacing (e.g., \"${module.id}::${key}\") or merge into one module.`,\n );\n }\n schemaOwners.set(key, module.id);\n }\n\n // Check for definition collisions across modules (derive, effects, constraints, resolvers)\n const checkCollisions = (obj: object | undefined, section: string) => {\n if (!obj) {\n return;\n }\n for (const key of Object.keys(obj)) {\n const owner = definitionOwners.get(key);\n if (owner && owner !== module.id) {\n throw new Error(\n `[Directive] Definition collision: ${section} \"${key}\" is defined in both module \"${owner}\" and \"${module.id}\". ` +\n \"Use namespacing or rename to avoid conflicts.\",\n );\n }\n definitionOwners.set(key, module.id);\n }\n };\n checkCollisions(module.derive, \"derivation\");\n checkCollisions(module.effects, \"effect\");\n checkCollisions(module.constraints, \"constraint\");\n checkCollisions(module.resolvers, \"resolver\");\n checkCollisions(module.events, \"event\");\n\n Object.assign(mergedSchema, module.schema);\n if (module.events) Object.assign(mergedEvents, module.events);\n if (module.derive) Object.assign(mergedDerive, module.derive);\n if (module.effects) Object.assign(mergedEffects, module.effects);\n if (module.constraints)\n Object.assign(mergedConstraints, module.constraints);\n if (module.resolvers) Object.assign(mergedResolvers, module.resolvers);\n }\n\n // Build snapshotEventNames: Set<string> | null\n // If any module declares history.snapshotEvents, build the filter set.\n // Modules WITHOUT history.snapshotEvents have all their events added (they still snapshot).\n let snapshotEventNames: Set<string> | null = null;\n // biome-ignore lint/suspicious/noExplicitAny: Module may have history.snapshotEvents at runtime\n const hasAnySnapshotEvents = config.modules.some(\n (m: any) => m.history?.snapshotEvents,\n );\n if (hasAnySnapshotEvents) {\n snapshotEventNames = new Set<string>();\n for (const module of config.modules) {\n // biome-ignore lint/suspicious/noExplicitAny: Module may have history.snapshotEvents at runtime\n const mod = module as any;\n if (mod.history?.snapshotEvents) {\n for (const eventName of mod.history.snapshotEvents) {\n snapshotEventNames.add(eventName);\n }\n } else if (mod.events) {\n // No filter — all events from this module create snapshots\n for (const eventName of Object.keys(mod.events)) {\n snapshotEventNames.add(eventName);\n }\n }\n }\n }\n\n // Snapshot intent flags — track whether the current change batch should create a snapshot\n let dispatchDepth = 0;\n let shouldTakeSnapshot = false;\n\n // Dev-mode: Warn if a fact and derivation share the same name\n if (process.env.NODE_ENV !== \"production\") {\n const derivationNames = new Set(Object.keys(mergedDerive));\n for (const key of Object.keys(mergedSchema)) {\n if (derivationNames.has(key)) {\n console.warn(\n `[Directive] \"${key}\" exists as both a fact and a derivation. ` +\n \"This may cause unexpected dependency tracking behavior.\",\n );\n }\n }\n }\n\n // Create plugin manager\n const pluginManager: PluginManager<S> = createPluginManager();\n for (const plugin of config.plugins ?? []) {\n pluginManager.register(plugin);\n }\n\n // Create error boundary\n const errorBoundary: ErrorBoundaryManager = createErrorBoundaryManager({\n config: config.errorBoundary,\n onError: (error) => pluginManager.emitError(error),\n onRecovery: (error, strategy) =>\n pluginManager.emitErrorRecovery(error, strategy),\n });\n\n // Retry-later polling timer\n let retryLaterTimer: ReturnType<typeof setInterval> | null = null;\n\n // Create facts store and proxy\n // Note: We need to create a local invalidate function that will be set after derivationsManager is created\n let invalidateDerivation: (key: string) => void = () => {};\n let invalidateManyDerivations: (keys: string[]) => void = () => {};\n\n // Forward-declared so onChange/onBatch closures can check isRestoring.\n // Assigned after createHistoryManager() below.\n let historyRef: HistoryManager<S> | null = null;\n\n // Trace management (per-run reconciliation changelog, gated by config.trace)\n const traceManager = createTraceManager({\n traceConfig: config.trace,\n pluginManager,\n });\n const traceEnabled = traceManager.enabled;\n\n const { store, facts } = createFacts<S>({\n schema: mergedSchema,\n onChange: (key, value, prev) => {\n pluginManager.emitFactSet(key, value, prev);\n // Invalidate derivations so they recompute on read\n invalidateDerivation(key);\n // Track fact changes for trace\n if (traceEnabled) {\n traceManager.recordFactChange(String(key), prev, value);\n }\n // During history restore, skip change tracking and reconciliation.\n // The restored state is already reconciled; re-reconciling would create\n // spurious snapshots that break undo/redo.\n if (historyRef?.isRestoring) return;\n // Direct fact mutations (outside event dispatch) always create snapshots\n if (dispatchDepth === 0) {\n shouldTakeSnapshot = true;\n }\n state.changedKeys.add(key);\n scheduleReconcile();\n },\n onBatch: (changes) => {\n pluginManager.emitFactsBatch(changes);\n const keys: string[] = [];\n for (const change of changes) {\n keys.push(change.key);\n }\n // Track fact changes for trace\n if (traceEnabled) {\n for (const change of changes) {\n traceManager.recordFactChange(\n change.key,\n change.prev,\n change.type === \"delete\" ? undefined : change.value,\n );\n }\n }\n // Invalidate all affected derivations at once — listeners fire only\n // after ALL keys are invalidated, so they see consistent state.\n invalidateManyDerivations(keys);\n // During history restore, skip change tracking and reconciliation.\n if (historyRef?.isRestoring) return;\n // Resolver/effect batches (outside event dispatch) always create snapshots\n if (dispatchDepth === 0) {\n shouldTakeSnapshot = true;\n }\n for (const change of changes) {\n state.changedKeys.add(change.key);\n }\n scheduleReconcile();\n },\n });\n\n // Create derivations manager\n const derivationsManager: DerivationsManager<\n S,\n DerivationsDef<S>\n > = createDerivationsManager({\n definitions: mergedDerive,\n facts,\n onCompute: (id, value, oldValue, deps) => {\n pluginManager.emitDerivationCompute(id, value, deps);\n if (traceManager.currentTrace) {\n traceManager.currentTrace.derivationsRecomputed.push({\n id,\n deps: deps ? [...deps] : [],\n oldValue,\n newValue: value,\n });\n }\n },\n onInvalidate: (id) => pluginManager.emitDerivationInvalidate(id),\n onError: (id, error) => {\n const strategy = errorBoundary.handleError(\"derivation\", id, error);\n\n if (strategy === \"retry\") {\n derivationsManager.invalidate(id);\n }\n },\n });\n\n // Now wire up derivation invalidation\n invalidateDerivation = (key: string) => derivationsManager.invalidate(key);\n invalidateManyDerivations = (keys: string[]) =>\n derivationsManager.invalidateMany(keys);\n\n // Create effects manager\n const effectsManager: EffectsManager<S> = createEffectsManager({\n definitions: mergedEffects,\n facts,\n store,\n onRun: (id, deps) => {\n pluginManager.emitEffectRun(id);\n if (traceManager.currentTrace) {\n traceManager.currentTrace.effectsRun.push({\n id,\n triggeredBy: deps,\n });\n }\n },\n onError: (id, error) => {\n const strategy = errorBoundary.handleError(\"effect\", id, error);\n pluginManager.emitEffectError(id, error);\n\n if (traceManager.currentTrace) {\n traceManager.currentTrace.effectErrors.push({\n id,\n error: String(error),\n });\n }\n\n if (strategy === \"disable\") {\n effectsManager.disable(id);\n }\n\n if (strategy === \"retry\") {\n state.changedKeys.add(\"*\");\n scheduleReconcile();\n }\n },\n });\n\n // Extract resolver key functions keyed by requirement type.\n // Resolvers with a string `requirement` and a `key` function contribute\n // to requirement deduplication inside the constraints manager.\n const requirementKeys: Record<string, RequirementKeyFn> = Object.create(null);\n for (const def of Object.values(mergedResolvers)) {\n if (\n def.key &&\n typeof def.requirement === \"string\"\n ) {\n requirementKeys[def.requirement] = def.key;\n }\n }\n\n // Create constraints manager\n const constraintsManager: ConstraintsManager<S> = createConstraintsManager({\n definitions: mergedConstraints,\n facts,\n requirementKeys,\n onEvaluate: (id, active) =>\n pluginManager.emitConstraintEvaluate(id, active),\n onError: (id, error) => {\n const strategy = errorBoundary.handleError(\"constraint\", id, error);\n pluginManager.emitConstraintError(id, error);\n\n if (strategy === \"disable\") {\n constraintsManager.disable(id);\n }\n },\n });\n\n /** Sync resolver key functions into the constraints manager */\n function syncResolverKeys(defs: ResolversDef<S>): void {\n for (const def of Object.values(defs)) {\n if (def.key && typeof def.requirement === \"string\") {\n constraintsManager.setRequirementKey(def.requirement, def.key);\n }\n }\n }\n\n // Create resolvers manager\n const resolversManager: ResolversManager<S> = createResolversManager({\n definitions: mergedResolvers,\n facts,\n store,\n onStart: (resolver, req) => pluginManager.emitResolverStart(resolver, req),\n onComplete: (resolver, req, duration) => {\n errorBoundary.clearRetryAttempts(resolver);\n pluginManager.emitResolverComplete(resolver, req, duration);\n pluginManager.emitRequirementMet(req, resolver);\n // Mark the constraint as resolved for `after` ordering\n constraintsManager.markResolved(req.fromConstraint);\n // Attribute to the trace entry that started this resolver\n if (traceEnabled) {\n traceManager.recordResolverComplete(req.id, resolver, duration);\n traceManager.decrementInflight(req.id);\n }\n },\n onError: (resolver, req, error) => {\n const strategy = errorBoundary.handleError(\n \"resolver\",\n resolver,\n error,\n req,\n );\n pluginManager.emitResolverError(resolver, req, error);\n\n if (strategy === \"disable\") {\n constraintsManager.disable(req.fromConstraint);\n }\n\n if (strategy === \"retry\") {\n // Remove from previousRequirements so the diff sees it as \"added\" again\n state.previousRequirements.remove(req.id);\n scheduleReconcile();\n }\n\n if (strategy === \"retry-later\") {\n const pending = errorBoundary\n .getRetryLaterManager()\n .getPendingRetries();\n const entry = pending.find((p) => p.sourceId === resolver);\n\n if (entry && !entry.callback) {\n entry.callback = () => {\n scheduleReconcile();\n };\n }\n }\n\n // Attribute error to the trace entry that started this resolver\n if (traceEnabled) {\n traceManager.recordResolverError(req.id, resolver, String(error));\n traceManager.decrementInflight(req.id);\n }\n },\n onRetry: (resolver, req, attempt) =>\n pluginManager.emitResolverRetry(resolver, req, attempt),\n onCancel: (resolver, req) => {\n pluginManager.emitResolverCancel(resolver, req);\n pluginManager.emitRequirementCanceled(req);\n // Decrement inflight for the trace entry\n if (traceEnabled) {\n traceManager.decrementInflight(req.id);\n }\n },\n onResolutionComplete: () => {\n // After a resolver completes, schedule another reconcile\n notifySettlementChange();\n scheduleReconcile();\n },\n });\n\n // History listeners — notified when snapshot state changes\n const historyListeners = new Set<() => void>();\n\n function notifyHistoryChange(): void {\n for (const listener of historyListeners) {\n listener();\n }\n }\n\n // Create history manager\n const historyManager: HistoryManager<S> = config.history\n ? createHistoryManager({\n historyOption: config.history,\n facts,\n store,\n onSnapshot: (snapshot) => {\n pluginManager.emitSnapshot(snapshot);\n notifyHistoryChange();\n },\n onHistoryChange: (from, to) => {\n pluginManager.emitHistoryNavigate(from, to);\n notifyHistoryChange();\n },\n })\n : createDisabledHistory();\n historyRef = historyManager;\n\n // Settlement listeners — notified when isSettled may have changed\n const settlementListeners = new Set<() => void>();\n\n function notifySettlementChange(): void {\n for (const listener of settlementListeners) {\n listener();\n }\n }\n\n // Reconcile depth guard — prevents runaway reconcile → scheduleReconcile chains\n const MAX_RECONCILE_DEPTH = 50;\n const MAX_DEFERRED_REGISTRATIONS = 100;\n let reconcileDepth = 0;\n\n // Engine state\n const state: EngineState<S> = {\n isRunning: false,\n isReconciling: false,\n reconcileScheduled: false,\n isInitializing: false,\n isInitialized: false,\n isReady: false,\n isDestroyed: false,\n changedKeys: new Set(),\n previousRequirements: new RequirementSet(),\n readyPromise: null,\n readyResolve: null,\n };\n\n // Dynamic definition registry (register, assign, unregister, call)\n const definitions = createDefinitionsRegistry({\n mergedConstraints,\n mergedResolvers,\n mergedDerive,\n mergedEffects,\n constraintsManager,\n resolversManager,\n derivationsManager,\n effectsManager,\n pluginManager,\n getState: () => state,\n scheduleReconcile,\n maxDeferredRegistrations: MAX_DEFERRED_REGISTRATIONS,\n });\n\n /** Schedule a reconciliation on the next microtask */\n function scheduleReconcile(): void {\n // Suppress reconciliation during initialization phase\n if (!state.isRunning || state.reconcileScheduled || state.isInitializing)\n return;\n\n state.reconcileScheduled = true;\n notifySettlementChange();\n queueMicrotask(() => {\n state.reconcileScheduled = false;\n if (state.isRunning && !state.isInitializing) {\n // Await reconcile to prevent race conditions\n // Error is caught inside reconcile, so no need to handle here\n reconcile().catch((error) => {\n // Only log unexpected errors (reconcile handles its own errors)\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\"[Directive] Unexpected error in reconcile:\", error);\n }\n });\n }\n });\n }\n\n /** The main reconciliation loop */\n async function reconcile(): Promise<void> {\n if (state.isReconciling) return;\n\n reconcileDepth++;\n if (reconcileDepth > MAX_RECONCILE_DEPTH) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Directive] Reconcile loop exceeded ${MAX_RECONCILE_DEPTH} iterations. ` +\n \"This usually means resolvers are creating circular requirement chains. \" +\n `Check that resolvers aren't mutating facts that re-trigger their own constraints.`,\n );\n }\n // Drain pending fact changes so they don't leak into the next trace entry (M4)\n if (traceEnabled) {\n traceManager.drainPendingChanges();\n }\n // Clear previous requirements so the next reconcile treats all\n // requirements as \"added\" and re-dispatches them to resolvers.\n // This recovers from situations where reconcile crashed (e.g.,\n // structuredClone failure) and left requirements stuck.\n state.previousRequirements = new RequirementSet();\n reconcileDepth = 0;\n return;\n }\n\n state.isReconciling = true;\n notifySettlementChange();\n\n const reconcileStartMs = traceEnabled ? traceManager.startRun() : 0;\n const currentTrace = traceManager.currentTrace;\n\n try {\n // Take snapshot before reconciliation (respects snapshotEvents filtering)\n if (state.changedKeys.size > 0) {\n if (snapshotEventNames === null || shouldTakeSnapshot) {\n const keys = state.changedKeys;\n const label =\n keys.size <= 5\n ? `facts-changed:${[...keys].join(\",\")}`\n : `facts-changed:${[...keys].slice(0, 5).join(\",\")}+${keys.size - 5}more`;\n historyManager.takeSnapshot(label);\n }\n shouldTakeSnapshot = false;\n }\n\n // Get snapshot for plugins\n const snapshot = facts.$snapshot() as FactsSnapshot<S>;\n pluginManager.emitReconcileStart(snapshot);\n\n // Note: Derivations are already invalidated immediately when facts change\n // (in the onChange/onBatch callbacks), so we don't need to do it here\n\n // Run effects for changed keys\n await effectsManager.runEffects(state.changedKeys);\n\n // Copy changed keys for constraint evaluation before clearing\n const keysForConstraints = new Set(state.changedKeys);\n\n // Clear changed keys\n state.changedKeys.clear();\n\n // Evaluate constraints (pass changed keys for incremental evaluation)\n const currentRequirements =\n await constraintsManager.evaluate(keysForConstraints);\n const currentSet = new RequirementSet();\n for (const req of currentRequirements) {\n currentSet.add(req);\n pluginManager.emitRequirementCreated(req);\n }\n\n // Capture which constraints produced requirements for trace\n if (currentTrace) {\n const hitConstraintIds = new Set(\n currentRequirements.map((r) => r.fromConstraint),\n );\n for (const cId of hitConstraintIds) {\n const cState = constraintsManager.getState(cId);\n if (cState) {\n const cDeps = constraintsManager.getDependencies(cId);\n currentTrace.constraintsHit.push({\n id: cId,\n priority: cState.priority,\n deps: cDeps ? [...cDeps] : [],\n });\n }\n }\n }\n\n // Diff with previous requirements\n const { added, removed } = currentSet.diff(state.previousRequirements);\n\n // Capture requirement diff for trace\n if (currentTrace) {\n for (const req of added) {\n currentTrace.requirementsAdded.push({\n id: req.id,\n type: req.requirement.type,\n fromConstraint: req.fromConstraint,\n });\n }\n for (const req of removed) {\n currentTrace.requirementsRemoved.push({\n id: req.id,\n type: req.requirement.type,\n fromConstraint: req.fromConstraint,\n });\n }\n }\n\n // Cancel resolvers for removed requirements\n for (const req of removed) {\n resolversManager.cancel(req.id);\n }\n\n // Start resolvers for new requirements\n for (const req of added) {\n resolversManager.resolve(req);\n }\n\n // Capture resolver starts for trace\n if (currentTrace) {\n const inflightNow = resolversManager.getInflightInfo();\n // Build Map for O(1) lookups instead of O(n) find per requirement\n const inflightById = new Map(inflightNow.map((i) => [i.id, i]));\n for (const req of added) {\n const info = inflightById.get(req.id);\n currentTrace.resolversStarted.push({\n resolver: info?.resolverId ?? \"unknown\",\n requirementId: req.id,\n });\n // Track attribution for async completion\n traceManager.attributeResolverStart(req.id);\n }\n }\n\n // Update previous requirements\n state.previousRequirements = currentSet;\n\n // Build reconcile result (only if plugins are listening)\n const inflightInfo = resolversManager.getInflightInfo();\n if (config.plugins && config.plugins.length > 0) {\n // Build Map for O(1) lookups on canceled requirements\n const inflightMap =\n removed.length > 0\n ? new Map(inflightInfo.map((i) => [i.id, i.resolverId]))\n : undefined;\n const result: ReconcileResult = {\n unmet: currentRequirements.filter(\n (r) => !resolversManager.isResolving(r.id),\n ),\n inflight: inflightInfo,\n completed: [], // Completed resolvers are tracked separately via onComplete callback\n canceled: removed.map((r) => ({\n id: r.id,\n resolverId: inflightMap?.get(r.id) ?? \"unknown\",\n })),\n };\n pluginManager.emitReconcileEnd(result);\n }\n\n // Mark system as ready after first successful reconcile\n if (!state.isReady) {\n state.isReady = true;\n if (state.readyResolve) {\n state.readyResolve();\n state.readyResolve = null;\n }\n }\n } finally {\n // Finalize the current trace entry\n if (traceEnabled) {\n traceManager.finalizeCurrentRun(reconcileStartMs);\n }\n\n state.isReconciling = false;\n\n // Flush any deferred dynamic definition operations that were queued\n // during this reconciliation cycle\n definitions.flushDeferred();\n\n // Schedule next reconcile BEFORE notifying settlement change,\n // so listeners never see a brief isSettled=true flash when\n // more changes are pending.\n // Reset depth counter at the end of each top-level reconcile.\n // Previously only reset on full settlement, which allowed depth\n // to climb toward MAX in long-running systems with continuous changes.\n reconcileDepth = 0;\n\n if (state.changedKeys.size > 0) {\n scheduleReconcile();\n }\n\n notifySettlementChange();\n }\n }\n\n /** Dispatch an event by name, handling snapshot flags and batching */\n function dispatchEventByName(\n eventName: string,\n payload?: Record<string, unknown>,\n ): void {\n const handler = mergedEvents[eventName];\n if (handler) {\n dispatchDepth++;\n if (snapshotEventNames === null || snapshotEventNames.has(eventName)) {\n shouldTakeSnapshot = true;\n }\n try {\n store.batch(() => {\n handler(facts, { type: eventName, ...payload });\n });\n } finally {\n dispatchDepth--;\n }\n } else if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Directive] Unknown event type \"${eventName}\". ` +\n \"No handler is registered for this event. \" +\n `Available events: ${Object.keys(mergedEvents).join(\", \") || \"(none)\"}`,\n );\n }\n }\n\n // Create typed derive accessor using a Proxy\n const deriveAccessor = createDeriveAccessor({\n mergedDerive: mergedDerive as Record<string, unknown>,\n getDerivation: (key) =>\n derivationsManager.get(key as keyof DerivationsDef<S>),\n definitions,\n });\n\n // Create typed events accessor using a Proxy\n const eventsAccessor = createEventsAccessor({\n mergedEvents: mergedEvents as Record<string, unknown>,\n dispatchEvent: dispatchEventByName,\n });\n\n // Create the system interface\n // biome-ignore lint/suspicious/noExplicitAny: Engine uses flat schema internally, public API uses ModuleSchema\n const system: System<any> = {\n facts,\n history: historyManager.isEnabled ? historyManager : null,\n // biome-ignore lint/suspicious/noExplicitAny: Proxy provides both derivation values and control methods at runtime\n derive: deriveAccessor as any,\n events: eventsAccessor,\n constraints: {\n disable: (id: string) => constraintsManager.disable(id),\n enable: (id: string) => constraintsManager.enable(id),\n isDisabled: (id: string) => constraintsManager.isDisabled(id),\n // biome-ignore lint/suspicious/noExplicitAny: Runtime accepts any constraint def shape\n register: (id: string, def: any) => {\n definitions.register(\"constraint\", id, def);\n },\n // biome-ignore lint/suspicious/noExplicitAny: Runtime accepts any constraint def shape\n assign: (id: string, def: any) => {\n definitions.assign(\"constraint\", id, def);\n },\n unregister: (id: string) => {\n definitions.unregister(\"constraint\", id);\n },\n call: (id: string, props?: Record<string, unknown>) =>\n definitions.call(\"constraint\", id, props) as Promise<\n Record<string, unknown>[]\n >,\n isDynamic: (id: string) => definitions.isDynamic(\"constraint\", id),\n listDynamic: () => definitions.listDynamic(\"constraint\"),\n },\n effects: {\n disable: (id: string) => effectsManager.disable(id),\n enable: (id: string) => effectsManager.enable(id),\n isEnabled: (id: string) => effectsManager.isEnabled(id),\n // biome-ignore lint/suspicious/noExplicitAny: Runtime accepts any effect def shape\n register: (id: string, def: any) => {\n definitions.register(\"effect\", id, def);\n },\n // biome-ignore lint/suspicious/noExplicitAny: Runtime accepts any effect def shape\n assign: (id: string, def: any) => {\n definitions.assign(\"effect\", id, def);\n },\n unregister: (id: string) => {\n definitions.unregister(\"effect\", id);\n },\n call: (id: string) => definitions.call(\"effect\", id) as Promise<void>,\n isDynamic: (id: string) => definitions.isDynamic(\"effect\", id),\n listDynamic: () => definitions.listDynamic(\"effect\"),\n },\n resolvers: {\n // biome-ignore lint/suspicious/noExplicitAny: Runtime accepts any resolver def shape\n register: (id: string, def: any) => {\n definitions.register(\"resolver\", id, def);\n syncResolverKeys({ [id]: def } as ResolversDef<S>);\n },\n // biome-ignore lint/suspicious/noExplicitAny: Runtime accepts any resolver def shape\n assign: (id: string, def: any) => {\n definitions.assign(\"resolver\", id, def);\n syncResolverKeys({ [id]: def } as ResolversDef<S>);\n },\n unregister: (id: string) => {\n // Remove the key function before unregistering\n const def = mergedResolvers[id];\n if (def?.key && typeof def.requirement === \"string\") {\n constraintsManager.removeRequirementKey(def.requirement);\n }\n definitions.unregister(\"resolver\", id);\n },\n call: (\n id: string,\n requirement: { type: string; [key: string]: unknown },\n ) => definitions.call(\"resolver\", id, requirement) as Promise<void>,\n isDynamic: (id: string) => definitions.isDynamic(\"resolver\", id),\n listDynamic: () => definitions.listDynamic(\"resolver\"),\n },\n\n get trace(): TraceEntry[] | null {\n return traceManager.getEntries();\n },\n\n initialize(): void {\n if (state.isInitialized) return;\n state.isInitializing = true;\n\n // Run module init functions (sets initial fact values)\n for (const module of config.modules) {\n if (module.init) {\n store.batch(() => {\n // biome-ignore lint/suspicious/noExplicitAny: Engine internal type coercion\n module.init!(facts as any);\n });\n }\n }\n\n // Apply initialFacts/hydrate via callback\n // This ensures initialFacts are applied AFTER module init but BEFORE reconcile\n if (config.onAfterModuleInit) {\n store.batch(() => {\n config.onAfterModuleInit!();\n });\n }\n\n state.isInitializing = false;\n state.isInitialized = true;\n\n // Eagerly compute all derivations so they're cached before any\n // external read (e.g. React's useSyncExternalStore). Without this,\n // derivations can evaluate against uninitialized facts.\n for (const id of Object.keys(mergedDerive)) {\n derivationsManager.get(id as keyof DerivationsDef<S>);\n }\n },\n\n start(): void {\n if (state.isRunning) return;\n\n // Ensure facts are initialized (no-op if already called)\n if (!state.isInitialized) {\n this.initialize();\n }\n\n state.isRunning = true;\n\n // Module onStart hooks (may access browser APIs — only in start())\n for (const module of config.modules) {\n // biome-ignore lint/suspicious/noExplicitAny: Engine internal type coercion\n module.hooks?.onStart?.(system as any);\n }\n\n // Emit start event\n pluginManager.emitStart(system);\n\n // Start retry-later polling timer if configured\n if (config.errorBoundary?.retryLater && !retryLaterTimer) {\n const intervalMs = Math.max(\n config.errorBoundary.retryLater.delayMs ?? 1000,\n 250,\n );\n\n retryLaterTimer = setInterval(\n () => {\n const dueRetries = errorBoundary.processDueRetries();\n\n for (const entry of dueRetries) {\n if (entry.callback) {\n entry.callback();\n } else {\n scheduleReconcile();\n }\n }\n },\n Math.min(intervalMs, 500),\n );\n }\n\n // Initial reconcile (now that all modules are initialized)\n scheduleReconcile();\n },\n\n stop(): void {\n if (!state.isRunning) return;\n state.isRunning = false;\n\n // Stop retry-later timer\n if (retryLaterTimer !== null) {\n clearInterval(retryLaterTimer);\n retryLaterTimer = null;\n }\n errorBoundary.getRetryLaterManager().clearAll();\n\n // Cancel all resolvers\n resolversManager.cancelAll();\n\n // Run all effect cleanups\n effectsManager.cleanupAll();\n\n // Call module hooks\n for (const module of config.modules) {\n module.hooks?.onStop?.(system);\n }\n\n // Emit stop event\n pluginManager.emitStop(system);\n },\n\n destroy(): void {\n if (state.isDestroyed) return;\n this.stop();\n state.isDestroyed = true;\n // Clean up store listeners\n (store as unknown as Record<string, () => void>).destroy?.();\n // Clean up resolvers (statuses, caches)\n resolversManager.destroy();\n // Clean up error boundary\n errorBoundary.clearErrors();\n settlementListeners.clear();\n historyListeners.clear();\n // Clean up trace state (C1)\n traceManager.destroy();\n // Clean up dynamic definition state\n definitions.destroy();\n pluginManager.emitDestroy(system);\n },\n\n dispatch(event: SystemEvent): void {\n if (BLOCKED_PROPS.has(event.type)) return;\n dispatchEventByName(event.type, event as Record<string, unknown>);\n },\n\n read<T = unknown>(derivationId: string): T {\n return derivationsManager.get(\n derivationId as keyof DerivationsDef<S>,\n ) as T;\n },\n\n subscribe(ids: string[], listener: () => void): () => void {\n const derivationIds: string[] = [];\n const factKeys: string[] = [];\n\n for (const id of ids) {\n if (id in mergedDerive) {\n derivationIds.push(id);\n } else if (id in mergedSchema) {\n factKeys.push(id);\n } else if (process.env.NODE_ENV !== \"production\") {\n console.warn(`[Directive] subscribe: unknown key \"${id}\"`);\n }\n }\n\n const unsubs: Array<() => void> = [];\n if (derivationIds.length > 0) {\n unsubs.push(\n derivationsManager.subscribe(\n derivationIds as Array<keyof DerivationsDef<S>>,\n listener,\n ),\n );\n }\n if (factKeys.length > 0) {\n unsubs.push(\n store.subscribe(factKeys as Array<keyof InferSchema<S>>, listener),\n );\n }\n\n return () => {\n for (const u of unsubs) u();\n };\n },\n\n watch<T = unknown>(\n id: string,\n callback: (newValue: T, previousValue: T | undefined) => void,\n options?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n ): () => void {\n const isEqual = options?.equalityFn\n ? (a: T, b: T | undefined) => options.equalityFn!(a, b)\n : (a: T, b: T | undefined) => Object.is(a, b);\n\n if (id in mergedDerive) {\n // Derivation path\n let previousValue: T | undefined = derivationsManager.get(\n id as keyof DerivationsDef<S>,\n ) as T | undefined;\n\n return derivationsManager.subscribe(\n [id as keyof DerivationsDef<S>],\n () => {\n const newValue = derivationsManager.get(\n id as keyof DerivationsDef<S>,\n ) as T;\n if (!isEqual(newValue, previousValue)) {\n const oldValue = previousValue;\n previousValue = newValue;\n callback(newValue, oldValue);\n }\n },\n );\n }\n\n // Fact path\n if (process.env.NODE_ENV !== \"production\") {\n if (!(id in mergedSchema)) {\n console.warn(`[Directive] watch: unknown key \"${id}\"`);\n }\n }\n let prev = store.get(id as keyof InferSchema<S>) as T | undefined;\n return store.subscribe([id as keyof InferSchema<S>], () => {\n const next = store.get(id as keyof InferSchema<S>) as T;\n if (!isEqual(next, prev)) {\n const old = prev;\n prev = next;\n callback(next, old);\n }\n });\n },\n\n when(\n predicate: (facts: Record<string, unknown>) => boolean,\n options?: { timeout?: number },\n ): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n // Check immediately\n const factsObj = store.toObject();\n if (predicate(factsObj)) {\n resolve();\n return;\n }\n\n let unsub: (() => void) | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const cleanup = () => {\n unsub?.();\n if (timer !== undefined) clearTimeout(timer);\n };\n\n // Subscribe to all fact changes\n unsub = store.subscribeAll(() => {\n const current = store.toObject();\n if (predicate(current)) {\n cleanup();\n resolve();\n }\n });\n\n // Timeout\n if (options?.timeout !== undefined && options.timeout > 0) {\n timer = setTimeout(() => {\n cleanup();\n reject(\n new Error(\n `[Directive] when: timed out after ${options.timeout}ms`,\n ),\n );\n }, options.timeout);\n }\n });\n },\n\n inspect(): SystemInspection {\n return {\n unmet: state.previousRequirements.all(),\n inflight: resolversManager.getInflightInfo(),\n constraints: constraintsManager.getAllStates().map((s) => ({\n id: s.id,\n active: s.lastResult ?? false,\n disabled: constraintsManager.isDisabled(s.id),\n priority: s.priority,\n hitCount: s.hitCount,\n lastActiveAt: s.lastActiveAt,\n })),\n resolvers: Object.fromEntries(\n resolversManager\n .getInflight()\n .map((id) => [id, resolversManager.getStatus(id)]),\n ),\n resolverDefs: Object.entries(mergedResolvers).map(([id, def]) => ({\n id,\n requirement:\n typeof def.requirement === \"string\"\n ? def.requirement\n : \"(predicate)\",\n })),\n traceEnabled,\n ...(traceEnabled\n ? { trace: structuredClone(traceManager.getEntries() ?? []) }\n : {}),\n };\n },\n\n explain(requirementId: string): string | null {\n // Find the requirement in current unmet requirements\n const requirements = state.previousRequirements.all();\n const req = requirements.find((r) => r.id === requirementId);\n\n if (!req) {\n return null;\n }\n\n const constraintState = constraintsManager.getState(req.fromConstraint);\n const resolverStatus = resolversManager.getStatus(requirementId);\n\n // Get relevant facts from the constraint's tracked dependencies\n const relevantFacts: Record<string, unknown> = {};\n const constraintDeps = constraintsManager.getDependencies(\n req.fromConstraint,\n );\n if (constraintDeps) {\n for (const key of constraintDeps) {\n relevantFacts[key] = store.get(key);\n }\n } else {\n // Fallback: include all facts if deps not tracked\n for (const [key, value] of Object.entries(store.toObject())) {\n relevantFacts[key] = value;\n }\n }\n\n const lines: string[] = [\n `Requirement \"${req.requirement.type}\" (id: ${req.id})`,\n `├─ Produced by constraint: ${req.fromConstraint}`,\n `├─ Constraint priority: ${constraintState?.priority ?? 0}`,\n `├─ Constraint active: ${constraintState?.lastResult ?? \"unknown\"}`,\n `├─ Resolver status: ${resolverStatus.state}`,\n ];\n\n // Add requirement details\n const reqDetails = Object.entries(req.requirement)\n .filter(([k]) => k !== \"type\")\n .map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n .join(\", \");\n if (reqDetails) {\n lines.push(`├─ Requirement payload: { ${reqDetails} }`);\n }\n\n // Add relevant facts (limit to prevent huge output)\n const factEntries = Object.entries(relevantFacts).slice(0, 10);\n if (factEntries.length > 0) {\n lines.push(\"└─ Relevant facts:\");\n factEntries.forEach(([k, v], i) => {\n const prefix = i === factEntries.length - 1 ? \" └─\" : \" ├─\";\n const valueStr =\n typeof v === \"object\" ? JSON.stringify(v) : String(v);\n lines.push(\n `${prefix} ${k} = ${valueStr.slice(0, 50)}${valueStr.length > 50 ? \"...\" : \"\"}`,\n );\n });\n }\n\n return lines.join(\"\\n\");\n },\n\n getOriginal(\n type: \"constraint\" | \"resolver\" | \"derivation\" | \"effect\",\n id: string,\n ): unknown | undefined {\n return definitions.getOriginal(type, id);\n },\n\n restoreOriginal(\n type: \"constraint\" | \"resolver\" | \"derivation\" | \"effect\",\n id: string,\n ): boolean {\n return definitions.restoreOriginal(type, id);\n },\n\n async settle(maxWait = 5000): Promise<void> {\n /** Check if the system is fully settled */\n const isSettled = (): boolean =>\n resolversManager.getInflightCount() === 0 &&\n !state.isReconciling &&\n !state.reconcileScheduled &&\n !resolversManager.hasPendingBatches();\n\n // Flush pending batches and yield once for microtasks\n if (resolversManager.hasPendingBatches()) {\n resolversManager.processBatches();\n }\n await new Promise((resolve) => setTimeout(resolve, 0));\n\n if (isSettled()) {\n return;\n }\n\n // Event-driven: resolve when settlement state changes\n return new Promise<void>((resolve, reject) => {\n let done = false;\n\n const cleanup = () => {\n if (done) {\n return;\n }\n done = true;\n clearTimeout(timeout);\n unsubscribe();\n };\n\n const timeout = setTimeout(() => {\n cleanup();\n const details: string[] = [];\n const inflight = resolversManager.getInflightInfo();\n if (inflight.length > 0) {\n details.push(\n `${inflight.length} resolvers inflight: ${inflight.map((r) => r.resolverId).join(\", \")}`,\n );\n }\n if (state.isReconciling) {\n details.push(\"reconciliation in progress\");\n }\n if (state.reconcileScheduled) {\n details.push(\"reconcile scheduled\");\n }\n const unmet = state.previousRequirements.all();\n if (unmet.length > 0) {\n details.push(\n `${unmet.length} unmet requirements: ${unmet.map((r) => r.requirement.type).join(\", \")}`,\n );\n }\n reject(\n new Error(\n `[Directive] settle() timed out after ${maxWait}ms. ${details.join(\"; \")}`,\n ),\n );\n }, maxWait);\n\n const unsubscribe = this.onSettledChange(() => {\n if (resolversManager.hasPendingBatches()) {\n resolversManager.processBatches();\n }\n // Yield a microtask to let pending reconciles complete\n setTimeout(() => {\n if (!done && isSettled()) {\n cleanup();\n resolve();\n }\n }, 0);\n });\n });\n },\n\n getSnapshot() {\n return {\n facts: store.toObject(),\n version: 1,\n };\n },\n\n getDistributableSnapshot<T = Record<string, unknown>>(\n options: {\n includeDerivations?: string[];\n excludeDerivations?: string[];\n includeFacts?: string[];\n ttlSeconds?: number;\n metadata?: Record<string, unknown>;\n includeVersion?: boolean;\n } = {},\n ): {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n } {\n const {\n includeDerivations,\n excludeDerivations,\n includeFacts,\n ttlSeconds,\n metadata,\n includeVersion,\n } = options;\n\n const data: Record<string, unknown> = {};\n\n // Collect derivation keys to include\n const allDerivationKeys = Object.keys(mergedDerive);\n const allDerivationSet = new Set(allDerivationKeys);\n let derivationKeys: string[];\n\n if (includeDerivations) {\n // Only include specified derivations (Set lookup: O(1) per key)\n derivationKeys = includeDerivations.filter((k) =>\n allDerivationSet.has(k),\n );\n\n // Warn about unknown derivation keys in dev mode\n if (process.env.NODE_ENV !== \"production\") {\n const unknown = includeDerivations.filter(\n (k) => !allDerivationSet.has(k),\n );\n if (unknown.length > 0) {\n console.warn(\n `[Directive] getDistributableSnapshot: Unknown derivation keys ignored: ${unknown.join(\", \")}. ` +\n `Available: ${allDerivationKeys.join(\", \") || \"(none)\"}`,\n );\n }\n }\n } else {\n // Include all derivations by default\n derivationKeys = allDerivationKeys;\n }\n\n // Apply exclusions\n if (excludeDerivations) {\n const excludeSet = new Set(excludeDerivations);\n derivationKeys = derivationKeys.filter((k) => !excludeSet.has(k));\n }\n\n // Read derivation values\n for (const key of derivationKeys) {\n try {\n data[key] = derivationsManager.get(key as keyof DerivationsDef<S>);\n } catch (error) {\n // Skip derivations that error during computation\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Directive] getDistributableSnapshot: Skipping derivation \"${key}\" due to error:`,\n error,\n );\n }\n }\n }\n\n // Include specified facts\n if (includeFacts && includeFacts.length > 0) {\n const factsSnapshot = store.toObject();\n const allFactKeys = Object.keys(factsSnapshot);\n\n // Warn about unknown fact keys in dev mode\n if (process.env.NODE_ENV !== \"production\") {\n const unknown = includeFacts.filter((k) => !(k in factsSnapshot));\n if (unknown.length > 0) {\n console.warn(\n `[Directive] getDistributableSnapshot: Unknown fact keys ignored: ${unknown.join(\", \")}. ` +\n `Available: ${allFactKeys.join(\", \") || \"(none)\"}`,\n );\n }\n }\n\n for (const key of includeFacts) {\n if (key in factsSnapshot) {\n data[key] = factsSnapshot[key];\n }\n }\n }\n\n // Build the snapshot\n const createdAt = Date.now();\n const snapshot: {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n } = {\n data: data as T,\n createdAt,\n };\n\n // Add TTL\n if (ttlSeconds !== undefined && ttlSeconds > 0) {\n snapshot.expiresAt = createdAt + ttlSeconds * 1000;\n }\n\n // Add version hash\n if (includeVersion) {\n // Simple version hash based on data content\n snapshot.version = hashObject(data);\n }\n\n // Add metadata\n if (metadata) {\n snapshot.metadata = metadata;\n }\n\n return snapshot;\n },\n\n watchDistributableSnapshot<T = Record<string, unknown>>(\n options: {\n includeDerivations?: string[];\n excludeDerivations?: string[];\n includeFacts?: string[];\n ttlSeconds?: number;\n metadata?: Record<string, unknown>;\n includeVersion?: boolean;\n },\n callback: (snapshot: {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n }) => void,\n ): () => void {\n const { includeDerivations, excludeDerivations } = options;\n\n // Determine which derivations to watch\n const allDerivationKeys = Object.keys(mergedDerive);\n let derivationKeys: string[];\n\n if (includeDerivations) {\n derivationKeys = includeDerivations.filter((k) =>\n allDerivationKeys.includes(k),\n );\n } else {\n derivationKeys = allDerivationKeys;\n }\n\n if (excludeDerivations) {\n const excludeSet = new Set(excludeDerivations);\n derivationKeys = derivationKeys.filter((k) => !excludeSet.has(k));\n }\n\n if (derivationKeys.length === 0) {\n // Nothing to watch, return no-op unsubscribe\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[Directive] watchDistributableSnapshot: No derivations to watch. \" +\n \"Callback will never be called.\",\n );\n }\n return () => {};\n }\n\n // Get initial snapshot to seed version and ensure derivations are computed\n // (derivations must be computed before subscribing so listeners are called on invalidation)\n const initialSnapshot = this.getDistributableSnapshot<T>({\n ...options,\n includeVersion: true,\n });\n let previousVersion = initialSnapshot.version;\n\n // Subscribe to all watched derivations\n return derivationsManager.subscribe(\n derivationKeys as Array<keyof DerivationsDef<S>>,\n () => {\n // Generate a new snapshot\n const snapshot = this.getDistributableSnapshot<T>({\n ...options,\n // Always include version for change detection\n includeVersion: true,\n });\n\n // Only call callback if snapshot actually changed\n if (snapshot.version !== previousVersion) {\n previousVersion = snapshot.version;\n callback(snapshot);\n }\n },\n );\n },\n\n restore(snapshot) {\n if (!snapshot || typeof snapshot !== \"object\") {\n throw new Error(\n \"[Directive] restore() requires a valid snapshot object\",\n );\n }\n if (!snapshot.facts || typeof snapshot.facts !== \"object\") {\n throw new Error(\n \"[Directive] restore() snapshot must have a facts object\",\n );\n }\n\n // Security: Validate snapshot for prototype pollution\n if (!isPrototypeSafe(snapshot)) {\n throw new Error(\n \"[Directive] restore() rejected: snapshot contains potentially dangerous keys \" +\n \"(__proto__, constructor, or prototype). This may indicate a prototype pollution attack.\",\n );\n }\n\n store.batch(() => {\n for (const [key, value] of Object.entries(snapshot.facts)) {\n // Skip dangerous keys (defense in depth)\n if (BLOCKED_PROPS.has(key)) continue;\n store.set(\n key as keyof InferSchema<S>,\n value as InferSchema<S>[keyof InferSchema<S>],\n );\n }\n });\n },\n\n onSettledChange(listener: () => void): () => void {\n settlementListeners.add(listener);\n return () => {\n settlementListeners.delete(listener);\n };\n },\n\n onHistoryChange(listener: () => void): () => void {\n historyListeners.add(listener);\n return () => {\n historyListeners.delete(listener);\n };\n },\n\n batch(fn: () => void): void {\n store.batch(fn);\n },\n\n get isSettled(): boolean {\n return (\n resolversManager.getInflightCount() === 0 &&\n !resolversManager.hasPendingBatches() &&\n !state.isReconciling &&\n !state.reconcileScheduled\n );\n },\n\n get isRunning(): boolean {\n return state.isRunning;\n },\n\n get isInitialized(): boolean {\n return state.isInitialized;\n },\n\n get isReady(): boolean {\n return state.isReady;\n },\n\n whenReady(): Promise<void> {\n // If already ready, resolve immediately\n if (state.isReady) {\n return Promise.resolve();\n }\n\n // If not running, the promise would never resolve\n if (!state.isRunning) {\n return Promise.reject(\n new Error(\n \"[Directive] whenReady() called before start(). \" +\n \"Call system.start() first, then await system.whenReady().\",\n ),\n );\n }\n\n // Create promise if not exists\n if (!state.readyPromise) {\n state.readyPromise = new Promise<void>((resolve) => {\n state.readyResolve = resolve;\n });\n }\n\n return state.readyPromise;\n },\n };\n\n /**\n * Register a new module into a running (or stopped) engine.\n * Merges the module's schema, events, derive, effects, constraints, and resolvers\n * into the existing engine state, runs init, and triggers reconciliation.\n */\n function registerModule(module: {\n id: string;\n schema: Record<string, unknown>;\n requirements?: Record<string, unknown>;\n init?: (facts: unknown) => void;\n derive?: Record<string, (facts: unknown, derived: unknown) => unknown>;\n events?: Record<string, (facts: unknown, event: unknown) => void>;\n effects?: Record<string, unknown>;\n constraints?: Record<string, unknown>;\n resolvers?: Record<string, unknown>;\n hooks?: {\n onInit?: (s: unknown) => void;\n onStart?: (s: unknown) => void;\n onStop?: (s: unknown) => void;\n onError?: (e: unknown, ctx: unknown) => void;\n };\n history?: { snapshotEvents?: string[] };\n }): void {\n // Guard: cannot register during reconciliation (would corrupt iteration state)\n if (state.isReconciling) {\n throw new Error(\n `[Directive] Cannot register module \"${module.id}\" during reconciliation. ` +\n \"Wait for the current reconciliation cycle to complete.\",\n );\n }\n\n // Guard: cannot register on a destroyed system\n if (state.isDestroyed) {\n throw new Error(\n `[Directive] Cannot register module \"${module.id}\" on a destroyed system.`,\n );\n }\n\n // Security: validate keys\n const validateKeys = (obj: object | undefined, section: string) => {\n if (!obj) return;\n for (const key of Object.keys(obj)) {\n if (BLOCKED_PROPS.has(key)) {\n throw new Error(\n `[Directive] Security: Module \"${module.id}\" has dangerous key \"${key}\" in ${section}.`,\n );\n }\n if (section === \"schema\" && key.startsWith(\"$\")) {\n throw new Error(\n `[Directive] Module \"${module.id}\" has schema key \"${key}\" starting with \"$\". ` +\n \"Keys starting with $ are reserved for internal accessors ($store, $snapshot).\",\n );\n }\n }\n };\n validateKeys(module.schema, \"schema\");\n validateKeys(module.events, \"events\");\n validateKeys(module.derive, \"derive\");\n validateKeys(module.effects, \"effects\");\n validateKeys(module.constraints, \"constraints\");\n validateKeys(module.resolvers, \"resolvers\");\n\n // Schema collision detection (unconditional — production collision would cause data corruption)\n for (const key of Object.keys(module.schema)) {\n if (key in mergedSchema) {\n throw new Error(\n `[Directive] Schema collision: Fact \"${key}\" already exists. Cannot register module \"${module.id}\".`,\n );\n }\n }\n // Fact/derivation name collision check (dev-only warning)\n if (process.env.NODE_ENV !== \"production\" && module.derive) {\n const existingFactKeys = new Set(Object.keys(mergedSchema));\n for (const key of Object.keys(module.derive)) {\n if (existingFactKeys.has(key)) {\n console.warn(\n `[Directive] \"${key}\" exists as both a fact and a derivation after registering module \"${module.id}\".`,\n );\n }\n }\n }\n\n // Update snapshotEventNames BEFORE merging events so we capture pre-merge state\n if (module.history?.snapshotEvents) {\n if (snapshotEventNames === null) {\n // First module with history.snapshotEvents — initialize the set with all existing event names\n snapshotEventNames = new Set<string>(Object.keys(mergedEvents));\n }\n for (const eventName of module.history.snapshotEvents) {\n snapshotEventNames.add(eventName);\n }\n } else if (snapshotEventNames !== null && module.events) {\n // Filtering is active and this module has no filter — add all its events\n for (const eventName of Object.keys(module.events)) {\n snapshotEventNames.add(eventName);\n }\n }\n\n // Merge into existing engine state\n Object.assign(mergedSchema, module.schema);\n if (module.events) Object.assign(mergedEvents, module.events);\n if (module.derive) {\n Object.assign(mergedDerive, module.derive);\n // Register new derivations with the derivations manager\n derivationsManager.registerDefinitions(\n module.derive as DerivationsDef<S>,\n );\n }\n if (module.effects) {\n Object.assign(mergedEffects, module.effects);\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic module registration\n effectsManager.registerDefinitions(module.effects as any);\n }\n if (module.constraints) {\n Object.assign(mergedConstraints, module.constraints);\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic module registration\n constraintsManager.registerDefinitions(module.constraints as any);\n }\n if (module.resolvers) {\n Object.assign(mergedResolvers, module.resolvers);\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic module registration\n resolversManager.registerDefinitions(module.resolvers as any);\n // Sync resolver key functions to the constraints manager\n syncResolverKeys(module.resolvers as ResolversDef<S>);\n }\n\n // Register new schema keys with the facts store\n // biome-ignore lint/suspicious/noExplicitAny: Internal dynamic method\n (store as any).registerKeys(module.schema as Record<string, unknown>);\n\n // Track the new module in config.modules for hooks\n config.modules.push(module as (typeof config.modules)[number]);\n\n // Run init within a batch\n if (module.init) {\n store.batch(() => {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic module init\n module.init!(facts as any);\n });\n }\n\n // Call lifecycle hooks\n module.hooks?.onInit?.(system);\n if (state.isRunning) {\n module.hooks?.onStart?.(system);\n // Trigger reconciliation to evaluate new constraints\n scheduleReconcile();\n }\n }\n\n // Attach registerModule to system\n (system as unknown as Record<string, unknown>).registerModule =\n registerModule;\n\n // Initialize plugins\n pluginManager.emitInit(system);\n\n // Call module init hooks\n for (const module of config.modules) {\n module.hooks?.onInit?.(system);\n }\n\n return system;\n}\n"]}