@graphrefly/ts 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapters/index.cjs +9015 -0
  3. package/dist/adapters/index.cjs.map +1 -0
  4. package/dist/adapters/index.d.cts +678 -0
  5. package/dist/adapters/index.d.ts +678 -0
  6. package/dist/adapters/index.js +2894 -0
  7. package/dist/adapters/index.js.map +1 -0
  8. package/dist/adapters/observe-storage.cjs +260 -0
  9. package/dist/adapters/observe-storage.cjs.map +1 -0
  10. package/dist/adapters/observe-storage.d.cts +77 -0
  11. package/dist/adapters/observe-storage.d.ts +77 -0
  12. package/dist/adapters/observe-storage.js +161 -0
  13. package/dist/adapters/observe-storage.js.map +1 -0
  14. package/dist/append-log-DisvEReb.d.cts +189 -0
  15. package/dist/append-log-DzKMmjxx.d.ts +189 -0
  16. package/dist/chunk-2ILL7HQI.js +1189 -0
  17. package/dist/chunk-2ILL7HQI.js.map +1 -0
  18. package/dist/chunk-4VLAQHZI.js +330 -0
  19. package/dist/chunk-4VLAQHZI.js.map +1 -0
  20. package/dist/chunk-6PHB5CJS.js +229 -0
  21. package/dist/chunk-6PHB5CJS.js.map +1 -0
  22. package/dist/chunk-COHO25CZ.js +2449 -0
  23. package/dist/chunk-COHO25CZ.js.map +1 -0
  24. package/dist/chunk-D6BG7U6A.js +161 -0
  25. package/dist/chunk-D6BG7U6A.js.map +1 -0
  26. package/dist/chunk-DJC4CHLQ.js +818 -0
  27. package/dist/chunk-DJC4CHLQ.js.map +1 -0
  28. package/dist/chunk-DK554R7P.js +67 -0
  29. package/dist/chunk-DK554R7P.js.map +1 -0
  30. package/dist/chunk-DKP56CSW.js +322 -0
  31. package/dist/chunk-DKP56CSW.js.map +1 -0
  32. package/dist/chunk-G4M3NHRJ.js +688 -0
  33. package/dist/chunk-G4M3NHRJ.js.map +1 -0
  34. package/dist/chunk-GAJW5I5P.js +1 -0
  35. package/dist/chunk-GAJW5I5P.js.map +1 -0
  36. package/dist/chunk-GDL26N2T.js +282 -0
  37. package/dist/chunk-GDL26N2T.js.map +1 -0
  38. package/dist/chunk-GTPCOEOZ.js +741 -0
  39. package/dist/chunk-GTPCOEOZ.js.map +1 -0
  40. package/dist/chunk-H2HTHFVN.js +1 -0
  41. package/dist/chunk-H2HTHFVN.js.map +1 -0
  42. package/dist/chunk-HDRL4VQQ.js +218 -0
  43. package/dist/chunk-HDRL4VQQ.js.map +1 -0
  44. package/dist/chunk-I3IHOHCJ.js +2267 -0
  45. package/dist/chunk-I3IHOHCJ.js.map +1 -0
  46. package/dist/chunk-JIMUDQN3.js +965 -0
  47. package/dist/chunk-JIMUDQN3.js.map +1 -0
  48. package/dist/chunk-JR4IKCR2.js +462 -0
  49. package/dist/chunk-JR4IKCR2.js.map +1 -0
  50. package/dist/chunk-K3FXTC3I.js +165 -0
  51. package/dist/chunk-K3FXTC3I.js.map +1 -0
  52. package/dist/chunk-OOEN33FB.js +65 -0
  53. package/dist/chunk-OOEN33FB.js.map +1 -0
  54. package/dist/chunk-PKVBHGBM.js +554 -0
  55. package/dist/chunk-PKVBHGBM.js.map +1 -0
  56. package/dist/chunk-RIIOUTGM.js +1857 -0
  57. package/dist/chunk-RIIOUTGM.js.map +1 -0
  58. package/dist/chunk-SCRFRCGR.js +33 -0
  59. package/dist/chunk-SCRFRCGR.js.map +1 -0
  60. package/dist/chunk-SWTLEQL6.js +53 -0
  61. package/dist/chunk-SWTLEQL6.js.map +1 -0
  62. package/dist/chunk-SZAETNNA.js +1 -0
  63. package/dist/chunk-SZAETNNA.js.map +1 -0
  64. package/dist/chunk-TEW47IVR.js +49 -0
  65. package/dist/chunk-TEW47IVR.js.map +1 -0
  66. package/dist/chunk-Y3ZLRGHC.js +1482 -0
  67. package/dist/chunk-Y3ZLRGHC.js.map +1 -0
  68. package/dist/chunk-Z2ANQ6JW.js +149 -0
  69. package/dist/chunk-Z2ANQ6JW.js.map +1 -0
  70. package/dist/codec-BB7p8fJc.d.cts +38 -0
  71. package/dist/codec-BB7p8fJc.d.ts +38 -0
  72. package/dist/composition/index.cjs +2505 -0
  73. package/dist/composition/index.cjs.map +1 -0
  74. package/dist/composition/index.d.cts +95 -0
  75. package/dist/composition/index.d.ts +95 -0
  76. package/dist/composition/index.js +19 -0
  77. package/dist/composition/index.js.map +1 -0
  78. package/dist/core/index.cjs +2475 -0
  79. package/dist/core/index.cjs.map +1 -0
  80. package/dist/core/index.d.cts +25 -0
  81. package/dist/core/index.d.ts +25 -0
  82. package/dist/core/index.js +74 -0
  83. package/dist/core/index.js.map +1 -0
  84. package/dist/cqrs/index.cjs +595 -0
  85. package/dist/cqrs/index.cjs.map +1 -0
  86. package/dist/cqrs/index.d.cts +200 -0
  87. package/dist/cqrs/index.d.ts +200 -0
  88. package/dist/cqrs/index.js +557 -0
  89. package/dist/cqrs/index.js.map +1 -0
  90. package/dist/data-structures/index.cjs +4277 -0
  91. package/dist/data-structures/index.cjs.map +1 -0
  92. package/dist/data-structures/index.d.cts +22 -0
  93. package/dist/data-structures/index.d.ts +22 -0
  94. package/dist/data-structures/index.js +31 -0
  95. package/dist/data-structures/index.js.map +1 -0
  96. package/dist/describe-BZb7AS2y.d.ts +57 -0
  97. package/dist/describe-Ciu8SUnN.d.cts +57 -0
  98. package/dist/graph/index.cjs +7832 -0
  99. package/dist/graph/index.cjs.map +1 -0
  100. package/dist/graph/index.d.cts +251 -0
  101. package/dist/graph/index.d.ts +251 -0
  102. package/dist/graph/index.js +131 -0
  103. package/dist/graph/index.js.map +1 -0
  104. package/dist/graph-DfdF9zy4.d.ts +666 -0
  105. package/dist/graph-s23RbbFO.d.cts +666 -0
  106. package/dist/index-CAEmLCYF.d.cts +166 -0
  107. package/dist/index-SnzZu3x7.d.ts +166 -0
  108. package/dist/index.cjs +15409 -0
  109. package/dist/index.cjs.map +1 -0
  110. package/dist/index.d.cts +23 -0
  111. package/dist/index.d.ts +23 -0
  112. package/dist/index.js +582 -0
  113. package/dist/index.js.map +1 -0
  114. package/dist/messages-BZqrGGm1.d.cts +55 -0
  115. package/dist/messages-BZqrGGm1.d.ts +55 -0
  116. package/dist/messaging/index.cjs +818 -0
  117. package/dist/messaging/index.cjs.map +1 -0
  118. package/dist/messaging/index.d.cts +235 -0
  119. package/dist/messaging/index.d.ts +235 -0
  120. package/dist/messaging/index.js +767 -0
  121. package/dist/messaging/index.js.map +1 -0
  122. package/dist/observe-event-log-0SVsx7JG.d.cts +88 -0
  123. package/dist/observe-event-log-Dnm76owp.d.ts +88 -0
  124. package/dist/operators/index.cjs +3774 -0
  125. package/dist/operators/index.cjs.map +1 -0
  126. package/dist/operators/index.d.cts +308 -0
  127. package/dist/operators/index.d.ts +308 -0
  128. package/dist/operators/index.js +112 -0
  129. package/dist/operators/index.js.map +1 -0
  130. package/dist/orchestration/index.cjs +3541 -0
  131. package/dist/orchestration/index.cjs.map +1 -0
  132. package/dist/orchestration/index.d.cts +302 -0
  133. package/dist/orchestration/index.d.ts +302 -0
  134. package/dist/orchestration/index.js +1004 -0
  135. package/dist/orchestration/index.js.map +1 -0
  136. package/dist/patterns/index.cjs +1045 -0
  137. package/dist/patterns/index.cjs.map +1 -0
  138. package/dist/patterns/index.d.cts +39 -0
  139. package/dist/patterns/index.d.ts +39 -0
  140. package/dist/patterns/index.js +33 -0
  141. package/dist/patterns/index.js.map +1 -0
  142. package/dist/reactive-collection-BxBqtIOE.d.cts +344 -0
  143. package/dist/reactive-collection-Cb1II1Fi.d.ts +344 -0
  144. package/dist/reactive-collection-storage-BNiEc-Gd.d.ts +217 -0
  145. package/dist/reactive-collection-storage-D-KmjE0J.d.cts +217 -0
  146. package/dist/reactive-map-BcB4KsQR.d.ts +256 -0
  147. package/dist/reactive-map-D-g3dv8I.d.cts +256 -0
  148. package/dist/read-through-B1CYPfq_.d.cts +82 -0
  149. package/dist/read-through-DwyJhGs1.d.ts +82 -0
  150. package/dist/render/index.cjs +250 -0
  151. package/dist/render/index.cjs.map +1 -0
  152. package/dist/render/index.d.cts +58 -0
  153. package/dist/render/index.d.ts +58 -0
  154. package/dist/render/index.js +20 -0
  155. package/dist/render/index.js.map +1 -0
  156. package/dist/resilience-Dig3Q7n0.d.cts +45 -0
  157. package/dist/resilience-Dig3Q7n0.d.ts +45 -0
  158. package/dist/semantic-memory-graph-BYoIlP35.d.cts +356 -0
  159. package/dist/semantic-memory-graph-CxyXLms3.d.ts +356 -0
  160. package/dist/solutions/index.cjs +3249 -0
  161. package/dist/solutions/index.cjs.map +1 -0
  162. package/dist/solutions/index.d.cts +520 -0
  163. package/dist/solutions/index.d.ts +520 -0
  164. package/dist/solutions/index.js +31 -0
  165. package/dist/solutions/index.js.map +1 -0
  166. package/dist/sources/browser.cjs +3095 -0
  167. package/dist/sources/browser.cjs.map +1 -0
  168. package/dist/sources/browser.d.cts +39 -0
  169. package/dist/sources/browser.d.ts +39 -0
  170. package/dist/sources/browser.js +137 -0
  171. package/dist/sources/browser.js.map +1 -0
  172. package/dist/sources/index.cjs +3021 -0
  173. package/dist/sources/index.cjs.map +1 -0
  174. package/dist/sources/index.d.cts +7 -0
  175. package/dist/sources/index.d.ts +7 -0
  176. package/dist/sources/index.js +63 -0
  177. package/dist/sources/index.js.map +1 -0
  178. package/dist/sources/node.cjs +675 -0
  179. package/dist/sources/node.cjs.map +1 -0
  180. package/dist/sources/node.d.cts +109 -0
  181. package/dist/sources/node.d.ts +109 -0
  182. package/dist/sources/node.js +639 -0
  183. package/dist/sources/node.js.map +1 -0
  184. package/dist/storage/browser.cjs +777 -0
  185. package/dist/storage/browser.cjs.map +1 -0
  186. package/dist/storage/browser.d.cts +40 -0
  187. package/dist/storage/browser.d.ts +40 -0
  188. package/dist/storage/browser.js +275 -0
  189. package/dist/storage/browser.js.map +1 -0
  190. package/dist/storage/index.cjs +1989 -0
  191. package/dist/storage/index.cjs.map +1 -0
  192. package/dist/storage/index.d.cts +92 -0
  193. package/dist/storage/index.d.ts +92 -0
  194. package/dist/storage/index.js +161 -0
  195. package/dist/storage/index.js.map +1 -0
  196. package/dist/storage/node.cjs +898 -0
  197. package/dist/storage/node.cjs.map +1 -0
  198. package/dist/storage/node.d.cts +66 -0
  199. package/dist/storage/node.d.ts +66 -0
  200. package/dist/storage/node.js +402 -0
  201. package/dist/storage/node.js.map +1 -0
  202. package/dist/testing/index.cjs +95 -0
  203. package/dist/testing/index.cjs.map +1 -0
  204. package/dist/testing/index.d.cts +20 -0
  205. package/dist/testing/index.d.ts +20 -0
  206. package/dist/testing/index.js +8 -0
  207. package/dist/testing/index.js.map +1 -0
  208. package/dist/types-bNMSWKqF.d.cts +732 -0
  209. package/dist/types-h12mNYbq.d.ts +732 -0
  210. package/package.json +250 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/solutions/index.ts","../../src/protocol/messages.ts","../../src/ctx/types.ts","../../src/json/codec.ts","../../src/patterns/semantic-memory.ts","../../src/patterns/semantic-memory-graph.ts","../../src/solutions/agentic-memory.ts"],"sourcesContent":["/**\n * Vertical application solution kits.\n *\n * Agentic memory, harness, and data-agent surfaces land here after B63/B62\n * classify and re-derive them onto lower D125 layers.\n */\n\nexport {\n\tAGENTIC_MEMORY_RECORD_FRAME_FORMAT,\n\tAGENTIC_MEMORY_RECORD_FRAME_VERSION,\n\ttype AgenticMemoryArtifactKind,\n\ttype AgenticMemoryBundle,\n\ttype AgenticMemoryBundleOptions,\n\ttype AgenticMemoryConsolidationBundle,\n\ttype AgenticMemoryConsolidationBundleOptions,\n\ttype AgenticMemoryConsolidationCommand,\n\ttype AgenticMemoryConsolidationCursor,\n\ttype AgenticMemoryConsolidationError,\n\ttype AgenticMemoryConsolidationErrorCode,\n\ttype AgenticMemoryConsolidationOutcome,\n\ttype AgenticMemoryConsolidationRecordDraft,\n\ttype AgenticMemoryConsolidationRequest,\n\ttype AgenticMemoryConsolidationResult,\n\ttype AgenticMemoryConsolidationSnapshot,\n\ttype AgenticMemoryConsolidationStatus,\n\ttype AgenticMemoryContext,\n\ttype AgenticMemoryContextEntry,\n\ttype AgenticMemoryContextPackingBundle,\n\ttype AgenticMemoryContextPackingBundleOptions,\n\ttype AgenticMemoryContextPackingCursor,\n\ttype AgenticMemoryContextPackingError,\n\ttype AgenticMemoryContextPackingErrorCode,\n\ttype AgenticMemoryContextPackingPolicy,\n\ttype AgenticMemoryContextPackingSnapshot,\n\ttype AgenticMemoryContextPackingStatus,\n\ttype AgenticMemoryContextState,\n\ttype AgenticMemoryContextText,\n\ttype AgenticMemoryError,\n\ttype AgenticMemoryErrorCode,\n\ttype AgenticMemoryFragmentFrame,\n\ttype AgenticMemoryKgAssertionDraft,\n\ttype AgenticMemoryKgProjectionBundle,\n\ttype AgenticMemoryKgProjectionBundleOptions,\n\ttype AgenticMemoryKgProjectionCursor,\n\ttype AgenticMemoryKgProjectionError,\n\ttype AgenticMemoryKgProjectionErrorCode,\n\ttype AgenticMemoryKgProjectionSnapshot,\n\ttype AgenticMemoryKgProjectionStatus,\n\ttype AgenticMemoryKgProjectionStatusState,\n\ttype AgenticMemoryKind,\n\ttype AgenticMemoryPackedContext,\n\ttype AgenticMemoryPackedContextEntry,\n\ttype AgenticMemoryPersistenceLevel,\n\ttype AgenticMemoryProjectionCursor,\n\ttype AgenticMemoryProjectionSnapshot,\n\ttype AgenticMemoryRecord,\n\ttype AgenticMemoryRecordFrame,\n\ttype AgenticMemoryRecordMetadata,\n\ttype AgenticMemoryRetentionBundle,\n\ttype AgenticMemoryRetentionBundleOptions,\n\ttype AgenticMemoryRetentionCommand,\n\ttype AgenticMemoryRetentionCursor,\n\ttype AgenticMemoryRetentionError,\n\ttype AgenticMemoryRetentionErrorCode,\n\ttype AgenticMemoryRetentionSnapshot,\n\ttype AgenticMemoryRetentionStatus,\n\ttype AgenticMemoryScope,\n\ttype AgenticMemorySourceProjection,\n\ttype AgenticMemoryStatus,\n\ttype AgenticMemoryStatusState,\n\ttype AgenticMemoryStrictJsonValue,\n\tagenticMemoryBundle,\n\tagenticMemoryConsolidationBundle,\n\tagenticMemoryContextPackingBundle,\n\tagenticMemoryKgProjectionBundle,\n\tagenticMemoryRecordCodec,\n\tagenticMemoryRecordFrame,\n\tagenticMemoryRecordFrameCodec,\n\tagenticMemoryRetentionBundle,\n\tassertAgenticMemoryRecordFrame,\n\ttype KnowledgeAssertion,\n\ttype KnowledgeAssertionObject,\n\ttype KnowledgeAssertionSubject,\n} from \"./agentic-memory.js\";\n","/**\n * Wave-protocol message types and the tier const table.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-msg-format, R-msg-closed-set, R-tier (D34), R-data-payload, R-sentinel.\n */\n\n/** Opaque pause-lock identifier (R-pause-lockset). */\nexport type LockId = string | symbol;\n\n/**\n * The CLOSED set of 10 message types (R-msg-closed-set / D9 + START handshake).\n * No open set, no user-defined custom types. Adding a type is a spec change.\n */\nexport type Message =\n\t| readonly [\"START\"]\n\t| readonly [\"DIRTY\"]\n\t| readonly [\"DATA\", unknown]\n\t| readonly [\"RESOLVED\"]\n\t| readonly [\"INVALIDATE\"]\n\t| readonly [\"COMPLETE\"]\n\t| readonly [\"ERROR\", unknown]\n\t| readonly [\"TEARDOWN\"]\n\t| readonly [\"PAUSE\", LockId]\n\t| readonly [\"RESUME\", LockId];\n\n/** One array of messages delivered in one call = one Wave (R-wave-boundary). */\nexport type Wave = readonly Message[];\n\n/** The message-type tag (the first tuple element). */\nexport type MessageType = Message[0];\n\n/**\n * SENTINEL = absence-of-DATA (R-sentinel / D16). TS representation is `undefined`.\n * Never a valid DATA payload; `null` IS a valid DATA value (domain-level absence).\n */\nexport const SENTINEL = undefined;\n\n/** R-data-payload: ERROR payloads must not collide with terminal metadata shorthand. */\nexport function isInvalidErrorPayload(v: unknown): boolean {\n\treturn v === SENTINEL || typeof v === \"boolean\";\n}\n\n/** R-data-payload / D78: host-language failures that collide with ctx.terminal shorthand become diagnostics. */\nexport function errorPayload(reason: unknown, fallback = \"error without a valid payload\"): unknown {\n\treturn isInvalidErrorPayload(reason) ? new Error(fallback) : reason;\n}\n\nexport const TIER_START = 0;\nexport const TIER_CONTROL = 1;\nexport const TIER_NOTIFICATION = 2;\nexport const TIER_VALUE = 3;\nexport const TIER_SETTLE = 4;\nexport const TIER_TERMINAL = 5;\nexport const TIER_TEARDOWN = 6;\n\n/**\n * Tier const table (R-tier / D34). Tiers below value dispatch immediately; value\n * and above are batch-deferred. This is a compile-time const table (D18), not runtime config.\n */\nconst TIER: Record<MessageType, number> = {\n\tSTART: TIER_START,\n\tPAUSE: TIER_CONTROL,\n\tRESUME: TIER_CONTROL,\n\tDIRTY: TIER_NOTIFICATION,\n\tDATA: TIER_VALUE,\n\tRESOLVED: TIER_VALUE,\n\tINVALIDATE: TIER_SETTLE,\n\tCOMPLETE: TIER_TERMINAL,\n\tERROR: TIER_TERMINAL,\n\tTEARDOWN: TIER_TEARDOWN,\n};\n\nexport function messageTier(t: MessageType): number {\n\treturn TIER[t];\n}\n\n/** Value and above are deferred inside a batch (DATA/RESOLVED/INVALIDATE/terminal/teardown). */\nexport function isDeferredTier(t: MessageType): boolean {\n\treturn TIER[t] >= TIER_VALUE;\n}\n\n/** Value-tier messages (DATA/RESOLVED) occupy the tier-3 slot. */\nexport function isValueTier(t: MessageType): boolean {\n\treturn TIER[t] === TIER_VALUE;\n}\n\n/** The pause buffer holds the settle slice only: value-tier DATA/RESOLVED plus INVALIDATE. */\nexport function isPauseBufferedTier(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier === TIER_VALUE || tier === TIER_SETTLE;\n}\n\n/**\n * A TERMINAL message = tier 5 (COMPLETE | ERROR), R-tier / D34. Detected via the CENTRAL tier\n * table, NOT a per-variant `=== \"COMPLETE\" || === \"ERROR\"` check — so terminal routing stays\n * driven by the one const table (feedback_use_tier_for_signal_routing); discriminate COMPLETE vs\n * ERROR within the tier by the message type only where the handling actually differs.\n */\nexport function isTerminal(t: MessageType): boolean {\n\treturn TIER[t] === TIER_TERMINAL;\n}\n\n/**\n * ctx.up carries control tiers only (R-ctx-up / DR-5): DIRTY, PAUSE, RESUME,\n * INVALIDATE, TEARDOWN. DATA/RESOLVED (tier 3) and COMPLETE/ERROR (tier 5) are\n * down-only.\n */\nexport function isUpAllowed(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier !== TIER_VALUE && tier !== TIER_TERMINAL;\n}\n","/**\n * The fn-invocation context and per-dep input shapes.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-fn-contract (D8/D27), R-ctx-state (D23/D29), R-cleanup-hooks (D28), R-ctx-up.\n */\n\nimport type { Dispatcher } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport type { Node } from \"../node/node.js\";\nimport { type Message, SENTINEL, type Wave } from \"../protocol/messages.js\";\n\n/** A downstream sink callback (the only way to connect to a node's output). */\nexport type Sink = (msg: Message, delivery?: DeliveryMeta) => void;\n\n/** Internal delivery metadata used to preserve the upstream `ctx.down(msgs)` wave boundary. */\nexport interface DeliveryMeta {\n\treadonly wave: object;\n\treadonly last: boolean;\n}\n\n/**\n * Internal current-value reader. It is deliberately a symbol-backed implementation detail:\n * raw ctx exposes `waveData` + `terminal`; helpers below derive from that plus this dep cache.\n */\nexport const CTX_DEP_CACHE: unique symbol = Symbol(\"graphrefly.ctx.depCache\");\n\nexport interface CtxDepCache {\n\treadonly latest: readonly unknown[];\n}\n\n/** Internal node-construction binding for graph-local helper-created deps. */\nexport const CTX_NODE_BINDING: unique symbol = Symbol(\"graphrefly.ctx.nodeBinding\");\n\nexport interface CtxNodeBinding {\n\treadonly dispatcher: Dispatcher;\n\tcreate<T>(factory: () => Node<T>): Node<T>;\n}\n\n/** Per-dep wave projections: dep -> waves -> values/SENTINEL markers. */\nexport type WaveData = readonly (readonly (readonly unknown[])[])[];\n\n/** Terminal metadata parallel to `waveData`: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport type TerminalData = readonly unknown[];\n\nexport function isTerminalNone(t: unknown): boolean {\n\treturn t === false || t === undefined;\n}\n\nexport function isTerminalComplete(t: unknown): t is true {\n\treturn t === true;\n}\n\nexport function isTerminalError(t: unknown): boolean {\n\treturn !isTerminalNone(t) && !isTerminalComplete(t);\n}\n\nexport function terminalErrorValue(t: unknown): unknown {\n\treturn isTerminalError(t) ? t : undefined;\n}\n\n/**\n * Per-node private cross-wave state (R-ctx-state / D23,D29). Default fresh-lifecycle\n * wipe; `persist(true)` keeps it across lifecycle transitions.\n */\nexport interface CtxState {\n\tget<S = unknown>(): S | undefined;\n\tset<S = unknown>(v: S): void;\n\tpersist(on?: boolean): void;\n}\n\n/**\n * Deferred SELF-rewire (R-rewire-deferred / D47). A node fn may, DURING its run, request a\n * mutation of its OWN dep set; the request is QUEUED and applied at the committed wave boundary\n * (after the current wave settles / batch commit / final-lock RESUME) as a fresh wave, reusing\n * R-rewire surgical/Option-C semantics (D42). This is the ONLY legal self-triggered rewire — an\n * IMMEDIATE in-fn `node.subscribeDep/unsubscribeDep/replaceDeps` is the D37 mid-fn feedback-cycle ERROR. An\n * added cached dep pushes `[DIRTY,DATA]` on the boundary wave (R-push-subscribe); a removed dep\n * is drained and, if it loses its last subscriber, `_deactivate`s + fires `onDeactivation`\n * (input-side teardown — the basis for higher-order operator cancellation / abortInFlight).\n */\nexport interface RewireNext {\n\t/** Defer subscribing to a dep (paired with the re-supplied fn — positional fn-deps lock, SD-1). */\n\tsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer unsubscribing from a dep (its source is torn down if it loses its last subscriber). */\n\tunsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer replacing the whole dep set (surgical: kept deps untouched, removed drained, added fresh-subscribe). */\n\treplaceDeps(deps: Node<unknown>[], fn: NodeFn): void;\n}\n\n/**\n * The single argument to a node fn: `(ctx) => void` (R-fn-contract / D8). All emission\n * is explicit via `ctx.down`; there is no return-value framing.\n */\nexport interface Ctx {\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). IMMEDIATE. `towardDep` (a dep index)\n\t * routes the wave up ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t * A pull DEMAND is `up([[RESUME, pullId]])` — but for a SELF-demand (demanding a dep this fn also\n\t * reads) use {@link Ctx.upNext} instead, since an immediate demand whose delivery loops back\n\t * re-enters this fn mid-wave (D37 / R-reentrancy).\n\t */\n\tup(msgs: Wave, towardDep?: number): void;\n\t/** Emit downstream toward sinks. */\n\tdown(msgs: Wave): void;\n\t/**\n\t * The single raw dep-value input surface (R-ctx-wave-data / D77): dep -> upstream waves ->\n\t * per-wave DATA payloads and INVALIDATE/SENTINEL markers. `waveData[i] = []` means dep i\n\t * delivered no wave to this invocation; `waveData[i] = [[]]` means RESOLVED-only.\n\t */\n\twaveData: WaveData;\n\t/** Terminal metadata for the same invocation; terminal values never enter `waveData`. */\n\tterminal: TerminalData;\n\tstate: CtxState;\n\t/** Release external resources on deactivation (R-cleanup-hooks). */\n\tonDeactivation(fn: () => void): void;\n\t/** Flush on INVALIDATE (R-cleanup-hooks). */\n\tonInvalidate(fn: () => void): void;\n\t/** Graph-owned environment drivers for source/adapter boundaries (D130/D131). */\n\tenvironment(): EnvironmentDrivers;\n\t/**\n\t * Deferred SELF-rewire (R-rewire-deferred / D47) — the substrate affordance higher-order\n\t * operators (switchMap/mergeMap/concatMap/exhaustMap/flatMap) use to grow/shrink their own\n\t * inner-source dep set in response to their own data. Always present; see {@link RewireNext}.\n\t */\n\trewireNext: RewireNext;\n\t/**\n\t * Deferred up — the boundary-deferred form of {@link Ctx.up} (R-up-routing / R-pull / D59). Routes\n\t * `msgs` up from this node at the COMMITTED wave boundary (broadcast, or up the single `towardDep`\n\t * edge), riding the same R-rewire-deferred (D47) drain as {@link RewireNext}. This is the\n\t * SELF-DEMAND path: a consumer issues `ctx.upNext([[RESUME, pullId]])` to demand a pull dep it\n\t * ALSO reads — the cone-routed RESUME reaches the pullId-holder, whose delivery loops back as a\n\t * FRESH wave (not a mid-fn re-entry → no D37). The consumer accepts one-wave latency (the\n\t * HTTP-request model). No node reference needed: the author writes the pullId verbatim.\n\t */\n\tupNext(msgs: Wave, towardDep?: number): void;\n\t/**\n\t * Read a dep's latest value by index (dynamicNode only, R-dynamic-node / D35).\n\t * Present only on dynamicNode fns; all declared deps still participate in wave\n\t * tracking. Under D49/R-resolved-undirty an unread dep's change still fires the fn,\n\t * which re-emits its (unchanged) output as a DATA occurrence — there is NO equals-\n\t * absorption; pair with distinctUntilChanged to suppress unchanged re-emits (opt-in).\n\t */\n\ttrack?(depIndex: number): unknown;\n\t[CTX_DEP_CACHE]?: CtxDepCache;\n\t[CTX_NODE_BINDING]?: CtxNodeBinding;\n}\n\n/** A node fn (R-fn-contract). Registered in a dispatcher pool, indexed by Handle. */\nexport type NodeFn = (ctx: Ctx) => void;\n\n/** Number of declared dep slots visible in this invocation. */\nexport function depCount(ctx: Ctx): number {\n\treturn ctx.waveData.length;\n}\n\n/** DATA/SENTINEL projection batches delivered by one dep in this invocation. */\nexport function depWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\treturn ctx.waveData[depIndex] ?? [];\n}\n\n/** Flattened DATA projection for old event-counting operator bodies; null = no wave. */\nexport function depBatch(ctx: Ctx, depIndex: number): readonly unknown[] | null {\n\tconst waves = depWaves(ctx, depIndex);\n\tif (waves.length === 0) return null;\n\tconst flattened = waves.flat().filter((v) => v !== SENTINEL);\n\treturn flattened.length === 0 ? [] : flattened;\n}\n\n/** Latest cached DATA for a dep, derived from implementation-owned dep cache. */\nexport function depLatest(ctx: Ctx, depIndex: number): unknown {\n\treturn ctx[CTX_DEP_CACHE]?.latest[depIndex];\n}\n\n/** Terminal metadata for one dep: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport function depTerminal(ctx: Ctx, depIndex: number): unknown {\n\tconst t = ctx.terminal[depIndex];\n\treturn t === undefined ? false : t;\n}\n","/**\n * Neutral JSON/encoding utilities (D96).\n *\n * Shared by graph checkpoints and storage bindings; neither layer owns the strict JSON\n * scanner/canonicalization contract.\n */\n\n/** Typed byte codec for D82 storage binding helpers and D96 shared JSON surfaces. */\nexport interface Codec<T> {\n\tencode(value: T): Uint8Array;\n\tdecode(bytes: Uint8Array): T;\n}\n\nexport type StrictJsonScalar = null | boolean | number | string;\nexport type StrictJsonValue =\n\t| StrictJsonScalar\n\t| readonly StrictJsonValue[]\n\t| { readonly [key: string]: StrictJsonValue };\nexport type StrictJsonObject = Readonly<Record<string, StrictJsonValue>>;\n\ntype JsonValue = StrictJsonValue;\n\nconst JS_MIN_NORMAL_NUMBER = 2 ** -1022;\n\nfunction assertStableJsonNumber(value: number, path: string): void {\n\tif (!Number.isFinite(value)) {\n\t\tthrow new TypeError(`stableJsonString: non-finite number at ${path}`);\n\t}\n}\n\nfunction assertStrictJsonNumber(value: number, path: string): void {\n\tassertStableJsonNumber(value, path);\n\tif (Object.is(value, -0)) {\n\t\tthrow new TypeError(`stableJsonString: non-canonical number at ${path}`);\n\t}\n\tconst abs = Math.abs(value);\n\tif (abs > 0 && abs < JS_MIN_NORMAL_NUMBER) {\n\t\tthrow new TypeError(`stableJsonString: subnormal number at ${path}`);\n\t}\n\tif (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n\t\tthrow new TypeError(`stableJsonString: integer outside safe range at ${path}`);\n\t}\n}\n\nfunction sortedJsonValue(\n\tvalue: unknown,\n\tseen = new Set<object>(),\n\tpath = \"$\",\n\tstrictNumbers = false,\n): JsonValue {\n\tif (value === null) return null;\n\tif (typeof value === \"string\" || typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") {\n\t\tif (strictNumbers) assertStrictJsonNumber(value, path);\n\t\telse assertStableJsonNumber(value, path);\n\t\treturn value;\n\t}\n\tif (typeof value !== \"object\") {\n\t\tthrow new TypeError(`stableJsonString: value at ${path} is not JSON-encodable`);\n\t}\n\tif (seen.has(value)) throw new TypeError(`stableJsonString: circular reference at ${path}`);\n\tconst proto = Object.getPrototypeOf(value);\n\tif (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {\n\t\tthrow new TypeError(`stableJsonString: non-plain object at ${path}`);\n\t}\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\t\tthrow new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);\n\t\t\t}\n\t\t\tfor (const key of Object.getOwnPropertyNames(value)) {\n\t\t\t\tconst isIndex =\n\t\t\t\t\t/^(0|[1-9]\\d*)$/.test(key) &&\n\t\t\t\t\tNumber.isSafeInteger(Number(key)) &&\n\t\t\t\t\tNumber(key) < value.length;\n\t\t\t\tif (key !== \"length\" && !isIndex) {\n\t\t\t\t\tthrow new TypeError(`stableJsonString: non-index array property at ${path}.${key}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst out: JsonValue[] = [];\n\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\tif (!(i in value)) {\n\t\t\t\t\tthrow new TypeError(`stableJsonString: sparse array hole at ${path}[${i}]`);\n\t\t\t\t}\n\t\t\t\tout.push(sortedJsonValue(value[i], seen, `${path}[${i}]`, strictNumbers));\n\t\t\t}\n\t\t\treturn out;\n\t\t}\n\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\tthrow new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);\n\t\t}\n\t\tconst out: Record<string, JsonValue> = Object.create(null);\n\t\tfor (const key of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tout[key] = sortedJsonValue(\n\t\t\t\t(value as Record<string, unknown>)[key],\n\t\t\t\tseen,\n\t\t\t\t`${path}.${key}`,\n\t\t\t\tstrictNumbers,\n\t\t\t);\n\t\t}\n\t\treturn out;\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\n/** Stable JSON string: object keys sort by code-unit order for deterministic storage/checkpoint bytes. */\nexport function stableJsonString(value: unknown): string {\n\treturn JSON.stringify(sortedJsonValue(value));\n}\n\nfunction strictStableJsonString(value: unknown): string {\n\treturn JSON.stringify(sortedJsonValue(value, new Set<object>(), \"$\", true));\n}\n\n/** Build a JSON codec using stable object-key ordering. */\nexport function jsonCodecFor<T>(): Codec<T> {\n\tconst encoder = new TextEncoder();\n\tconst decoder = new TextDecoder();\n\treturn {\n\t\tencode(value: T): Uint8Array {\n\t\t\treturn encoder.encode(stableJsonString(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): T {\n\t\t\treturn JSON.parse(decoder.decode(bytes)) as T;\n\t\t},\n\t};\n}\n\n/** Default stable JSON codec for unknown values. */\nexport const jsonCodec: Codec<unknown> = jsonCodecFor<unknown>();\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n\tif (a.byteLength !== b.byteLength) return false;\n\tfor (let i = 0; i < a.byteLength; i += 1) {\n\t\tif (a[i] !== b[i]) return false;\n\t}\n\treturn true;\n}\n\nfunction hasUnpairedSurrogate(value: string): boolean {\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tconst code = value.charCodeAt(i);\n\t\tif (code >= 0xd800 && code <= 0xdbff) {\n\t\t\tconst next = value.charCodeAt(i + 1);\n\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\ti += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (code >= 0xdc00 && code <= 0xdfff) return true;\n\t}\n\treturn false;\n}\n\nfunction assertNoUnpairedSurrogates(value: unknown, seen = new Set<object>(), path = \"$\"): void {\n\tif (typeof value === \"string\") {\n\t\tif (hasUnpairedSurrogate(value)) {\n\t\t\tthrow new TypeError(`strictJsonCodec: unpaired surrogate at ${path}`);\n\t\t}\n\t\treturn;\n\t}\n\tif (value === null || typeof value !== \"object\") return;\n\tif (seen.has(value)) return;\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\tassertNoUnpairedSurrogates(value[i], seen, `${path}[${i}]`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tfor (const key of Object.keys(value as Record<string, unknown>)) {\n\t\t\tif (hasUnpairedSurrogate(key)) {\n\t\t\t\tthrow new TypeError(`strictJsonCodec: unpaired surrogate at ${path}.${key}`);\n\t\t\t}\n\t\t\tassertNoUnpairedSurrogates((value as Record<string, unknown>)[key], seen, `${path}.${key}`);\n\t\t}\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\nfunction assertNoDuplicateJsonObjectKeys(text: string): void {\n\tlet index = 0;\n\n\tfunction fail(message: string): never {\n\t\tthrow new TypeError(`strictJsonCodec: ${message}`);\n\t}\n\n\tfunction skipWhitespace(): void {\n\t\twhile (/\\s/.test(text[index] ?? \"\")) index += 1;\n\t}\n\n\tfunction readJsonString(): string {\n\t\tconst start = index;\n\t\tindex += 1;\n\t\twhile (index < text.length) {\n\t\t\tconst ch = text[index];\n\t\t\tif (ch === '\"') {\n\t\t\t\tindex += 1;\n\t\t\t\ttry {\n\t\t\t\t\treturn JSON.parse(text.slice(start, index)) as string;\n\t\t\t\t} catch {\n\t\t\t\t\tfail(\"malformed JSON string\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ch === \"\\\\\") {\n\t\t\t\tindex += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tindex += 1;\n\t\t}\n\t\tfail(\"unterminated JSON string\");\n\t}\n\n\tfunction consumeLiteral(literal: string): void {\n\t\tif (text.slice(index, index + literal.length) !== literal) {\n\t\t\tfail(`malformed JSON near byte ${index}`);\n\t\t}\n\t\tindex += literal.length;\n\t}\n\n\tfunction consumeNumber(): void {\n\t\tconst match = /^-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?/.exec(text.slice(index));\n\t\tif (!match) fail(`malformed JSON number near byte ${index}`);\n\t\tindex += match[0].length;\n\t}\n\n\tfunction parseValue(path: string): void {\n\t\tskipWhitespace();\n\t\tconst ch = text[index];\n\t\tif (ch === \"{\") {\n\t\t\tparseObject(path);\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"[\") {\n\t\t\tparseArray(path);\n\t\t\treturn;\n\t\t}\n\t\tif (ch === '\"') {\n\t\t\treadJsonString();\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"t\") {\n\t\t\tconsumeLiteral(\"true\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"f\") {\n\t\t\tconsumeLiteral(\"false\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"n\") {\n\t\t\tconsumeLiteral(\"null\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"-\" || (ch !== undefined && ch >= \"0\" && ch <= \"9\")) {\n\t\t\tconsumeNumber();\n\t\t\treturn;\n\t\t}\n\t\tfail(`malformed JSON near byte ${index}`);\n\t}\n\n\tfunction parseObject(path: string): void {\n\t\tconst keys = new Set<string>();\n\t\tindex += 1;\n\t\tskipWhitespace();\n\t\tif (text[index] === \"}\") {\n\t\t\tindex += 1;\n\t\t\treturn;\n\t\t}\n\t\twhile (index < text.length) {\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] !== '\"') fail(`expected object key near byte ${index}`);\n\t\t\tconst key = readJsonString();\n\t\t\tif (keys.has(key)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`strictJsonCodec: duplicate object key ${JSON.stringify(key)} at ${path}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tkeys.add(key);\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] !== \":\") fail(`expected ':' after object key near byte ${index}`);\n\t\t\tindex += 1;\n\t\t\tparseValue(`${path}.${key}`);\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] === \",\") {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (text[index] === \"}\") {\n\t\t\t\tindex += 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfail(`expected ',' or '}' near byte ${index}`);\n\t\t}\n\t\tfail(\"unterminated JSON object\");\n\t}\n\n\tfunction parseArray(path: string): void {\n\t\tindex += 1;\n\t\tskipWhitespace();\n\t\tif (text[index] === \"]\") {\n\t\t\tindex += 1;\n\t\t\treturn;\n\t\t}\n\t\tlet item = 0;\n\t\twhile (index < text.length) {\n\t\t\tparseValue(`${path}[${item}]`);\n\t\t\titem += 1;\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] === \",\") {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (text[index] === \"]\") {\n\t\t\t\tindex += 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfail(`expected ',' or ']' near byte ${index}`);\n\t\t}\n\t\tfail(\"unterminated JSON array\");\n\t}\n\n\tparseValue(\"$\");\n\tskipWhitespace();\n\tif (index !== text.length) fail(`trailing JSON token near byte ${index}`);\n}\n\n/**\n * Build a strict canonical JSON codec (D84/D87/D96).\n * The strict surface rejects malformed UTF-8, duplicate object keys, non-canonical bytes,\n * unpaired surrogates, and values that cannot round-trip through stable JSON.\n */\nexport function strictJsonCodecFor<T>(): Codec<T> {\n\tconst encoder = new TextEncoder();\n\tconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\treturn {\n\t\tencode(value: T): Uint8Array {\n\t\t\tassertNoUnpairedSurrogates(value);\n\t\t\treturn encoder.encode(strictStableJsonString(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): T {\n\t\t\tconst text = decoder.decode(bytes);\n\t\t\tassertNoDuplicateJsonObjectKeys(text);\n\t\t\tconst decoded = JSON.parse(text) as unknown;\n\t\t\tassertNoUnpairedSurrogates(decoded);\n\t\t\tconst canonical = encoder.encode(strictStableJsonString(decoded));\n\t\t\tif (!bytesEqual(bytes, canonical)) {\n\t\t\t\tthrow new TypeError(\"strictJsonCodec: bytes are not canonical stable JSON\");\n\t\t\t}\n\t\t\treturn decoded as T;\n\t\t},\n\t};\n}\n\n/** Default strict canonical JSON codec for unknown values. */\nexport const strictJsonCodec: Codec<unknown> = strictJsonCodecFor<unknown>();\n\n/** D113 neutral helper for strict canonical JSON UTF-8 bytes. */\nexport function strictCanonicalJsonBytes(value: unknown): Uint8Array {\n\treturn strictJsonCodec.encode(value);\n}\n\n/** Validate and normalize a host value into strict canonical JSON data. */\nexport function assertStrictJsonValue(value: unknown, label = \"strictJsonValue\"): StrictJsonValue {\n\ttry {\n\t\treturn strictJsonCodec.decode(strictJsonCodec.encode(value)) as StrictJsonValue;\n\t} catch (cause) {\n\t\tconst message = cause instanceof Error ? cause.message : String(cause);\n\t\tthrow new TypeError(`${label}: value is not strict JSON compatible: ${message}`, { cause });\n\t}\n}\n\n/** Validate and normalize a host value into a strict canonical JSON object. */\nexport function assertStrictJsonObject(\n\tvalue: unknown,\n\tlabel = \"strictJsonObject\",\n): StrictJsonObject {\n\tconst normalized = assertStrictJsonValue(value, label);\n\tif (normalized === null || typeof normalized !== \"object\" || Array.isArray(normalized)) {\n\t\tthrow new TypeError(`${label}: value must be a strict JSON object`);\n\t}\n\treturn normalized as StrictJsonObject;\n}\n","/**\n * Passive semantic-memory vocabulary and deterministic helpers.\n *\n * D158 splits semantic memory into horizontal patterns and vertical solutions.\n * This module intentionally owns no graph nodes, storage restore, timers,\n * subscriptions, vector indexes, knowledge graphs, or agentic runtime.\n */\n\nimport type { StrictJsonValue } from \"../json/codec.js\";\n\n/** Stable identity for a semantic-memory fact. */\nexport type FactId = string;\n\n/** Shard partition key used by passive sharding helpers. */\nexport type ShardKey = string | number;\n\n/**\n * A single semantic-memory fact. Pattern convention only: this is not a\n * protocol message, storage record owner, restore contract, or graph runtime.\n */\nexport interface MemoryFragment<T = unknown> {\n\treadonly id: FactId;\n\treadonly payload: T;\n\t/** Transaction time, typically monotonic nanoseconds. */\n\treadonly tNs: bigint;\n\t/** Valid-time start. Undefined means unbounded past. */\n\treadonly validFrom?: bigint;\n\t/** Valid-time end. Undefined means currently valid. */\n\treadonly validTo?: bigint;\n\t/** Confidence score in the closed interval [0, 1]. */\n\treadonly confidence: number;\n\treadonly tags: readonly string[];\n\t/** Fact ids this fragment derives from or depends on. */\n\treadonly sources: readonly FactId[];\n\treadonly embedding?: readonly number[];\n\treadonly parentFragmentId?: FactId;\n\treadonly provenance?: string;\n}\n\n/** Columnar passive store vocabulary for callers that keep memory facts outside GraphReFly. */\nexport interface FactStore<T = unknown> {\n\treadonly byId: ReadonlyMap<FactId, MemoryFragment<T>>;\n}\n\n/** Read-only projection passed to scoring policies; it exposes no mutation surface. */\nexport interface StoreReadHandle<T = unknown> {\n\tget(id: FactId): MemoryFragment<T> | undefined;\n\thas(id: FactId): boolean;\n\treadonly size: number;\n\tvalues(): IterableIterator<MemoryFragment<T>>;\n}\n\nexport type ScoringPolicy<T = unknown> = (\n\tfragment: MemoryFragment<T>,\n\tstore: StoreReadHandle<T>,\n) => number;\nexport type DecayPolicy = (confidence: number, ageNs: bigint) => number;\nexport type AdmissionFilter<T = unknown> = (fragment: MemoryFragment<T>) => boolean;\n\n/** Outcome signal for policy learning. This is an application fact, not a protocol event. */\nexport interface OutcomeSignal {\n\treadonly factId: FactId;\n\treadonly reward: number;\n}\n\n/** Passive structured query over semantic-memory facts. */\nexport interface MemoryQuery {\n\treadonly tags?: readonly string[];\n\treadonly asOf?: bigint;\n\treadonly minConfidence?: number;\n\treadonly limit?: number;\n}\n\nexport interface MemoryAnswer<T = unknown> {\n\treadonly query: MemoryQuery;\n\treadonly results: readonly MemoryFragment<T>[];\n}\n\nexport type KnowledgeAssertionStrictJsonValue = StrictJsonValue;\n\n/** Passive KG endpoint vocabulary. Entity ids are DATA keys, not graph node ids. */\nexport interface KnowledgeAssertionSubject {\n\treadonly id: FactId;\n\treadonly type?: string;\n}\n\n/** Passive KG object/value vocabulary. */\nexport type KnowledgeAssertionObject =\n\t| {\n\t\t\treadonly kind: \"entity\";\n\t\t\treadonly id: FactId;\n\t\t\treadonly type?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"value\";\n\t\t\treadonly value: KnowledgeAssertionStrictJsonValue;\n\t\t\treadonly valueType?: string;\n\t };\n\n/** Passive KG assertion fact consumed by lower semantic-memory graph patterns. */\nexport interface KnowledgeAssertion {\n\treadonly id: FactId;\n\treadonly recordId?: FactId;\n\treadonly fragmentId?: FactId;\n\treadonly subject: KnowledgeAssertionSubject;\n\treadonly predicate: string;\n\treadonly object: KnowledgeAssertionObject;\n\treadonly confidence?: number;\n\treadonly sources?: readonly FactId[];\n\treadonly provenance?: string;\n}\n\n/** Entry vocabulary for ranked collection-like memory views. */\nexport interface CollectionEntry<T = unknown> {\n\treadonly id: string;\n\treadonly value: T;\n\treadonly createdAtNs: bigint;\n\treadonly lastAccessNs: bigint;\n\treadonly baseScore: number;\n}\n\nexport type RankedCollectionEntry<T = unknown> = CollectionEntry<T> & {\n\treadonly score: number;\n};\n\nexport type CollectionScoreFn<T = unknown> = (value: T) => number;\n\n/** Query shape shared by passive retrieval/ranking helpers. */\nexport interface RetrievalQuery {\n\treadonly text?: string;\n\treadonly vector?: readonly number[];\n\treadonly entityIds?: readonly string[];\n\treadonly context?: readonly string[];\n}\n\nexport interface VectorSearchResult<TMeta = unknown> {\n\treadonly id: string;\n\treadonly score: number;\n\treadonly meta?: TMeta;\n}\n\nexport interface RetrievalEntry<TMem = unknown> {\n\treadonly key: string;\n\treadonly value: TMem;\n\treadonly score: number;\n\treadonly sources: ReadonlyArray<\"vector\" | \"graph\" | \"store\">;\n\treadonly context?: readonly string[];\n}\n\nexport interface RetrievalTrace<TMem = unknown> {\n\treadonly vectorCandidates: ReadonlyArray<VectorSearchResult<TMem>>;\n\treadonly graphExpanded: ReadonlyArray<string>;\n\treadonly ranked: ReadonlyArray<RetrievalEntry<TMem>>;\n\treadonly packed: ReadonlyArray<RetrievalEntry<TMem>>;\n}\n\n/** Generic per-dimension thresholds. Any configured dimension below threshold is rejected. */\nexport type AdmissionThresholds<Dims extends string> = Partial<Record<Dims, number>>;\n\nexport interface AdmissionScoredOptions<Dims extends string, TRaw = unknown> {\n\treadonly scoreFn: (raw: TRaw) => Readonly<Record<Dims, number>>;\n\treadonly thresholds?: AdmissionThresholds<Dims>;\n}\n\nexport interface AdmissionScores {\n\treadonly persistence: number;\n\treadonly structure: number;\n\treadonly personalValue: number;\n}\n\nexport interface AdmissionScore3DOptions {\n\treadonly scoreFn: (raw: unknown) => AdmissionScores;\n\treadonly persistenceThreshold?: number;\n\treadonly personalValueThreshold?: number;\n\treadonly requireStructured?: boolean;\n}\n\nexport interface ShardByTenantOptions {\n\treadonly tenants?: readonly string[];\n\treadonly shardCount?: number;\n}\n\nexport interface ShardByTenantConfig<T = unknown> {\n\treadonly shardBy: (fragment: MemoryFragment<T>) => ShardKey;\n\treadonly shardCount: number;\n}\n\nexport interface MemoryFragmentValidation {\n\treadonly ok: boolean;\n\treadonly errors: readonly string[];\n}\n\n/** Cosine similarity over zero-padded vectors. Non-finite results normalize to 0. */\nexport function cosineSimilarity(a: readonly number[], b: readonly number[]): number {\n\tconst n = Math.max(a.length, b.length);\n\tlet dot = 0;\n\tlet na = 0;\n\tlet nb = 0;\n\tfor (let i = 0; i < n; i += 1) {\n\t\tconst av = a[i] ?? 0;\n\t\tconst bv = b[i] ?? 0;\n\t\tdot += av * bv;\n\t\tna += av * av;\n\t\tnb += bv * bv;\n\t}\n\tif (na === 0 || nb === 0) return 0;\n\tconst score = dot / Math.sqrt(na * nb);\n\treturn Number.isFinite(score) ? score : 0;\n}\n\n/**\n * Returns true when a fragment is valid at `asOf`.\n *\n * Omitted `asOf` has no clock to compare against, so it admits only fragments\n * that are live and not valid-time delayed.\n */\nexport function memoryFragmentValidAt(fragment: MemoryFragment, asOf?: bigint): boolean {\n\tif (asOf === undefined) return fragment.validTo === undefined && fragment.validFrom === undefined;\n\tif (fragment.validFrom !== undefined && fragment.validFrom > asOf) return false;\n\tif (fragment.validTo !== undefined && fragment.validTo <= asOf) return false;\n\treturn true;\n}\n\n/** Pure structured-query predicate over a single fragment. */\nexport function memoryFragmentMatchesQuery(\n\tfragment: MemoryFragment,\n\tquery: MemoryQuery = {},\n): boolean {\n\tif (!memoryFragmentValidAt(fragment, query.asOf)) return false;\n\tif (query.minConfidence !== undefined && fragment.confidence < query.minConfidence) return false;\n\tif (\n\t\tquery.tags &&\n\t\tquery.tags.length > 0 &&\n\t\t!query.tags.some((tag) => fragment.tags.includes(tag))\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/** Filter and rank fragments by confidence desc, then transaction time desc. */\nexport function filterMemoryFragments<T>(\n\tfragments: Iterable<MemoryFragment<T>>,\n\tquery: MemoryQuery = {},\n): readonly MemoryFragment<T>[] {\n\tconst results = [...fragments].filter((fragment) => memoryFragmentMatchesQuery(fragment, query));\n\tresults.sort((a, b) => b.confidence - a.confidence || compareBigIntDesc(a.tNs, b.tNs));\n\treturn query.limit === undefined ? results : results.slice(0, Math.max(0, query.limit));\n}\n\n/** Validate the passive MemoryFragment shape without throwing. */\nexport function validateMemoryFragment(value: unknown): MemoryFragmentValidation {\n\tconst errors: string[] = [];\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn { ok: false, errors: [\"fragment must be an object\"] };\n\t}\n\tconst fragment = value as Partial<MemoryFragment>;\n\tif (typeof fragment.id !== \"string\" || fragment.id.length === 0) {\n\t\terrors.push(\"id must be a non-empty string\");\n\t}\n\tif (!Object.hasOwn(fragment, \"payload\")) {\n\t\terrors.push(\"payload must be present\");\n\t}\n\tif (typeof fragment.tNs !== \"bigint\") {\n\t\terrors.push(\"tNs must be a bigint\");\n\t}\n\tconst confidence = fragment.confidence;\n\tif (\n\t\t!Number.isFinite(confidence) ||\n\t\tconfidence === undefined ||\n\t\tconfidence < 0 ||\n\t\tconfidence > 1\n\t) {\n\t\terrors.push(\"confidence must be a finite number in [0, 1]\");\n\t}\n\tif (!isDenseArrayOf(fragment.tags, (tag): tag is string => typeof tag === \"string\")) {\n\t\terrors.push(\"tags must be a readonly string array\");\n\t}\n\tif (!isDenseArrayOf(fragment.sources, (source): source is string => typeof source === \"string\")) {\n\t\terrors.push(\"sources must be a readonly string array\");\n\t}\n\tif (fragment.validFrom !== undefined && typeof fragment.validFrom !== \"bigint\") {\n\t\terrors.push(\"validFrom must be a bigint when present\");\n\t}\n\tif (fragment.validTo !== undefined && typeof fragment.validTo !== \"bigint\") {\n\t\terrors.push(\"validTo must be a bigint when present\");\n\t}\n\tif (\n\t\ttypeof fragment.validFrom === \"bigint\" &&\n\t\ttypeof fragment.validTo === \"bigint\" &&\n\t\tfragment.validFrom >= fragment.validTo\n\t) {\n\t\terrors.push(\"validFrom must be earlier than validTo\");\n\t}\n\tif (\n\t\tfragment.embedding !== undefined &&\n\t\t!isDenseArrayOf(fragment.embedding, (component): component is number =>\n\t\t\tNumber.isFinite(component),\n\t\t)\n\t) {\n\t\terrors.push(\"embedding must be a finite number array when present\");\n\t}\n\tif (fragment.parentFragmentId !== undefined && typeof fragment.parentFragmentId !== \"string\") {\n\t\terrors.push(\"parentFragmentId must be a string when present\");\n\t}\n\tif (fragment.provenance !== undefined && typeof fragment.provenance !== \"string\") {\n\t\terrors.push(\"provenance must be a string when present\");\n\t}\n\treturn { ok: errors.length === 0, errors };\n}\n\nexport function isMemoryFragment(value: unknown): value is MemoryFragment {\n\treturn validateMemoryFragment(value).ok;\n}\n\n/**\n * Generic N-dimension admission filter. Missing or non-finite thresholded scores reject.\n */\nexport function admissionScored<Dims extends string, TRaw = unknown>(\n\topts: AdmissionScoredOptions<Dims, TRaw>,\n): (raw: TRaw) => boolean {\n\tconst thresholds = opts.thresholds ?? ({} as AdmissionThresholds<Dims>);\n\treturn (raw: TRaw): boolean => {\n\t\tconst scores = opts.scoreFn(raw);\n\t\tfor (const dim of Object.keys(thresholds) as Dims[]) {\n\t\t\tconst min = thresholds[dim];\n\t\t\tif (min === undefined) continue;\n\t\t\tconst score = scores[dim];\n\t\t\tconst safe = Number.isFinite(score) ? (score as number) : Number.NEGATIVE_INFINITY;\n\t\t\tif (safe < min) return false;\n\t\t}\n\t\treturn true;\n\t};\n}\n\n/** Three-axis admission sugar for persistence / structure / personal-value scoring. */\nexport function admissionFilter3D(opts: AdmissionScore3DOptions): (raw: unknown) => boolean {\n\treturn (raw: unknown): boolean => {\n\t\tconst scores = opts.scoreFn(raw);\n\t\tif (!scoreAtLeast(scores.persistence, opts.persistenceThreshold ?? 0.3)) return false;\n\t\tif (!scoreAtLeast(scores.personalValue, opts.personalValueThreshold ?? 0.3)) return false;\n\t\tif (!opts.requireStructured) return true;\n\t\treturn scoreAtLeast(scores.structure, Number.MIN_VALUE);\n\t};\n}\n\n/** Build a passive `{ shardBy, shardCount }` pair for tenant-isolated sharding. */\nexport function shardByTenant<T>(\n\ttenantOf: (fragment: MemoryFragment<T>) => string,\n\topts: ShardByTenantOptions = {},\n): ShardByTenantConfig<T> {\n\tif (opts.tenants && opts.tenants.length > 0) {\n\t\tconst tenants = [...new Set(opts.tenants)];\n\t\tconst index = new Map(tenants.map((tenant, i) => [tenant, i] as const));\n\t\tconst overflow = tenants.length;\n\t\treturn {\n\t\t\tshardBy: (fragment) => index.get(tenantOf(fragment)) ?? overflow,\n\t\t\tshardCount: tenants.length + 1,\n\t\t};\n\t}\n\tconst configuredShardCount = opts.shardCount ?? 4;\n\tconst shardCount = Number.isSafeInteger(configuredShardCount)\n\t\t? Math.max(1, configuredShardCount)\n\t\t: 4;\n\treturn { shardBy: (fragment) => tenantOf(fragment), shardCount };\n}\n\nfunction compareBigIntDesc(a: bigint, b: bigint): number {\n\tif (a === b) return 0;\n\treturn a > b ? -1 : 1;\n}\n\nfunction isDenseArrayOf<T>(value: unknown, predicate: (item: unknown) => item is T): value is T[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !predicate(value[i])) return false;\n\t}\n\treturn true;\n}\n\nfunction scoreAtLeast(score: number, min: number): boolean {\n\treturn Number.isFinite(score) && score >= min;\n}\n","/**\n * Graph-visible semantic-memory retrieval patterns.\n *\n * D158 allows horizontal semantic-memory patterns when they are ordinary graph\n * nodes with declared deps and graph-visible facts. This file intentionally\n * owns no storage restore/hydration, scheduler, hidden subscription, vector DB,\n * retention loop, consolidation loop, Graph subclass, or protocol behavior.\n */\n\nimport { depBatch, depLatest } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\tcosineSimilarity,\n\ttype FactId,\n\tfilterMemoryFragments,\n\ttype KnowledgeAssertion,\n\ttype KnowledgeAssertionObject,\n\ttype KnowledgeAssertionSubject,\n\ttype MemoryAnswer,\n\ttype MemoryFragment,\n\ttype MemoryQuery,\n\tmemoryFragmentMatchesQuery,\n\tvalidateMemoryFragment,\n} from \"./semantic-memory.js\";\n\n/** Query shape for the first graph-visible retrieval bundle. */\nexport interface MemoryRetrievalQuery extends MemoryQuery {\n\t/** Optional dense embedding used only for deterministic in-memory ranking. */\n\treadonly vector?: readonly number[];\n}\n\nexport interface MemoryRetrievalCursor {\n\treadonly evaluation: number;\n\treadonly validFragments: number;\n\treadonly invalidFragments: number;\n\treadonly resultCount: number;\n}\n\nexport type MemoryRetrievalStatusState = \"ready\" | \"empty\" | \"partial\" | \"error\";\n\nexport interface MemoryRetrievalStatus {\n\treadonly state: MemoryRetrievalStatusState;\n\treadonly query: MemoryRetrievalQuery;\n\treadonly cursor: MemoryRetrievalCursor;\n}\n\nexport interface MemoryRetrievalIndex<T = unknown> {\n\treadonly ids: readonly FactId[];\n\treadonly byId: Readonly<Record<FactId, MemoryFragment<T>>>;\n\treadonly cursor: MemoryRetrievalCursor;\n}\n\nexport type MemoryRetrievalErrorCode =\n\t| \"duplicate-fragment-id\"\n\t| \"invalid-fragments-input\"\n\t| \"invalid-fragment\"\n\t| \"invalid-query\"\n\t| \"invalid-query-vector\";\n\nexport interface MemoryRetrievalError {\n\treadonly code: MemoryRetrievalErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly fragment?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: MemoryRetrievalCursor;\n}\n\nexport interface MemoryRetrievalSnapshot<T = unknown> {\n\treadonly fragments: readonly MemoryFragment<T>[];\n\treadonly indexed: MemoryRetrievalIndex<T>;\n\treadonly ranked: MemoryAnswer<T>;\n\treadonly status: MemoryRetrievalStatus;\n\treadonly errors: readonly MemoryRetrievalError[];\n\treadonly cursor: MemoryRetrievalCursor;\n}\n\nexport type MemoryRetrievalFact<T = unknown> = MemoryRetrievalSnapshot<T>;\n\nexport interface KnowledgeGraphEntity {\n\treadonly id: FactId;\n\treadonly type?: string;\n\treadonly assertionIds: readonly FactId[];\n\treadonly subjectAssertionIds: readonly FactId[];\n\treadonly objectAssertionIds: readonly FactId[];\n}\n\nexport interface KnowledgeGraphRelation {\n\treadonly assertionId: FactId;\n\treadonly subject: KnowledgeAssertionSubject;\n\treadonly predicate: string;\n\treadonly object: KnowledgeAssertionObject;\n\treadonly confidence?: number;\n\treadonly sources: readonly FactId[];\n\treadonly provenance?: string;\n}\n\nexport interface KnowledgeGraphTopic {\n\treadonly predicate: string;\n\treadonly assertionIds: readonly FactId[];\n\treadonly entityIds: readonly FactId[];\n}\n\nexport interface KnowledgeGraphIndex {\n\treadonly assertionIds: readonly FactId[];\n\treadonly entityIds: readonly FactId[];\n\treadonly relationIds: readonly FactId[];\n\treadonly predicates: readonly string[];\n}\n\nexport interface KnowledgeGraphPolicy {\n\treadonly allowedPredicates?: readonly string[];\n\treadonly requireEntityTypes?: boolean;\n}\n\nexport interface KnowledgeGraphCursor {\n\treadonly evaluation: number;\n\treadonly validAssertions: number;\n\treadonly invalidAssertions: number;\n\treadonly entityCount: number;\n\treadonly relationCount: number;\n\treadonly predicateCount: number;\n}\n\nexport type KnowledgeGraphStatusState = \"ready\" | \"empty\" | \"partial\" | \"error\";\n\nexport interface KnowledgeGraphStatus {\n\treadonly state: KnowledgeGraphStatusState;\n\treadonly cursor: KnowledgeGraphCursor;\n}\n\nexport type KnowledgeGraphErrorCode =\n\t| \"invalid-assertions-input\"\n\t| \"invalid-assertion\"\n\t| \"duplicate-assertion-id\"\n\t| \"invalid-policy\"\n\t| \"policy-conflict\";\n\nexport interface KnowledgeGraphError {\n\treadonly code: KnowledgeGraphErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly assertionId?: FactId;\n\treadonly assertion?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: KnowledgeGraphCursor;\n}\n\nexport interface KnowledgeGraphSnapshot {\n\treadonly assertions: readonly KnowledgeAssertion[];\n\treadonly entities: readonly KnowledgeGraphEntity[];\n\treadonly relations: readonly KnowledgeGraphRelation[];\n\treadonly topics: readonly KnowledgeGraphTopic[];\n\treadonly index: KnowledgeGraphIndex;\n\treadonly status: KnowledgeGraphStatus;\n\treadonly errors: readonly KnowledgeGraphError[];\n\treadonly cursor: KnowledgeGraphCursor;\n}\n\nexport interface KnowledgeGraphReducerBundle {\n\treadonly input: {\n\t\treadonly assertions: Node<readonly unknown[]>;\n\t\treadonly policy?: Node<KnowledgeGraphPolicy>;\n\t};\n\treadonly snapshot: Node<KnowledgeGraphSnapshot>;\n\treadonly assertions: Node<readonly KnowledgeAssertion[]>;\n\treadonly entities: Node<readonly KnowledgeGraphEntity[]>;\n\treadonly relations: Node<readonly KnowledgeGraphRelation[]>;\n\treadonly topics: Node<readonly KnowledgeGraphTopic[]>;\n\treadonly index: Node<KnowledgeGraphIndex>;\n\treadonly status: Node<KnowledgeGraphStatus>;\n\treadonly errors: Node<readonly KnowledgeGraphError[]>;\n\treadonly cursor: Node<KnowledgeGraphCursor>;\n}\n\nexport interface KnowledgeGraphReducerBundleOptions {\n\treadonly name?: string;\n\treadonly assertions: Node<readonly unknown[]>;\n\treadonly policy?: Node<KnowledgeGraphPolicy>;\n}\n\nexport interface MemoryRetrievalBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly fragments: Node<readonly unknown[]>;\n\t\treadonly query: Node<MemoryRetrievalQuery>;\n\t};\n\treadonly snapshot: Node<MemoryRetrievalSnapshot<T>>;\n\treadonly fragments: Node<readonly MemoryFragment<T>[]>;\n\treadonly indexed: Node<MemoryRetrievalIndex<T>>;\n\treadonly ranked: Node<MemoryAnswer<T>>;\n\treadonly status: Node<MemoryRetrievalStatus>;\n\treadonly errors: Node<readonly MemoryRetrievalError[]>;\n\treadonly cursor: Node<MemoryRetrievalCursor>;\n}\n\nexport interface MemoryRetrievalBundleOptions {\n\treadonly name?: string;\n\treadonly fragments: Node<readonly unknown[]>;\n\treadonly query: Node<MemoryRetrievalQuery>;\n}\n\ninterface MemoryRetrievalRuntimeState {\n\tevaluation: number;\n}\n\ninterface MemoryRetrievalQueryValidation {\n\treadonly ok: boolean;\n\treadonly query: MemoryRetrievalQuery;\n\treadonly errors: readonly Omit<MemoryRetrievalError, \"cursor\">[];\n}\n\ninterface FragmentValidationResult<T> {\n\treadonly fragment?: MemoryFragment<T>;\n\treadonly error?: Omit<MemoryRetrievalError, \"cursor\">;\n}\n\n/**\n * Build a graph-visible memory retrieval bundle from explicit fragment/query deps.\n *\n * Invalid fragments and ranking status are emitted as ordinary DATA facts. The\n * bundle never owns storage restore or hidden mutation; callers that need\n * persistence compose D161 collection/storage sidecars outside this pattern.\n */\nexport function memoryRetrievalBundle<T = unknown>(\n\tgraph: Graph,\n\topts: MemoryRetrievalBundleOptions,\n): MemoryRetrievalBundle<T> {\n\tconst name = opts.name ?? \"memoryRetrieval\";\n\tconst { fragments, query } = opts;\n\tconst snapshot = graph.node<MemoryRetrievalSnapshot<T>>(\n\t\t[fragments, query],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<MemoryRetrievalRuntimeState>() ??\n\t\t\t\t({ evaluation: 0 } satisfies MemoryRetrievalRuntimeState);\n\t\t\tstate.evaluation += 1;\n\t\t\tconst rawFragments = depLatest(ctx, 0);\n\t\t\tconst rawQuery = depLatest(ctx, 1);\n\t\t\tconst queryValidation = validateMemoryRetrievalQuery(rawQuery);\n\t\t\tconst currentQuery = queryValidation.query;\n\t\t\tconst valid: MemoryFragment<T>[] = [];\n\t\t\tconst seenIds = new Set<FactId>();\n\t\t\tconst errors: Omit<MemoryRetrievalError, \"cursor\">[] = [...queryValidation.errors];\n\n\t\t\tif (!Array.isArray(rawFragments)) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-fragments-input\",\n\t\t\t\t\tmessage: \"memoryRetrievalBundle: fragments input must be an array\",\n\t\t\t\t\tfragment: rawFragments,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst length = safeArrayLength(rawFragments);\n\t\t\t\tif (length === undefined) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tcode: \"invalid-fragments-input\",\n\t\t\t\t\t\tmessage: \"memoryRetrievalBundle: fragments input length could not be read\",\n\t\t\t\t\t\tfragment: rawFragments,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tfor (let i = 0; i < (length ?? 0); i += 1) {\n\t\t\t\t\tconst result = validateAndSnapshotFragment<T>(rawFragments, i);\n\t\t\t\t\tif (result.error !== undefined) {\n\t\t\t\t\t\terrors.push(result.error);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst fragment = result.fragment as MemoryFragment<T>;\n\t\t\t\t\tif (seenIds.has(fragment.id)) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tcode: \"duplicate-fragment-id\",\n\t\t\t\t\t\t\tmessage: \"memoryRetrievalBundle: duplicate fragment id\",\n\t\t\t\t\t\t\tindex: i,\n\t\t\t\t\t\t\tfragment,\n\t\t\t\t\t\t\tvalidationErrors: [`duplicate fragment id '${fragment.id}'`],\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tseenIds.add(fragment.id);\n\t\t\t\t\tvalid.push(fragment);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst ranked = errors.some((error) => !isRecoverableFragmentError(error))\n\t\t\t\t? []\n\t\t\t\t: rankFragments(valid, currentQuery);\n\t\t\tconst cursor: MemoryRetrievalCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidFragments: valid.length,\n\t\t\t\tinvalidFragments: errors.filter(\n\t\t\t\t\t(error) => error.code === \"invalid-fragment\" || error.code === \"duplicate-fragment-id\",\n\t\t\t\t).length,\n\t\t\t\tresultCount: ranked.length,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tconst answer: MemoryAnswer<T> = Object.freeze({\n\t\t\t\tquery: currentQuery,\n\t\t\t\tresults: Object.freeze(ranked),\n\t\t\t});\n\t\t\tconst status: MemoryRetrievalStatus = Object.freeze({\n\t\t\t\tstate: statusState(errors, ranked.length),\n\t\t\t\tquery: currentQuery,\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tconst indexed: MemoryRetrievalIndex<T> = Object.freeze({\n\t\t\t\tids: Object.freeze(valid.map((fragment) => fragment.id)),\n\t\t\t\tbyId: indexById(valid),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tconst errorFacts = Object.freeze(\n\t\t\t\terrors.map((error) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t...error,\n\t\t\t\t\t\t...(error.validationErrors === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tfragments: Object.freeze([...valid]),\n\t\t\t\t\t\tindexed,\n\t\t\t\t\t\tranked: answer,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors: errorFacts,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/snapshot`,\n\t\t\tfactory: \"memoryRetrievalSnapshot\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { fragments, query },\n\t\tsnapshot,\n\t\tfragments: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/fragments`,\n\t\t\t\"memoryRetrievalFragments\",\n\t\t\t(fact) => fact.fragments,\n\t\t),\n\t\tindexed: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/indexed`,\n\t\t\t\"memoryRetrievalIndexed\",\n\t\t\t(fact) => fact.indexed,\n\t\t),\n\t\tranked: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/ranked`,\n\t\t\t\"memoryRetrievalRanked\",\n\t\t\t(fact) => fact.ranked,\n\t\t),\n\t\tstatus: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/status`,\n\t\t\t\"memoryRetrievalStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/errors`,\n\t\t\t\"memoryRetrievalErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/cursor`,\n\t\t\t\"memoryRetrievalCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/**\n * D170 lower semantic-memory KG materializer.\n *\n * Assertion, entity, relation, and topic ids remain DATA keys. The bundle has\n * static describe-visible topology and owns no storage, LLM extraction,\n * scheduler, agent runtime, or dynamic graph node lifecycle.\n */\nexport function knowledgeGraphReducerBundle(\n\tgraph: Graph,\n\topts: KnowledgeGraphReducerBundleOptions,\n): KnowledgeGraphReducerBundle {\n\tconst name = opts.name ?? \"knowledgeGraph\";\n\tconst deps = opts.policy === undefined ? [opts.assertions] : [opts.assertions, opts.policy];\n\tconst snapshot = graph.node<KnowledgeGraphSnapshot>(\n\t\tdeps,\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst policy = validateKnowledgeGraphPolicy(\n\t\t\t\topts.policy === undefined ? undefined : depLatest(ctx, 1),\n\t\t\t);\n\t\t\tconst reduced = reduceKnowledgeAssertions(depLatest(ctx, 0), policy.policy);\n\t\t\tconst pendingErrors = [...policy.errors, ...reduced.errors];\n\t\t\tconst cursor: KnowledgeGraphCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidAssertions: reduced.assertions.length,\n\t\t\t\tinvalidAssertions: reduced.invalidAssertions,\n\t\t\t\tentityCount: reduced.entities.length,\n\t\t\t\trelationCount: reduced.relations.length,\n\t\t\t\tpredicateCount: reduced.topics.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\tpendingErrors.map((error) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t...error,\n\t\t\t\t\t\t...(error.validationErrors === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst status: KnowledgeGraphStatus = Object.freeze({\n\t\t\t\tstate:\n\t\t\t\t\treduced.assertions.length === 0 && errors.length === 0\n\t\t\t\t\t\t? \"empty\"\n\t\t\t\t\t\t: errors.length === 0\n\t\t\t\t\t\t\t? \"ready\"\n\t\t\t\t\t\t\t: reduced.assertions.length > 0\n\t\t\t\t\t\t\t\t? \"partial\"\n\t\t\t\t\t\t\t\t: \"error\",\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tassertions: Object.freeze(reduced.assertions),\n\t\t\t\t\t\tentities: Object.freeze(reduced.entities),\n\t\t\t\t\t\trelations: Object.freeze(reduced.relations),\n\t\t\t\t\t\ttopics: Object.freeze(reduced.topics),\n\t\t\t\t\t\tindex: reduced.index,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/snapshot`,\n\t\t\tfactory: \"knowledgeGraphReducerSnapshot\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: {\n\t\t\tassertions: opts.assertions,\n\t\t\t...(opts.policy === undefined ? {} : { policy: opts.policy }),\n\t\t},\n\t\tsnapshot,\n\t\tassertions: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/assertions`,\n\t\t\t\"knowledgeGraphAssertions\",\n\t\t\t(fact) => fact.assertions,\n\t\t),\n\t\tentities: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/entities`,\n\t\t\t\"knowledgeGraphEntities\",\n\t\t\t(fact) => fact.entities,\n\t\t),\n\t\trelations: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/relations`,\n\t\t\t\"knowledgeGraphRelations\",\n\t\t\t(fact) => fact.relations,\n\t\t),\n\t\ttopics: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/topics`,\n\t\t\t\"knowledgeGraphTopics\",\n\t\t\t(fact) => fact.topics,\n\t\t),\n\t\tindex: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/index`,\n\t\t\t\"knowledgeGraphIndex\",\n\t\t\t(fact) => fact.index,\n\t\t),\n\t\tstatus: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/status`,\n\t\t\t\"knowledgeGraphStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/errors`,\n\t\t\t\"knowledgeGraphErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/cursor`,\n\t\t\t\"knowledgeGraphCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\nfunction retrievalProjection<TFact, T>(\n\tgraph: Graph,\n\tsnapshot: Node<MemoryRetrievalSnapshot<T>>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: MemoryRetrievalSnapshot<T>) => TFact | undefined,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst fact = raw as MemoryRetrievalSnapshot<T>;\n\t\t\t\tconst selected = select(fact);\n\t\t\t\tif (selected !== undefined) ctx.down([[\"DATA\", selected]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction kgProjection<TFact>(\n\tgraph: Graph,\n\tsnapshot: Node<KnowledgeGraphSnapshot>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: KnowledgeGraphSnapshot) => TFact,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", select(raw as KnowledgeGraphSnapshot)]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction validateKnowledgeGraphPolicy(value: unknown): {\n\treadonly policy?: KnowledgeGraphPolicy;\n\treadonly errors: readonly Omit<KnowledgeGraphError, \"cursor\">[];\n} {\n\tif (value === undefined) return { policy: undefined, errors: [] };\n\tif (!isPlainObject(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-policy\",\n\t\t\t\t\tmessage: \"knowledgeGraphReducerBundle: policy must be an object\",\n\t\t\t\t\tassertion: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst errors: string[] = [];\n\tconst policy = value as Partial<KnowledgeGraphPolicy>;\n\tif (\n\t\tpolicy.allowedPredicates !== undefined &&\n\t\t!isDenseArrayOf(policy.allowedPredicates, (item): item is string => typeof item === \"string\")\n\t) {\n\t\terrors.push(\"allowedPredicates must be a readonly string array\");\n\t}\n\tif (policy.requireEntityTypes !== undefined && typeof policy.requireEntityTypes !== \"boolean\") {\n\t\terrors.push(\"requireEntityTypes must be a boolean when present\");\n\t}\n\tif (errors.length > 0) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-policy\",\n\t\t\t\t\tmessage: \"knowledgeGraphReducerBundle: policy is invalid\",\n\t\t\t\t\tassertion: value,\n\t\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\treturn {\n\t\tpolicy: Object.freeze({\n\t\t\t...(policy.allowedPredicates === undefined\n\t\t\t\t? {}\n\t\t\t\t: { allowedPredicates: Object.freeze([...policy.allowedPredicates]) }),\n\t\t\t...(policy.requireEntityTypes === undefined\n\t\t\t\t? {}\n\t\t\t\t: { requireEntityTypes: policy.requireEntityTypes }),\n\t\t}),\n\t\terrors: [],\n\t};\n}\n\nfunction reduceKnowledgeAssertions(\n\tvalue: unknown,\n\tpolicy?: KnowledgeGraphPolicy,\n): {\n\treadonly assertions: readonly KnowledgeAssertion[];\n\treadonly entities: readonly KnowledgeGraphEntity[];\n\treadonly relations: readonly KnowledgeGraphRelation[];\n\treadonly topics: readonly KnowledgeGraphTopic[];\n\treadonly index: KnowledgeGraphIndex;\n\treadonly errors: readonly Omit<KnowledgeGraphError, \"cursor\">[];\n\treadonly invalidAssertions: number;\n} {\n\tconst assertions: KnowledgeAssertion[] = [];\n\tconst errors: Omit<KnowledgeGraphError, \"cursor\">[] = [];\n\tconst seenAssertions = new Set<FactId>();\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tentities: [],\n\t\t\trelations: [],\n\t\t\ttopics: [],\n\t\t\tindex: emptyKnowledgeGraphIndex(),\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-assertions-input\",\n\t\t\t\t\tmessage: \"knowledgeGraphReducerBundle: assertions input must be an array\",\n\t\t\t\t\tassertion: value,\n\t\t\t\t},\n\t\t\t],\n\t\t\tinvalidAssertions: 0,\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tentities: [],\n\t\t\trelations: [],\n\t\t\ttopics: [],\n\t\t\tindex: emptyKnowledgeGraphIndex(),\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-assertions-input\",\n\t\t\t\t\tmessage: \"knowledgeGraphReducerBundle: assertions input length could not be read\",\n\t\t\t\t\tassertion: value,\n\t\t\t\t},\n\t\t\t],\n\t\t\tinvalidAssertions: 0,\n\t\t};\n\t}\n\tfor (let i = 0; i < length; i += 1) {\n\t\tconst result = validateKnowledgeAssertion(value[i], i, policy);\n\t\tif (result.error !== undefined) {\n\t\t\terrors.push(result.error);\n\t\t\tcontinue;\n\t\t}\n\t\tconst assertion = result.assertion as KnowledgeAssertion;\n\t\tif (seenAssertions.has(assertion.id)) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-assertion-id\",\n\t\t\t\tmessage: \"knowledgeGraphReducerBundle: duplicate assertion id\",\n\t\t\t\tindex: i,\n\t\t\t\tassertionId: assertion.id,\n\t\t\t\tassertion,\n\t\t\t\tvalidationErrors: Object.freeze([`duplicate assertion id '${assertion.id}'`]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseenAssertions.add(assertion.id);\n\t\tassertions.push(assertion);\n\t}\n\tconst materialized = materializeKnowledgeGraph(assertions);\n\treturn {\n\t\tassertions: Object.freeze(assertions),\n\t\t...materialized,\n\t\terrors,\n\t\tinvalidAssertions: errors.filter((error) => error.code !== \"invalid-policy\").length,\n\t};\n}\n\nfunction validateKnowledgeAssertion(\n\tvalue: unknown,\n\tindex: number,\n\tpolicy?: KnowledgeGraphPolicy,\n): {\n\treadonly assertion?: KnowledgeAssertion;\n\treadonly error?: Omit<KnowledgeGraphError, \"cursor\">;\n} {\n\tif (!isPlainObject(value)) {\n\t\treturn invalidKnowledgeAssertion(index, value, [\"assertion must be an object\"]);\n\t}\n\tconst raw = value as Partial<KnowledgeAssertion>;\n\tconst errors: string[] = [];\n\tif (!isNonEmptyString(raw.id)) errors.push(\"id must be a non-empty string\");\n\tif (!isKnowledgeSubject(raw.subject)) errors.push(\"subject.id must be a non-empty string\");\n\tif (!isNonEmptyString(raw.predicate)) errors.push(\"predicate must be a non-empty string\");\n\tif (!isKnowledgeObject(raw.object)) errors.push(\"object shape is invalid\");\n\tif (\n\t\traw.confidence !== undefined &&\n\t\t(!Number.isFinite(raw.confidence) || raw.confidence < 0 || raw.confidence > 1)\n\t) {\n\t\terrors.push(\"confidence must be a finite number in [0, 1] when present\");\n\t}\n\tif (raw.sources !== undefined && !isDenseArrayOf(raw.sources, isNonEmptyString)) {\n\t\terrors.push(\"sources must be a readonly non-empty string array when present\");\n\t}\n\tif (\n\t\tpolicy?.allowedPredicates !== undefined &&\n\t\t!policy.allowedPredicates.includes(raw.predicate ?? \"\")\n\t) {\n\t\terrors.push(`predicate '${String(raw.predicate)}' is not allowed by policy`);\n\t}\n\tif (policy?.requireEntityTypes === true) {\n\t\tif (isKnowledgeSubject(raw.subject) && raw.subject.type === undefined) {\n\t\t\terrors.push(\"subject.type is required by policy\");\n\t\t}\n\t\tif (\n\t\t\tisKnowledgeObject(raw.object) &&\n\t\t\traw.object.kind === \"entity\" &&\n\t\t\traw.object.type === undefined\n\t\t) {\n\t\t\terrors.push(\"object.type is required by policy for entity objects\");\n\t\t}\n\t}\n\tif (errors.length > 0) {\n\t\treturn invalidKnowledgeAssertion(index, value, errors, raw.id);\n\t}\n\treturn {\n\t\tassertion: Object.freeze({\n\t\t\tid: raw.id as FactId,\n\t\t\t...(raw.recordId === undefined ? {} : { recordId: raw.recordId }),\n\t\t\t...(raw.fragmentId === undefined ? {} : { fragmentId: raw.fragmentId }),\n\t\t\tsubject: snapshotSubject(raw.subject as KnowledgeAssertionSubject),\n\t\t\tpredicate: raw.predicate as string,\n\t\t\tobject: snapshotObject(raw.object as KnowledgeAssertionObject),\n\t\t\t...(raw.confidence === undefined ? {} : { confidence: raw.confidence }),\n\t\t\tsources: Object.freeze([...(raw.sources ?? [])]),\n\t\t\t...(raw.provenance === undefined ? {} : { provenance: raw.provenance }),\n\t\t}),\n\t};\n}\n\nfunction invalidKnowledgeAssertion(\n\tindex: number,\n\tassertion: unknown,\n\tvalidationErrors: readonly string[],\n\tassertionId?: unknown,\n): { readonly error: Omit<KnowledgeGraphError, \"cursor\"> } {\n\treturn {\n\t\terror: {\n\t\t\tcode: \"invalid-assertion\",\n\t\t\tmessage: \"knowledgeGraphReducerBundle: assertion is invalid\",\n\t\t\tindex,\n\t\t\tassertionId: typeof assertionId === \"string\" ? assertionId : undefined,\n\t\t\tassertion,\n\t\t\tvalidationErrors: Object.freeze([...validationErrors]),\n\t\t},\n\t};\n}\n\nfunction materializeKnowledgeGraph(assertions: readonly KnowledgeAssertion[]): {\n\treadonly entities: readonly KnowledgeGraphEntity[];\n\treadonly relations: readonly KnowledgeGraphRelation[];\n\treadonly topics: readonly KnowledgeGraphTopic[];\n\treadonly index: KnowledgeGraphIndex;\n} {\n\tconst entityAssertions = new Map<\n\t\tFactId,\n\t\t{\n\t\t\ttype?: string;\n\t\t\tassertionIds: Set<FactId>;\n\t\t\tsubjectAssertionIds: Set<FactId>;\n\t\t\tobjectAssertionIds: Set<FactId>;\n\t\t}\n\t>();\n\tconst topics = new Map<FactId, { assertionIds: Set<FactId>; entityIds: Set<FactId> }>();\n\tconst relations: KnowledgeGraphRelation[] = [];\n\tfor (const assertion of assertions) {\n\t\tconst subject = touchEntity(entityAssertions, assertion.subject.id, assertion.subject.type);\n\t\tsubject.assertionIds.add(assertion.id);\n\t\tsubject.subjectAssertionIds.add(assertion.id);\n\t\tlet topic = topics.get(assertion.predicate);\n\t\tif (topic === undefined) {\n\t\t\ttopic = { assertionIds: new Set(), entityIds: new Set() };\n\t\t\ttopics.set(assertion.predicate, topic);\n\t\t}\n\t\ttopic.assertionIds.add(assertion.id);\n\t\ttopic.entityIds.add(assertion.subject.id);\n\t\tif (assertion.object.kind === \"entity\") {\n\t\t\tconst object = touchEntity(entityAssertions, assertion.object.id, assertion.object.type);\n\t\t\tobject.assertionIds.add(assertion.id);\n\t\t\tobject.objectAssertionIds.add(assertion.id);\n\t\t\ttopic.entityIds.add(assertion.object.id);\n\t\t}\n\t\trelations.push(\n\t\t\tObject.freeze({\n\t\t\t\tassertionId: assertion.id,\n\t\t\t\tsubject: assertion.subject,\n\t\t\t\tpredicate: assertion.predicate,\n\t\t\t\tobject: assertion.object,\n\t\t\t\t...(assertion.confidence === undefined ? {} : { confidence: assertion.confidence }),\n\t\t\t\tsources: Object.freeze([...(assertion.sources ?? [])]),\n\t\t\t\t...(assertion.provenance === undefined ? {} : { provenance: assertion.provenance }),\n\t\t\t}),\n\t\t);\n\t}\n\tconst entities = [...entityAssertions.entries()].map(([id, entity]) =>\n\t\tObject.freeze({\n\t\t\tid,\n\t\t\t...(entity.type === undefined ? {} : { type: entity.type }),\n\t\t\tassertionIds: freezeSortedSet(entity.assertionIds),\n\t\t\tsubjectAssertionIds: freezeSortedSet(entity.subjectAssertionIds),\n\t\t\tobjectAssertionIds: freezeSortedSet(entity.objectAssertionIds),\n\t\t}),\n\t);\n\tentities.sort((a, b) => compareString(a.id, b.id));\n\trelations.sort((a, b) => compareString(a.assertionId, b.assertionId));\n\tconst topicFacts = [...topics.entries()].map(([predicate, topic]) =>\n\t\tObject.freeze({\n\t\t\tpredicate,\n\t\t\tassertionIds: freezeSortedSet(topic.assertionIds),\n\t\t\tentityIds: freezeSortedSet(topic.entityIds),\n\t\t}),\n\t);\n\ttopicFacts.sort((a, b) => compareString(a.predicate, b.predicate));\n\tconst index: KnowledgeGraphIndex = Object.freeze({\n\t\tassertionIds: Object.freeze(assertions.map((assertion) => assertion.id).sort(compareString)),\n\t\tentityIds: Object.freeze(entities.map((entity) => entity.id)),\n\t\trelationIds: Object.freeze(relations.map((relation) => relation.assertionId)),\n\t\tpredicates: Object.freeze(topicFacts.map((topic) => topic.predicate)),\n\t});\n\treturn {\n\t\tentities: Object.freeze(entities),\n\t\trelations: Object.freeze(relations),\n\t\ttopics: Object.freeze(topicFacts),\n\t\tindex,\n\t};\n}\n\nfunction touchEntity(\n\tentities: Map<\n\t\tFactId,\n\t\t{\n\t\t\ttype?: string;\n\t\t\tassertionIds: Set<FactId>;\n\t\t\tsubjectAssertionIds: Set<FactId>;\n\t\t\tobjectAssertionIds: Set<FactId>;\n\t\t}\n\t>,\n\tid: FactId,\n\ttype?: string,\n) {\n\tlet entity = entities.get(id);\n\tif (entity === undefined) {\n\t\tentity = {\n\t\t\t...(type === undefined ? {} : { type }),\n\t\t\tassertionIds: new Set(),\n\t\t\tsubjectAssertionIds: new Set(),\n\t\t\tobjectAssertionIds: new Set(),\n\t\t};\n\t\tentities.set(id, entity);\n\t} else if (entity.type === undefined && type !== undefined) {\n\t\tentity.type = type;\n\t}\n\treturn entity;\n}\n\nfunction emptyKnowledgeGraphIndex(): KnowledgeGraphIndex {\n\treturn Object.freeze({\n\t\tassertionIds: Object.freeze([]),\n\t\tentityIds: Object.freeze([]),\n\t\trelationIds: Object.freeze([]),\n\t\tpredicates: Object.freeze([]),\n\t});\n}\n\nfunction snapshotSubject(subject: KnowledgeAssertionSubject): KnowledgeAssertionSubject {\n\treturn Object.freeze({\n\t\tid: subject.id,\n\t\t...(subject.type === undefined ? {} : { type: subject.type }),\n\t});\n}\n\nfunction snapshotObject(object: KnowledgeAssertionObject): KnowledgeAssertionObject {\n\treturn object.kind === \"entity\"\n\t\t? Object.freeze({\n\t\t\t\tkind: \"entity\",\n\t\t\t\tid: object.id,\n\t\t\t\t...(object.type === undefined ? {} : { type: object.type }),\n\t\t\t})\n\t\t: Object.freeze({\n\t\t\t\tkind: \"value\",\n\t\t\t\tvalue: object.value,\n\t\t\t\t...(object.valueType === undefined ? {} : { valueType: object.valueType }),\n\t\t\t});\n}\n\nfunction isKnowledgeSubject(value: unknown): value is KnowledgeAssertionSubject {\n\treturn (\n\t\tisPlainObject(value) &&\n\t\tisNonEmptyString(value.id) &&\n\t\t(value.type === undefined || isNonEmptyString(value.type))\n\t);\n}\n\nfunction isKnowledgeObject(value: unknown): value is KnowledgeAssertionObject {\n\tif (!isPlainObject(value)) return false;\n\tif (value.kind === \"entity\") {\n\t\treturn isNonEmptyString(value.id) && (value.type === undefined || isNonEmptyString(value.type));\n\t}\n\tif (value.kind !== \"value\") return false;\n\treturn (\n\t\tisStrictJsonValue(value.value) &&\n\t\t(value.valueType === undefined || isNonEmptyString(value.valueType))\n\t);\n}\n\nfunction isStrictJsonValue(value: unknown): boolean {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n\tif (typeof value === \"number\") return Number.isFinite(value);\n\tif (Array.isArray(value)) {\n\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\tif (!Object.hasOwn(value, i) || !isStrictJsonValue(value[i])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\tif (!isPlainObject(value)) return false;\n\tfor (const key of Object.keys(value)) {\n\t\tif (!isStrictJsonValue(value[key])) return false;\n\t}\n\treturn Object.getOwnPropertySymbols(value).length === 0;\n}\n\nfunction freezeSortedSet(value: ReadonlySet<FactId>): readonly FactId[] {\n\treturn Object.freeze([...value].sort(compareString));\n}\n\nfunction rankFragments<T>(\n\tfragments: readonly MemoryFragment<T>[],\n\tquery: MemoryRetrievalQuery,\n): readonly MemoryFragment<T>[] {\n\tif (query.vector === undefined) return filterMemoryFragments(fragments, query);\n\tconst ranked = fragments.filter((fragment) => memoryFragmentMatchesQuery(fragment, query));\n\tranked.sort((a, b) => {\n\t\tconst vectorDelta = vectorScore(b, query) - vectorScore(a, query);\n\t\tif (vectorDelta !== 0) return vectorDelta;\n\t\tconst confidenceDelta = b.confidence - a.confidence;\n\t\tif (confidenceDelta !== 0) return confidenceDelta;\n\t\treturn compareBigIntDesc(a.tNs, b.tNs);\n\t});\n\treturn query.limit === undefined ? ranked : ranked.slice(0, Math.max(0, query.limit));\n}\n\nfunction vectorScore(fragment: MemoryFragment, query: MemoryRetrievalQuery): number {\n\tif (query.vector === undefined || fragment.embedding === undefined) return 0;\n\treturn cosineSimilarity(query.vector, fragment.embedding);\n}\n\nfunction statusState(\n\terrors: readonly Omit<MemoryRetrievalError, \"cursor\">[],\n\tresultCount: number,\n): MemoryRetrievalStatusState {\n\tif (errors.some((error) => !isRecoverableFragmentError(error))) return \"error\";\n\tif (errors.length > 0) return \"partial\";\n\treturn resultCount > 0 ? \"ready\" : \"empty\";\n}\n\nfunction isRecoverableFragmentError(error: Omit<MemoryRetrievalError, \"cursor\">): boolean {\n\treturn error.code === \"invalid-fragment\" || error.code === \"duplicate-fragment-id\";\n}\n\nfunction indexById<T>(\n\tfragments: readonly MemoryFragment<T>[],\n): Readonly<Record<FactId, MemoryFragment<T>>> {\n\tconst byId = Object.create(null) as Record<FactId, MemoryFragment<T>>;\n\tfor (const fragment of fragments) byId[fragment.id] = fragment;\n\treturn Object.freeze(byId);\n}\n\nfunction isFiniteVector(value: unknown): value is readonly number[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !Number.isFinite(value[i])) return false;\n\t}\n\treturn true;\n}\n\nfunction validateMemoryRetrievalQuery(value: unknown): MemoryRetrievalQueryValidation {\n\ttry {\n\t\treturn validateMemoryRetrievalQueryInner(value);\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tquery: {},\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-query\",\n\t\t\t\t\tmessage: `memoryRetrievalBundle: query access failed: ${errorMessage(error)}`,\n\t\t\t\t\tfragment: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n}\n\nfunction validateMemoryRetrievalQueryInner(value: unknown): MemoryRetrievalQueryValidation {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn invalidQuery(value, \"memoryRetrievalBundle: query must be an object\");\n\t}\n\tconst query = value as Partial<MemoryRetrievalQuery>;\n\tconst errors: Omit<MemoryRetrievalError, \"cursor\">[] = [];\n\tif (\n\t\tquery.tags !== undefined &&\n\t\t!isDenseArrayOf(query.tags, (tag): tag is string => typeof tag === \"string\")\n\t) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.tags must be a readonly string array\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"tags must be a readonly string array\"],\n\t\t});\n\t}\n\tif (query.asOf !== undefined && typeof query.asOf !== \"bigint\") {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.asOf must be a bigint\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"asOf must be a bigint when present\"],\n\t\t});\n\t}\n\tif (\n\t\tquery.minConfidence !== undefined &&\n\t\t(!Number.isFinite(query.minConfidence) || query.minConfidence < 0 || query.minConfidence > 1)\n\t) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.minConfidence must be a finite number in [0, 1]\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"minConfidence must be a finite number in [0, 1]\"],\n\t\t});\n\t}\n\tif (query.limit !== undefined && (!Number.isSafeInteger(query.limit) || query.limit < 0)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.limit must be a non-negative safe integer\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"limit must be a non-negative safe integer\"],\n\t\t});\n\t}\n\tif (query.vector !== undefined && !isFiniteVector(query.vector)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query-vector\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.vector must be a finite number array\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"vector must be a finite number array\"],\n\t\t});\n\t}\n\tif (errors.length > 0) return { ok: false, query: {}, errors };\n\treturn { ok: true, query: snapshotQuery(query), errors };\n}\n\nfunction invalidQuery(value: unknown, message: string): MemoryRetrievalQueryValidation {\n\treturn {\n\t\tok: false,\n\t\tquery: {},\n\t\terrors: [\n\t\t\t{\n\t\t\t\tcode: \"invalid-query\",\n\t\t\t\tmessage,\n\t\t\t\tfragment: value,\n\t\t\t},\n\t\t],\n\t};\n}\n\nfunction snapshotQuery(query: Partial<MemoryRetrievalQuery>): MemoryRetrievalQuery {\n\treturn Object.freeze({\n\t\t...(query.tags === undefined ? {} : { tags: Object.freeze([...query.tags]) }),\n\t\t...(query.asOf === undefined ? {} : { asOf: query.asOf }),\n\t\t...(query.minConfidence === undefined ? {} : { minConfidence: query.minConfidence }),\n\t\t...(query.limit === undefined ? {} : { limit: query.limit }),\n\t\t...(query.vector === undefined ? {} : { vector: Object.freeze([...query.vector]) }),\n\t});\n}\n\nfunction safeArrayLength(value: readonly unknown[]): number | undefined {\n\ttry {\n\t\treturn value.length;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction validateAndSnapshotFragment<T>(\n\trawFragments: readonly unknown[],\n\tindex: number,\n): FragmentValidationResult<T> {\n\tlet raw: unknown;\n\ttry {\n\t\traw = rawFragments[index];\n\t\tconst validation = validateMemoryFragment(raw);\n\t\tif (!validation.ok) {\n\t\t\treturn {\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"invalid-fragment\",\n\t\t\t\t\tmessage: \"memoryRetrievalBundle: invalid memory fragment\",\n\t\t\t\t\tindex,\n\t\t\t\t\tfragment: raw,\n\t\t\t\t\tvalidationErrors: Object.freeze([...validation.errors]),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn { fragment: snapshotFragment(raw as MemoryFragment<T>) };\n\t} catch (error) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-fragment\",\n\t\t\t\tmessage: `memoryRetrievalBundle: fragment access failed: ${errorMessage(error)}`,\n\t\t\t\tindex,\n\t\t\t\tfragment: raw,\n\t\t\t\tvalidationErrors: Object.freeze([\"fragment access failed\"]),\n\t\t\t},\n\t\t};\n\t}\n}\n\nfunction snapshotFragment<T>(fragment: MemoryFragment<T>): MemoryFragment<T> {\n\treturn Object.freeze({\n\t\tid: fragment.id,\n\t\tpayload: fragment.payload,\n\t\ttNs: fragment.tNs,\n\t\t...(fragment.validFrom === undefined ? {} : { validFrom: fragment.validFrom }),\n\t\t...(fragment.validTo === undefined ? {} : { validTo: fragment.validTo }),\n\t\tconfidence: fragment.confidence,\n\t\ttags: Object.freeze([...fragment.tags]),\n\t\tsources: Object.freeze([...fragment.sources]),\n\t\t...(fragment.embedding === undefined\n\t\t\t? {}\n\t\t\t: { embedding: Object.freeze([...fragment.embedding]) }),\n\t\t...(fragment.parentFragmentId === undefined\n\t\t\t? {}\n\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t});\n}\n\nfunction isDenseArrayOf<T>(value: unknown, predicate: (item: unknown) => item is T): value is T[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !predicate(value[i])) return false;\n\t}\n\treturn true;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction compareString(a: string, b: string): number {\n\treturn a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction compareBigIntDesc(a: bigint, b: bigint): number {\n\tif (a === b) return 0;\n\treturn a > b ? -1 : 1;\n}\n","/**\n * Thin agentic-memory solution surface.\n *\n * D125 places vertical application kits under solutions, while D158 keeps\n * semantic-memory retrieval/ranking in horizontal patterns. This v0 bundle\n * composes those lower layers into graph-visible facts only: no agent runtime,\n * hidden scheduler, storage restore/hydration, LLM loop, or protocol behavior.\n */\n\nimport { depBatch, depLatest } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport {\n\ttype Codec,\n\ttype StrictJsonValue as SharedStrictJsonValue,\n\tstrictJsonCodec,\n} from \"../json/codec.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\ttype FactId,\n\ttype KnowledgeAssertion,\n\ttype KnowledgeAssertionObject,\n\ttype KnowledgeAssertionSubject,\n\ttype MemoryAnswer,\n\ttype MemoryFragment,\n\tvalidateMemoryFragment,\n} from \"../patterns/semantic-memory.js\";\nimport {\n\ttype MemoryRetrievalBundle,\n\ttype MemoryRetrievalCursor,\n\ttype MemoryRetrievalError,\n\ttype MemoryRetrievalIndex,\n\ttype MemoryRetrievalQuery,\n\ttype MemoryRetrievalSnapshot,\n\ttype MemoryRetrievalStatus,\n\tmemoryRetrievalBundle,\n} from \"../patterns/semantic-memory-graph.js\";\n\nexport type AgenticMemoryStrictJsonValue = SharedStrictJsonValue;\n\ntype StrictJsonValue = SharedStrictJsonValue;\n\nexport type {\n\tKnowledgeAssertion,\n\tKnowledgeAssertionObject,\n\tKnowledgeAssertionSubject,\n} from \"../patterns/semantic-memory.js\";\n\n/** Agent-facing memory category. D164 keeps this separate from durability and artifact kind. */\nexport type AgenticMemoryKind = \"working\" | \"episodic\" | \"semantic\" | \"procedural\" | \"profile\";\n\n/** Semantic durability/retention policy metadata. This is not a storage tier handle. */\nexport type AgenticMemoryPersistenceLevel =\n\t| \"turn\"\n\t| \"session\"\n\t| \"project\"\n\t| \"longTerm\"\n\t| \"permanent\"\n\t| \"archived\";\n\n/** Whether the record is raw evidence or a derived artifact. */\nexport type AgenticMemoryArtifactKind = \"raw\" | \"insight\" | \"profile\" | \"procedure\";\n\n/** Optional solution-facing scope metadata. Scope ids are ordinary DATA facts. */\nexport interface AgenticMemoryScope {\n\treadonly sessionId?: string;\n\treadonly projectId?: string;\n\treadonly userId?: string;\n\treadonly tenantId?: string;\n}\n\n/**\n * D164 solution envelope over a lower-layer MemoryFragment.\n *\n * The envelope carries agentic-memory metadata only. It intentionally owns no\n * storage tiers/keys/adapters, restore/hydration behavior, timers, schedulers,\n * LLM/tool/runner handles, or protocol semantics.\n */\nexport interface AgenticMemoryRecord<T = unknown> {\n\treadonly id: FactId;\n\treadonly kind: AgenticMemoryKind;\n\treadonly persistenceLevel: AgenticMemoryPersistenceLevel;\n\treadonly artifactKind: AgenticMemoryArtifactKind;\n\treadonly scope?: AgenticMemoryScope;\n\treadonly fragment: MemoryFragment<T>;\n}\n\nexport interface AgenticMemoryRecordMetadata {\n\treadonly recordId: FactId;\n\treadonly kind: AgenticMemoryKind;\n\treadonly persistenceLevel: AgenticMemoryPersistenceLevel;\n\treadonly artifactKind: AgenticMemoryArtifactKind;\n\treadonly scope?: AgenticMemoryScope;\n}\n\nexport interface AgenticMemoryProjectionCursor {\n\treadonly evaluation: number;\n\treadonly validRecords: number;\n\treadonly invalidRecords: number;\n\treadonly projectedFragments: number;\n}\n\nexport type AgenticMemoryStatusState = \"ready\" | \"empty\" | \"partial\" | \"error\";\n\nexport interface AgenticMemoryStatus {\n\treadonly state: AgenticMemoryStatusState;\n\treadonly cursor: AgenticMemoryProjectionCursor;\n}\n\nexport type AgenticMemoryErrorCode =\n\t| \"duplicate-record-id\"\n\t| \"duplicate-fragment-id\"\n\t| \"invalid-records-input\"\n\t| \"invalid-record\"\n\t| \"invalid-record-kind\"\n\t| \"invalid-persistence-level\"\n\t| \"invalid-artifact-kind\"\n\t| \"invalid-scope\"\n\t| \"invalid-fragment\";\n\nexport interface AgenticMemoryError {\n\treadonly code: AgenticMemoryErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly recordId?: FactId;\n\treadonly fragmentId?: FactId;\n\treadonly record?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryProjectionCursor;\n}\n\nexport interface AgenticMemoryProjectionSnapshot<T = unknown> {\n\treadonly records: readonly AgenticMemoryRecord<T>[];\n\treadonly fragments: readonly MemoryFragment<T>[];\n\treadonly metadataByFragmentId: Readonly<Record<FactId, AgenticMemoryRecordMetadata>>;\n\treadonly status: AgenticMemoryStatus;\n\treadonly errors: readonly AgenticMemoryError[];\n\treadonly cursor: AgenticMemoryProjectionCursor;\n}\n\n/** Source/provenance projection for a valid memory fragment. */\nexport interface AgenticMemorySourceProjection {\n\treadonly fragmentId: FactId;\n\treadonly record?: AgenticMemoryRecordMetadata;\n\treadonly sources: readonly FactId[];\n\treadonly parentFragmentId?: FactId;\n\treadonly provenance?: string;\n}\n\n/** A context-ready item derived from ranked memory retrieval results. */\nexport interface AgenticMemoryContextEntry<T = unknown> {\n\treadonly fragmentId: FactId;\n\treadonly payload: T;\n\treadonly confidence: number;\n\treadonly tags: readonly string[];\n\treadonly sources: readonly FactId[];\n\treadonly record?: AgenticMemoryRecordMetadata;\n\treadonly fragment: MemoryFragment<T>;\n}\n\nexport type AgenticMemoryContextState = \"ready\" | \"empty\" | \"partial\" | \"error\";\n\n/**\n * Context-ready ranked memory output for callers such as prompt builders.\n *\n * This is still only a DATA fact. It does not extract, summarize, reflect, run\n * tools, or choose an autonomous action.\n */\nexport interface AgenticMemoryContext<T = unknown> {\n\treadonly state: AgenticMemoryContextState;\n\treadonly query: MemoryRetrievalQuery;\n\treadonly entries: readonly AgenticMemoryContextEntry<T>[];\n\treadonly cursor: MemoryRetrievalCursor;\n\treadonly errors: readonly AgenticMemoryError[];\n\treadonly retrievalErrors: readonly MemoryRetrievalError[];\n\treadonly contextReady: boolean;\n}\n\n/** Explicit KG assertion draft fact; extraction/LLM work happens outside this bundle. */\nexport interface AgenticMemoryKgAssertionDraft {\n\treadonly id: FactId;\n\treadonly recordId: FactId;\n\treadonly fragmentId: FactId;\n\treadonly subject: KnowledgeAssertionSubject;\n\treadonly predicate: string;\n\treadonly object: KnowledgeAssertionObject;\n\treadonly confidence?: number;\n\treadonly sources?: readonly FactId[];\n\treadonly provenance?: string;\n}\n\nexport interface AgenticMemoryKgProjectionCursor {\n\treadonly evaluation: number;\n\treadonly validRecords: number;\n\treadonly validDrafts: number;\n\treadonly invalidDrafts: number;\n\treadonly projectedAssertions: number;\n}\n\nexport type AgenticMemoryKgProjectionStatusState = AgenticMemoryStatusState;\n\nexport interface AgenticMemoryKgProjectionStatus {\n\treadonly state: AgenticMemoryKgProjectionStatusState;\n\treadonly cursor: AgenticMemoryKgProjectionCursor;\n}\n\nexport type AgenticMemoryKgProjectionErrorCode =\n\t| AgenticMemoryErrorCode\n\t| \"invalid-drafts-input\"\n\t| \"invalid-draft\"\n\t| \"duplicate-assertion-id\"\n\t| \"missing-record-ref\"\n\t| \"missing-fragment-ref\"\n\t| \"fragment-record-mismatch\"\n\t| \"invalid-assertion-shape\";\n\nexport interface AgenticMemoryKgProjectionError {\n\treadonly code: AgenticMemoryKgProjectionErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly assertionId?: FactId;\n\treadonly recordId?: FactId;\n\treadonly fragmentId?: FactId;\n\treadonly draft?: unknown;\n\treadonly record?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryKgProjectionCursor;\n}\n\nexport interface AgenticMemoryKgProjectionSnapshot {\n\treadonly assertions: readonly KnowledgeAssertion[];\n\treadonly status: AgenticMemoryKgProjectionStatus;\n\treadonly errors: readonly AgenticMemoryKgProjectionError[];\n\treadonly cursor: AgenticMemoryKgProjectionCursor;\n}\n\nexport interface AgenticMemoryKgProjectionBundle {\n\treadonly input: {\n\t\treadonly records: Node<readonly AgenticMemoryRecord[]>;\n\t\treadonly drafts: Node<readonly AgenticMemoryKgAssertionDraft[]>;\n\t};\n\treadonly projection: Node<AgenticMemoryKgProjectionSnapshot>;\n\treadonly assertions: Node<readonly KnowledgeAssertion[]>;\n\treadonly status: Node<AgenticMemoryKgProjectionStatus>;\n\treadonly errors: Node<readonly AgenticMemoryKgProjectionError[]>;\n\treadonly cursor: Node<AgenticMemoryKgProjectionCursor>;\n}\n\nexport interface AgenticMemoryKgProjectionBundleOptions {\n\treadonly name?: string;\n\treadonly records: Node<readonly AgenticMemoryRecord[]>;\n\treadonly drafts: Node<readonly AgenticMemoryKgAssertionDraft[]>;\n}\n\nexport const AGENTIC_MEMORY_RECORD_FRAME_FORMAT = \"graphrefly.agenticMemoryRecord\";\nexport const AGENTIC_MEMORY_RECORD_FRAME_VERSION = 1;\n\nexport interface AgenticMemoryFragmentFrame<TJson extends StrictJsonValue = StrictJsonValue> {\n\treadonly id: FactId;\n\treadonly payload: TJson;\n\treadonly tNs: string;\n\treadonly validFrom?: string;\n\treadonly validTo?: string;\n\treadonly confidence: number;\n\treadonly tags: readonly string[];\n\treadonly sources: readonly FactId[];\n\treadonly embedding?: readonly number[];\n\treadonly parentFragmentId?: FactId;\n\treadonly provenance?: string;\n}\n\nexport interface AgenticMemoryRecordFrame<TJson extends StrictJsonValue = StrictJsonValue> {\n\treadonly format: typeof AGENTIC_MEMORY_RECORD_FRAME_FORMAT;\n\treadonly version: typeof AGENTIC_MEMORY_RECORD_FRAME_VERSION;\n\treadonly record: {\n\t\treadonly id: FactId;\n\t\treadonly kind: AgenticMemoryKind;\n\t\treadonly persistenceLevel: AgenticMemoryPersistenceLevel;\n\t\treadonly artifactKind: AgenticMemoryArtifactKind;\n\t\treadonly scope?: AgenticMemoryScope;\n\t\treadonly fragment: AgenticMemoryFragmentFrame<TJson>;\n\t};\n}\n\nexport type AgenticMemoryRetentionCommand =\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly kind: \"archive\";\n\t\t\treadonly recordId: FactId;\n\t\t\treadonly reason?: string;\n\t }\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly kind: \"restore\";\n\t\t\treadonly recordId: FactId;\n\t\t\treadonly persistenceLevel?: Exclude<AgenticMemoryPersistenceLevel, \"archived\">;\n\t\t\treadonly reason?: string;\n\t }\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly kind: \"setPersistenceLevel\";\n\t\t\treadonly recordId: FactId;\n\t\t\treadonly persistenceLevel: AgenticMemoryPersistenceLevel;\n\t\t\treadonly reason?: string;\n\t }\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly kind: \"requestConsolidation\";\n\t\t\treadonly recordIds: readonly FactId[];\n\t\t\treadonly requestId?: FactId;\n\t\t\treadonly reason?: string;\n\t };\n\nexport interface AgenticMemoryConsolidationRequest {\n\treadonly id: FactId;\n\treadonly commandId: FactId;\n\treadonly recordIds: readonly FactId[];\n\treadonly reason?: string;\n}\n\nexport interface AgenticMemoryRetentionCursor {\n\treadonly evaluation: number;\n\treadonly validRecords: number;\n\treadonly validCommands: number;\n\treadonly invalidCommands: number;\n\treadonly activeRecords: number;\n\treadonly archivedRecords: number;\n\treadonly consolidationRequests: number;\n}\n\nexport interface AgenticMemoryRetentionStatus {\n\treadonly state: AgenticMemoryStatusState;\n\treadonly cursor: AgenticMemoryRetentionCursor;\n}\n\nexport type AgenticMemoryRetentionErrorCode =\n\t| AgenticMemoryErrorCode\n\t| \"invalid-commands-input\"\n\t| \"invalid-command\"\n\t| \"duplicate-command-id\"\n\t| \"missing-record-ref\";\n\nexport interface AgenticMemoryRetentionError {\n\treadonly code: AgenticMemoryRetentionErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly commandId?: FactId;\n\treadonly recordId?: FactId;\n\treadonly recordIds?: readonly FactId[];\n\treadonly command?: unknown;\n\treadonly record?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryRetentionCursor;\n}\n\nexport interface AgenticMemoryRetentionSnapshot<T = unknown> {\n\treadonly activeRecords: readonly AgenticMemoryRecord<T>[];\n\treadonly archivedRecords: readonly AgenticMemoryRecord<T>[];\n\treadonly consolidationRequests: readonly AgenticMemoryConsolidationRequest[];\n\treadonly status: AgenticMemoryRetentionStatus;\n\treadonly errors: readonly AgenticMemoryRetentionError[];\n\treadonly cursor: AgenticMemoryRetentionCursor;\n}\n\nexport interface AgenticMemoryRetentionBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\t\treadonly commands: Node<readonly AgenticMemoryRetentionCommand[]>;\n\t};\n\treadonly projection: Node<AgenticMemoryRetentionSnapshot<T>>;\n\treadonly activeRecords: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly archivedRecords: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly consolidationRequests: Node<readonly AgenticMemoryConsolidationRequest[]>;\n\treadonly status: Node<AgenticMemoryRetentionStatus>;\n\treadonly errors: Node<readonly AgenticMemoryRetentionError[]>;\n\treadonly cursor: Node<AgenticMemoryRetentionCursor>;\n}\n\nexport interface AgenticMemoryRetentionBundleOptions<T = unknown> {\n\treadonly name?: string;\n\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly commands: Node<readonly AgenticMemoryRetentionCommand[]>;\n}\n\nexport type AgenticMemoryConsolidationOutcome<T = unknown> =\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly requestId: FactId;\n\t\t\treadonly kind: \"proposedRecords\";\n\t\t\treadonly records: readonly AgenticMemoryRecord<T>[];\n\t\t\treadonly provenance?: string;\n\t }\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly requestId: FactId;\n\t\t\treadonly kind: \"failed\";\n\t\t\treadonly message: string;\n\t\t\treadonly provenance?: string;\n\t };\n\nexport interface AgenticMemoryConsolidationRecordDraft<T = unknown> {\n\treadonly id: FactId;\n\treadonly requestId: FactId;\n\treadonly outcomeId: FactId;\n\treadonly record: AgenticMemoryRecord<T>;\n}\n\nexport interface AgenticMemoryConsolidationCommand {\n\treadonly id: FactId;\n\treadonly kind: \"proposeRecords\" | \"markFailed\";\n\treadonly requestId: FactId;\n\treadonly outcomeId: FactId;\n\treadonly draftIds?: readonly FactId[];\n\treadonly message?: string;\n}\n\nexport interface AgenticMemoryConsolidationResult {\n\treadonly id: FactId;\n\treadonly requestId: FactId;\n\treadonly outcomeId: FactId;\n\treadonly state: \"proposed\" | \"failed\";\n\treadonly sourceRecordIds: readonly FactId[];\n\treadonly proposedRecordIds: readonly FactId[];\n\treadonly message?: string;\n\treadonly provenance?: string;\n}\n\nexport interface AgenticMemoryConsolidationCursor {\n\treadonly evaluation: number;\n\treadonly validRequests: number;\n\treadonly validOutcomes: number;\n\treadonly invalidOutcomes: number;\n\treadonly results: number;\n\treadonly proposedRecordDrafts: number;\n}\n\nexport interface AgenticMemoryConsolidationStatus {\n\treadonly state: AgenticMemoryStatusState;\n\treadonly cursor: AgenticMemoryConsolidationCursor;\n}\n\nexport type AgenticMemoryConsolidationErrorCode =\n\t| AgenticMemoryRetentionErrorCode\n\t| \"invalid-outcomes-input\"\n\t| \"invalid-outcome\"\n\t| \"duplicate-outcome-id\"\n\t| \"missing-request-ref\"\n\t| \"invalid-proposed-record\";\n\nexport interface AgenticMemoryConsolidationError {\n\treadonly code: AgenticMemoryConsolidationErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly outcomeId?: FactId;\n\treadonly requestId?: FactId;\n\treadonly recordId?: FactId;\n\treadonly outcome?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryConsolidationCursor;\n}\n\nexport interface AgenticMemoryConsolidationSnapshot<T = unknown> {\n\treadonly results: readonly AgenticMemoryConsolidationResult[];\n\treadonly proposedRecordDrafts: readonly AgenticMemoryConsolidationRecordDraft<T>[];\n\treadonly commands: readonly AgenticMemoryConsolidationCommand[];\n\treadonly status: AgenticMemoryConsolidationStatus;\n\treadonly errors: readonly AgenticMemoryConsolidationError[];\n\treadonly cursor: AgenticMemoryConsolidationCursor;\n}\n\nexport interface AgenticMemoryConsolidationBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\t\treadonly requests: Node<readonly AgenticMemoryConsolidationRequest[]>;\n\t\treadonly outcomes: Node<readonly AgenticMemoryConsolidationOutcome<T>[]>;\n\t};\n\treadonly projection: Node<AgenticMemoryConsolidationSnapshot<T>>;\n\treadonly results: Node<readonly AgenticMemoryConsolidationResult[]>;\n\treadonly proposedRecordDrafts: Node<readonly AgenticMemoryConsolidationRecordDraft<T>[]>;\n\treadonly commands: Node<readonly AgenticMemoryConsolidationCommand[]>;\n\treadonly status: Node<AgenticMemoryConsolidationStatus>;\n\treadonly errors: Node<readonly AgenticMemoryConsolidationError[]>;\n\treadonly cursor: Node<AgenticMemoryConsolidationCursor>;\n}\n\nexport interface AgenticMemoryConsolidationBundleOptions<T = unknown> {\n\treadonly name?: string;\n\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly requests: Node<readonly AgenticMemoryConsolidationRequest[]>;\n\treadonly outcomes: Node<readonly AgenticMemoryConsolidationOutcome<T>[]>;\n}\n\nexport interface AgenticMemoryContextText {\n\treadonly fragmentId: FactId;\n\treadonly text: string;\n\treadonly cost?: number;\n\treadonly metadata?: Readonly<Record<string, StrictJsonValue>>;\n}\n\nexport interface AgenticMemoryContextPackingPolicy {\n\treadonly maxEntries?: number;\n\treadonly maxChars?: number;\n\treadonly maxCost?: number;\n\treadonly includeMetadata?: boolean;\n}\n\nexport interface AgenticMemoryPackedContextEntry {\n\treadonly fragmentId: FactId;\n\treadonly text: string;\n\treadonly cost: number;\n\treadonly chars: number;\n\treadonly record?: AgenticMemoryRecordMetadata;\n\treadonly metadata?: Readonly<Record<string, StrictJsonValue>>;\n}\n\nexport interface AgenticMemoryPackedContext {\n\treadonly entries: readonly AgenticMemoryPackedContextEntry[];\n\treadonly text: string;\n\treadonly totalChars: number;\n\treadonly totalCost: number;\n\treadonly truncated: boolean;\n}\n\nexport interface AgenticMemoryContextPackingCursor {\n\treadonly evaluation: number;\n\treadonly inputEntries: number;\n\treadonly packedEntries: number;\n\treadonly omittedEntries: number;\n\treadonly totalChars: number;\n\treadonly totalCost: number;\n}\n\nexport interface AgenticMemoryContextPackingStatus {\n\treadonly state: AgenticMemoryStatusState;\n\treadonly cursor: AgenticMemoryContextPackingCursor;\n}\n\nexport type AgenticMemoryContextPackingErrorCode =\n\t| \"invalid-context\"\n\t| \"invalid-texts-input\"\n\t| \"invalid-text\"\n\t| \"duplicate-text-fragment-id\"\n\t| \"missing-text\"\n\t| \"invalid-policy\";\n\nexport interface AgenticMemoryContextPackingError {\n\treadonly code: AgenticMemoryContextPackingErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly fragmentId?: FactId;\n\treadonly value?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryContextPackingCursor;\n}\n\nexport interface AgenticMemoryContextPackingSnapshot {\n\treadonly packedContext: AgenticMemoryPackedContext;\n\treadonly status: AgenticMemoryContextPackingStatus;\n\treadonly errors: readonly AgenticMemoryContextPackingError[];\n\treadonly cursor: AgenticMemoryContextPackingCursor;\n}\n\nexport interface AgenticMemoryContextPackingBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly context: Node<AgenticMemoryContext<T>>;\n\t\treadonly texts: Node<readonly AgenticMemoryContextText[]>;\n\t\treadonly policy: Node<AgenticMemoryContextPackingPolicy>;\n\t};\n\treadonly projection: Node<AgenticMemoryContextPackingSnapshot>;\n\treadonly packedContext: Node<AgenticMemoryPackedContext>;\n\treadonly status: Node<AgenticMemoryContextPackingStatus>;\n\treadonly errors: Node<readonly AgenticMemoryContextPackingError[]>;\n\treadonly cursor: Node<AgenticMemoryContextPackingCursor>;\n}\n\nexport interface AgenticMemoryContextPackingBundleOptions<T = unknown> {\n\treadonly name?: string;\n\treadonly context: Node<AgenticMemoryContext<T>>;\n\treadonly texts: Node<readonly AgenticMemoryContextText[]>;\n\treadonly policy: Node<AgenticMemoryContextPackingPolicy>;\n}\n\ninterface ValidatedPackingContext {\n\treadonly entries: readonly AgenticMemoryContextEntry[];\n}\n\nexport interface AgenticMemoryBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\t\treadonly query: Node<MemoryRetrievalQuery>;\n\t};\n\treadonly projection: Node<AgenticMemoryProjectionSnapshot<T>>;\n\treadonly retrieval: MemoryRetrievalBundle<T>;\n\treadonly retrievalSnapshot: Node<MemoryRetrievalSnapshot<T>>;\n\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly fragments: Node<readonly MemoryFragment<T>[]>;\n\treadonly sources: Node<readonly AgenticMemorySourceProjection[]>;\n\treadonly indexed: Node<MemoryRetrievalIndex<T>>;\n\treadonly ranked: Node<MemoryAnswer<T>>;\n\treadonly context: Node<AgenticMemoryContext<T>>;\n\treadonly status: Node<AgenticMemoryStatus>;\n\treadonly errors: Node<readonly AgenticMemoryError[]>;\n\treadonly retrievalStatus: Node<MemoryRetrievalStatus>;\n\treadonly retrievalErrors: Node<readonly MemoryRetrievalError[]>;\n\treadonly cursor: Node<MemoryRetrievalCursor>;\n}\n\nexport interface AgenticMemoryBundleOptions<T = unknown> {\n\treadonly name?: string;\n\t/** Explicit record-envelope input. Persistence, if needed, composes D161 outside this bundle. */\n\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\t/** Explicit retrieval query input. */\n\treadonly query: Node<MemoryRetrievalQuery>;\n}\n\n/**\n * Compose graph-visible semantic-memory retrieval into an agentic-memory v0 bundle.\n *\n * The returned nodes are ordinary graph nodes with declared deps and DATA facts.\n * Invalid record envelopes and duplicate record ids stay graph-visible through\n * solution-level status/errors DATA facts. The lower retrieval bundle remains\n * visible and receives only projected MemoryFragment values.\n */\nexport function agenticMemoryBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryBundleOptions<T>,\n): AgenticMemoryBundle<T> {\n\tconst name = opts.name ?? \"agenticMemory\";\n\tconst projection = agenticMemoryRecordProjection<T>(graph, opts.records, `${name}/projection`);\n\tconst projectedRecords = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/records`,\n\t\t\"agenticMemoryRecords\",\n\t\t(fact) => fact.records,\n\t);\n\tconst projectedFragments = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/fragments`,\n\t\t\"agenticMemoryFragments\",\n\t\t(fact) => fact.fragments,\n\t);\n\tconst status = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/status`,\n\t\t\"agenticMemoryStatus\",\n\t\t(fact) => fact.status,\n\t);\n\tconst errors = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/errors`,\n\t\t\"agenticMemoryErrors\",\n\t\t(fact) => fact.errors,\n\t);\n\tconst retrieval = memoryRetrievalBundle<T>(graph, {\n\t\tname: `${name}/retrieval`,\n\t\tfragments: projectedFragments,\n\t\tquery: opts.query,\n\t});\n\tconst sources = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/sources`,\n\t\t\"agenticMemorySources\",\n\t\t(fact) =>\n\t\t\tObject.freeze(\n\t\t\t\tfact.fragments.map((fragment) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tfragmentId: fragment.id,\n\t\t\t\t\t\t...(fact.metadataByFragmentId[fragment.id] === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { record: fact.metadataByFragmentId[fragment.id] }),\n\t\t\t\t\t\tsources: Object.freeze([...fragment.sources]),\n\t\t\t\t\t\t...(fragment.parentFragmentId === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t\t\t\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t),\n\t);\n\tconst context = agenticMemoryContextProjection(\n\t\tgraph,\n\t\tprojection,\n\t\tretrieval.snapshot,\n\t\t`${name}/context`,\n\t);\n\n\treturn {\n\t\tinput: { records: opts.records, query: opts.query },\n\t\tprojection,\n\t\tretrieval,\n\t\tretrievalSnapshot: retrieval.snapshot,\n\t\trecords: projectedRecords,\n\t\tfragments: projectedFragments,\n\t\tsources,\n\t\tindexed: retrieval.indexed,\n\t\tranked: retrieval.ranked,\n\t\tcontext,\n\t\tstatus,\n\t\terrors,\n\t\tretrievalStatus: retrieval.status,\n\t\tretrievalErrors: retrieval.errors,\n\t\tcursor: retrieval.cursor,\n\t};\n}\n\n/**\n * D165 solution-level KG assertion projection.\n *\n * Records and explicit assertion drafts stay visible as declared deps. This\n * bundle validates references and shape, then emits DATA facts only; it does\n * not extract assertions, call LLMs, read/write storage, or mutate topology.\n */\nexport function agenticMemoryKgProjectionBundle(\n\tgraph: Graph,\n\topts: AgenticMemoryKgProjectionBundleOptions,\n): AgenticMemoryKgProjectionBundle {\n\tconst name = opts.name ?? \"agenticMemoryKgProjection\";\n\tconst projection = graph.node<AgenticMemoryKgProjectionSnapshot>(\n\t\t[opts.records, opts.drafts],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst recordProjection = validateAndProjectRecords(depLatest(ctx, 0));\n\t\t\tconst draftProjection = validateAndProjectKgDrafts(\n\t\t\t\tdepLatest(ctx, 1),\n\t\t\t\trecordProjection.records,\n\t\t\t);\n\t\t\tconst cursor: AgenticMemoryKgProjectionCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRecords: recordProjection.records.length,\n\t\t\t\tvalidDrafts: draftProjection.assertions.length,\n\t\t\t\tinvalidDrafts: draftProjection.invalidDrafts,\n\t\t\t\tprojectedAssertions: draftProjection.assertions.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\t[...recordProjection.errors.map(kgErrorFromRecordError), ...draftProjection.errors].map(\n\t\t\t\t\t(error) => freezeError({ ...error, cursor }),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst status: AgenticMemoryKgProjectionStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(errors.length, draftProjection.assertions.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tassertions: Object.freeze(draftProjection.assertions),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryKgProjection\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { records: opts.records, drafts: opts.drafts },\n\t\tprojection,\n\t\tassertions: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/assertions`,\n\t\t\t\"agenticMemoryKgAssertions\",\n\t\t\t(fact) => fact.assertions,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryKgStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryKgErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryKgCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/** Build a D166 strict-JSON frame from an in-memory AgenticMemoryRecord. */\nexport function agenticMemoryRecordFrame<TJson extends StrictJsonValue>(\n\trecord: AgenticMemoryRecord<TJson>,\n): AgenticMemoryRecordFrame<TJson> {\n\tconst result = validateAndSnapshotRecord<TJson>(record, 0);\n\tif (result.errors.length > 0 || result.record === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`agenticMemoryRecordFrame: invalid record: ${result.errors\n\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\t}\n\tassertAgenticMemoryRecordCodecShape(record);\n\tassertStrictJsonValue(result.record.fragment.payload, \"record.fragment.payload\");\n\treturn Object.freeze({\n\t\tformat: AGENTIC_MEMORY_RECORD_FRAME_FORMAT,\n\t\tversion: AGENTIC_MEMORY_RECORD_FRAME_VERSION,\n\t\trecord: Object.freeze({\n\t\t\tid: result.record.id,\n\t\t\tkind: result.record.kind,\n\t\t\tpersistenceLevel: result.record.persistenceLevel,\n\t\t\tartifactKind: result.record.artifactKind,\n\t\t\t...(result.record.scope === undefined ? {} : { scope: result.record.scope }),\n\t\t\tfragment: fragmentFrame(result.record.fragment as MemoryFragment<TJson>),\n\t\t}),\n\t});\n}\n\n/** Assert and snapshot a decoded D166 record frame. Unknown fields fail honestly. */\nexport function assertAgenticMemoryRecordFrame<TJson extends StrictJsonValue = StrictJsonValue>(\n\tvalue: unknown,\n): AgenticMemoryRecordFrame<TJson> {\n\tif (!isPlainRecord(value))\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: frame must be an object\");\n\tassertStrictJsonValue(value, \"agenticMemoryRecordFrame\");\n\tassertExactKeys(value, [\"format\", \"record\", \"version\"], \"agenticMemoryRecordFrame\");\n\tif (value.format !== AGENTIC_MEMORY_RECORD_FRAME_FORMAT) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid format\");\n\t}\n\tif (value.version !== AGENTIC_MEMORY_RECORD_FRAME_VERSION) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid version\");\n\t}\n\tconst rawRecord = value.record;\n\tif (!isPlainRecord(rawRecord)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: record must be an object\");\n\t}\n\tassertExactKeys(\n\t\trawRecord,\n\t\trawRecord.scope === undefined\n\t\t\t? [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\"]\n\t\t\t: [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\", \"scope\"],\n\t\t\"agenticMemoryRecordFrame.record\",\n\t);\n\tconst rawFragment = rawRecord.fragment;\n\tif (!isPlainRecord(rawFragment)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: fragment must be an object\");\n\t}\n\tassertExactKeys(\n\t\trawFragment,\n\t\t[\n\t\t\t\"id\",\n\t\t\t\"payload\",\n\t\t\t\"tNs\",\n\t\t\t...(rawFragment.validFrom === undefined ? [] : [\"validFrom\"]),\n\t\t\t...(rawFragment.validTo === undefined ? [] : [\"validTo\"]),\n\t\t\t\"confidence\",\n\t\t\t\"tags\",\n\t\t\t\"sources\",\n\t\t\t...(rawFragment.embedding === undefined ? [] : [\"embedding\"]),\n\t\t\t...(rawFragment.parentFragmentId === undefined ? [] : [\"parentFragmentId\"]),\n\t\t\t...(rawFragment.provenance === undefined ? [] : [\"provenance\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.fragment\",\n\t);\n\tif (rawRecord.scope !== undefined) assertScopeFrame(rawRecord.scope);\n\tconst frame = value as unknown as AgenticMemoryRecordFrame<TJson>;\n\tconst decoded = recordFromFrame(frame);\n\tconst roundtrip = agenticMemoryRecordFrame(decoded);\n\treturn roundtrip as AgenticMemoryRecordFrame<TJson>;\n}\n\n/** Strict canonical JSON codec for D166 AgenticMemoryRecordFrame values. */\nexport function agenticMemoryRecordFrameCodec<\n\tTJson extends StrictJsonValue = StrictJsonValue,\n>(): Codec<AgenticMemoryRecordFrame<TJson>> {\n\treturn {\n\t\tencode(value: AgenticMemoryRecordFrame<TJson>): Uint8Array {\n\t\t\treturn strictJsonCodec.encode(assertAgenticMemoryRecordFrame<TJson>(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): AgenticMemoryRecordFrame<TJson> {\n\t\t\treturn assertAgenticMemoryRecordFrame<TJson>(strictJsonCodec.decode(bytes));\n\t\t},\n\t};\n}\n\n/** Strict canonical JSON codec that persists records and decodes bigint fields back to bigint. */\nexport function agenticMemoryRecordCodec<TJson extends StrictJsonValue = StrictJsonValue>(): Codec<\n\tAgenticMemoryRecord<TJson>\n> {\n\tconst frameCodec = agenticMemoryRecordFrameCodec<TJson>();\n\treturn {\n\t\tencode(value: AgenticMemoryRecord<TJson>): Uint8Array {\n\t\t\treturn frameCodec.encode(agenticMemoryRecordFrame(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): AgenticMemoryRecord<TJson> {\n\t\t\treturn recordFromFrame(frameCodec.decode(bytes));\n\t\t},\n\t};\n}\n\n/**\n * D167 solution-level retention command projection.\n *\n * Archive/restore/setPersistenceLevel are derived views over current records;\n * requestConsolidation emits request facts only.\n */\nexport function agenticMemoryRetentionBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryRetentionBundleOptions<T>,\n): AgenticMemoryRetentionBundle<T> {\n\tconst name = opts.name ?? \"agenticMemoryRetention\";\n\tconst projection = graph.node<AgenticMemoryRetentionSnapshot<T>>(\n\t\t[opts.records, opts.commands],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst recordProjection = validateAndProjectRecords<T>(depLatest(ctx, 0));\n\t\t\tconst retention = projectRetention<T>(depLatest(ctx, 1), recordProjection.records);\n\t\t\tconst cursor: AgenticMemoryRetentionCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRecords: recordProjection.records.length,\n\t\t\t\tvalidCommands: retention.validCommands,\n\t\t\t\tinvalidCommands: retention.invalidCommands,\n\t\t\t\tactiveRecords: retention.activeRecords.length,\n\t\t\t\tarchivedRecords: retention.archivedRecords.length,\n\t\t\t\tconsolidationRequests: retention.consolidationRequests.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\t[...recordProjection.errors.map(retentionErrorFromRecordError), ...retention.errors].map(\n\t\t\t\t\t(error) => freezeError({ ...error, cursor }),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst status: AgenticMemoryRetentionStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(errors.length, recordProjection.records.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tactiveRecords: Object.freeze(retention.activeRecords),\n\t\t\t\t\t\tarchivedRecords: Object.freeze(retention.archivedRecords),\n\t\t\t\t\t\tconsolidationRequests: Object.freeze(retention.consolidationRequests),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryRetention\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { records: opts.records, commands: opts.commands },\n\t\tprojection,\n\t\tactiveRecords: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/activeRecords`,\n\t\t\t\"agenticMemoryRetentionActiveRecords\",\n\t\t\t(fact) => fact.activeRecords,\n\t\t),\n\t\tarchivedRecords: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/archivedRecords`,\n\t\t\t\"agenticMemoryRetentionArchivedRecords\",\n\t\t\t(fact) => fact.archivedRecords,\n\t\t),\n\t\tconsolidationRequests: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/consolidationRequests`,\n\t\t\t\"agenticMemoryRetentionConsolidationRequests\",\n\t\t\t(fact) => fact.consolidationRequests,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryRetentionStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryRetentionErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryRetentionCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/**\n * D171 consolidation outcome projection.\n *\n * The bundle does not execute consolidation. External adapters may publish\n * outcome facts, and this projection turns them into visible result/proposal\n * facts for downstream record-creation policy.\n */\nexport function agenticMemoryConsolidationBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryConsolidationBundleOptions<T>,\n): AgenticMemoryConsolidationBundle<T> {\n\tconst name = opts.name ?? \"agenticMemoryConsolidation\";\n\tconst projection = graph.node<AgenticMemoryConsolidationSnapshot<T>>(\n\t\t[opts.records, opts.requests, opts.outcomes],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst recordProjection = validateAndProjectRecords<T>(depLatest(ctx, 0));\n\t\t\tconst requests = validateConsolidationRequests(depLatest(ctx, 1), recordProjection.records);\n\t\t\tconst outcomes = projectConsolidationOutcomes<T>(\n\t\t\t\tdepLatest(ctx, 2),\n\t\t\t\trequests.requests,\n\t\t\t\tstate.evaluation,\n\t\t\t);\n\t\t\tconst cursor: AgenticMemoryConsolidationCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRequests: requests.requests.length,\n\t\t\t\tvalidOutcomes: outcomes.validOutcomes,\n\t\t\t\tinvalidOutcomes: outcomes.invalidOutcomes,\n\t\t\t\tresults: outcomes.results.length,\n\t\t\t\tproposedRecordDrafts: outcomes.proposedRecordDrafts.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\t[\n\t\t\t\t\t...recordProjection.errors.map(consolidationErrorFromRecordError),\n\t\t\t\t\t...requests.errors.map(consolidationErrorFromRetentionError),\n\t\t\t\t\t...outcomes.errors,\n\t\t\t\t].map((error) => freezeError({ ...error, cursor })),\n\t\t\t);\n\t\t\tconst status: AgenticMemoryConsolidationStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(errors.length, outcomes.results.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tresults: Object.freeze(outcomes.results),\n\t\t\t\t\t\tproposedRecordDrafts: Object.freeze(outcomes.proposedRecordDrafts),\n\t\t\t\t\t\tcommands: Object.freeze(outcomes.commands),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryConsolidation\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { records: opts.records, requests: opts.requests, outcomes: opts.outcomes },\n\t\tprojection,\n\t\tresults: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/results`,\n\t\t\t\"agenticMemoryConsolidationResults\",\n\t\t\t(fact) => fact.results,\n\t\t),\n\t\tproposedRecordDrafts: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/proposedRecordDrafts`,\n\t\t\t\"agenticMemoryConsolidationRecordDrafts\",\n\t\t\t(fact) => fact.proposedRecordDrafts,\n\t\t),\n\t\tcommands: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/commands`,\n\t\t\t\"agenticMemoryConsolidationCommands\",\n\t\t\t(fact) => fact.commands,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryConsolidationStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryConsolidationErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryConsolidationCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/** D168 deterministic context-packing bundle over explicit context text facts. */\nexport function agenticMemoryContextPackingBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryContextPackingBundleOptions<T>,\n): AgenticMemoryContextPackingBundle<T> {\n\tconst name = opts.name ?? \"agenticMemoryContextPacking\";\n\tconst projection = graph.node<AgenticMemoryContextPackingSnapshot>(\n\t\t[opts.context, opts.texts, opts.policy],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst packed = packContext(\n\t\t\t\tdepLatest(ctx, 0),\n\t\t\t\tdepLatest(ctx, 1),\n\t\t\t\tdepLatest(ctx, 2),\n\t\t\t\tstate.evaluation,\n\t\t\t);\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([[\"DATA\", packed]]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryContextPacking\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { context: opts.context, texts: opts.texts, policy: opts.policy },\n\t\tprojection,\n\t\tpackedContext: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/packedContext`,\n\t\t\t\"agenticMemoryPackedContext\",\n\t\t\t(fact) => fact.packedContext,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryContextPackingStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryContextPackingErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryContextPackingCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\nfunction solutionProjection<TFact, TSnapshot>(\n\tgraph: Graph,\n\tsnapshot: Node<TSnapshot>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: TSnapshot) => TFact,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", select(raw as TSnapshot)]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction agenticMemoryProjection<TFact, T>(\n\tgraph: Graph,\n\tsnapshot: Node<AgenticMemoryProjectionSnapshot<T>>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: AgenticMemoryProjectionSnapshot<T>) => TFact,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", select(raw as AgenticMemoryProjectionSnapshot<T>)]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction agenticMemoryContextProjection<T>(\n\tgraph: Graph,\n\tprojection: Node<AgenticMemoryProjectionSnapshot<T>>,\n\tretrieval: Node<MemoryRetrievalSnapshot<T>>,\n\tname: string,\n): Node<AgenticMemoryContext<T>> {\n\treturn graph.node<AgenticMemoryContext<T>>(\n\t\t[projection, retrieval],\n\t\t(ctx) => {\n\t\t\tconst projectionFact = depLatest(ctx, 0) as AgenticMemoryProjectionSnapshot<T> | undefined;\n\t\t\tconst retrievalFacts = depBatch(ctx, 1) ?? [];\n\t\t\tif (projectionFact === undefined || retrievalFacts.length === 0) return;\n\t\t\tfor (const raw of retrievalFacts) {\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", contextFromSnapshot(projectionFact, raw as MemoryRetrievalSnapshot<T>)],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory: \"agenticMemoryContext\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction contextFromSnapshot<T>(\n\tprojection: AgenticMemoryProjectionSnapshot<T>,\n\tretrieval: MemoryRetrievalSnapshot<T>,\n): AgenticMemoryContext<T> {\n\tconst entries = retrieval.ranked.results.map((fragment) =>\n\t\tObject.freeze({\n\t\t\tfragmentId: fragment.id,\n\t\t\tpayload: fragment.payload,\n\t\t\tconfidence: fragment.confidence,\n\t\t\ttags: fragment.tags,\n\t\t\tsources: fragment.sources,\n\t\t\t...(projection.metadataByFragmentId[fragment.id] === undefined\n\t\t\t\t? {}\n\t\t\t\t: { record: projection.metadataByFragmentId[fragment.id] }),\n\t\t\tfragment,\n\t\t}),\n\t);\n\tconst hasContext = entries.length > 0;\n\tconst state = contextState(projection.status.state, retrieval.status.state);\n\treturn Object.freeze({\n\t\tstate,\n\t\tquery: retrieval.ranked.query,\n\t\tentries: Object.freeze(entries),\n\t\tcursor: retrieval.cursor,\n\t\terrors: projection.errors,\n\t\tretrievalErrors: retrieval.errors,\n\t\tcontextReady: hasContext && (state === \"ready\" || state === \"partial\"),\n\t});\n}\n\nfunction agenticMemoryRecordProjection<T>(\n\tgraph: Graph,\n\trecords: Node<readonly AgenticMemoryRecord<T>[]>,\n\tname: string,\n): Node<AgenticMemoryProjectionSnapshot<T>> {\n\treturn graph.node<AgenticMemoryProjectionSnapshot<T>>(\n\t\t[records],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst rawRecords = (depBatch(ctx, 0) ?? []).at(-1);\n\t\t\tconst projected = validateAndProjectRecords<T>(rawRecords);\n\t\t\tconst cursor: AgenticMemoryProjectionCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRecords: projected.records.length,\n\t\t\t\tinvalidRecords: projected.invalidRecordIndexes.size,\n\t\t\t\tprojectedFragments: projected.fragments.length,\n\t\t\t});\n\t\t\tconst status: AgenticMemoryStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(projected.errors.length, projected.records.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\tprojected.errors.map((error) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t...error,\n\t\t\t\t\t\t...(error.validationErrors === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\trecords: Object.freeze(projected.records),\n\t\t\t\t\t\tfragments: Object.freeze(projected.fragments),\n\t\t\t\t\t\tmetadataByFragmentId: Object.freeze(projected.metadataByFragmentId),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory: \"agenticMemoryProjection\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction validateAndProjectKgDrafts(\n\tvalue: unknown,\n\trecords: readonly AgenticMemoryRecord[],\n): {\n\treadonly assertions: KnowledgeAssertion[];\n\treadonly errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[];\n\treadonly invalidDrafts: number;\n} {\n\tconst assertions: KnowledgeAssertion[] = [];\n\tconst errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[] = [];\n\tlet invalidDrafts = 0;\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tinvalidDrafts: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-drafts-input\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: drafts input must be an array\",\n\t\t\t\t\tdraft: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tinvalidDrafts: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-drafts-input\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: drafts input length could not be read\",\n\t\t\t\t\tdraft: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst recordById = new Map(records.map((record) => [record.id, record]));\n\tconst fragmentToRecord = new Map(records.map((record) => [record.fragment.id, record.id]));\n\tconst seenAssertions = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = value[i];\n\t\t\tconst result = validateKgDraft(raw, i);\n\t\t\tif (result.errors.length > 0 || result.draft === undefined) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push(...result.errors);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst draft = result.draft;\n\t\t\tif (seenAssertions.has(draft.id)) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"duplicate-assertion-id\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: duplicate assertion id\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [`duplicate assertion id '${draft.id}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst record = recordById.get(draft.recordId);\n\t\t\tif (record === undefined) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-record-ref\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft references a missing record\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [`record '${draft.recordId}' is not projected`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst owner = fragmentToRecord.get(draft.fragmentId);\n\t\t\tif (owner === undefined) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-fragment-ref\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft references a missing fragment\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [`fragment '${draft.fragmentId}' is not projected`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (owner !== draft.recordId || record.fragment.id !== draft.fragmentId) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"fragment-record-mismatch\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft record and fragment refs disagree\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [\n\t\t\t\t\t\t`fragment '${draft.fragmentId}' belongs to record '${owner}', not '${draft.recordId}'`,\n\t\t\t\t\t],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tseenAssertions.add(draft.id);\n\t\t\tassertions.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tsubject: draft.subject,\n\t\t\t\t\tpredicate: draft.predicate,\n\t\t\t\t\tobject: draft.object,\n\t\t\t\t\t...(draft.confidence === undefined ? {} : { confidence: draft.confidence }),\n\t\t\t\t\tsources: Object.freeze(draft.sources ?? [draft.fragmentId]),\n\t\t\t\t\t...(draft.provenance === undefined ? {} : { provenance: draft.provenance }),\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tinvalidDrafts += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-draft\",\n\t\t\t\tmessage: `agenticMemoryKgProjectionBundle: draft access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tdraft: raw,\n\t\t\t\tvalidationErrors: [\"draft access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\treturn { assertions, errors, invalidDrafts };\n}\n\nfunction validateKgDraft(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly draft?: AgenticMemoryKgAssertionDraft;\n\treadonly errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[];\n} {\n\tconst errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[] = [];\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-draft\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft must be an object\",\n\t\t\t\t\tindex,\n\t\t\t\t\tdraft: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst raw = value as Partial<AgenticMemoryKgAssertionDraft>;\n\tconst id = typeof raw.id === \"string\" && raw.id.length > 0 ? raw.id : undefined;\n\tconst recordId =\n\t\ttypeof raw.recordId === \"string\" && raw.recordId.length > 0 ? raw.recordId : undefined;\n\tconst fragmentId =\n\t\ttypeof raw.fragmentId === \"string\" && raw.fragmentId.length > 0 ? raw.fragmentId : undefined;\n\tconst subject = validateAssertionSubject(raw.subject);\n\tconst object = validateAssertionObject(raw.object);\n\tconst shapeErrors: string[] = [];\n\tif (id === undefined) shapeErrors.push(\"draft.id must be a non-empty string\");\n\tif (recordId === undefined) {\n\t\tshapeErrors.push(\"draft.recordId must be a non-empty string\");\n\t}\n\tif (fragmentId === undefined) {\n\t\tshapeErrors.push(\"draft.fragmentId must be a non-empty string\");\n\t}\n\tshapeErrors.push(...subject.errors);\n\tif (typeof raw.predicate !== \"string\" || raw.predicate.length === 0) {\n\t\tshapeErrors.push(\"draft.predicate must be a non-empty string\");\n\t}\n\tshapeErrors.push(...object.errors);\n\tif (\n\t\traw.confidence !== undefined &&\n\t\t(!Number.isFinite(raw.confidence) || raw.confidence < 0 || raw.confidence > 1)\n\t) {\n\t\tshapeErrors.push(\"draft.confidence must be a finite number in [0, 1]\");\n\t}\n\tif (raw.sources !== undefined && !isDenseArrayOf(raw.sources, isNonEmptyString)) {\n\t\tshapeErrors.push(\"draft.sources must be a readonly string array\");\n\t}\n\tif (raw.provenance !== undefined && typeof raw.provenance !== \"string\") {\n\t\tshapeErrors.push(\"draft.provenance must be a string when present\");\n\t}\n\tif (shapeErrors.length > 0) errors.push(kgShapeError(index, value, ...shapeErrors));\n\tif (errors.length > 0 || id === undefined || recordId === undefined || fragmentId === undefined) {\n\t\treturn { errors };\n\t}\n\treturn {\n\t\tdraft: Object.freeze({\n\t\t\tid,\n\t\t\trecordId,\n\t\t\tfragmentId,\n\t\t\tsubject: subject.subject as KnowledgeAssertionSubject,\n\t\t\tpredicate: raw.predicate as string,\n\t\t\tobject: object.object as KnowledgeAssertionObject,\n\t\t\t...(raw.confidence === undefined ? {} : { confidence: raw.confidence }),\n\t\t\t...(raw.sources === undefined ? {} : { sources: Object.freeze([...raw.sources]) }),\n\t\t\t...(raw.provenance === undefined ? {} : { provenance: raw.provenance }),\n\t\t}),\n\t\terrors,\n\t};\n}\n\nfunction validateAssertionSubject(value: unknown): {\n\treadonly subject?: KnowledgeAssertionSubject;\n\treadonly errors: readonly string[];\n} {\n\tif (!isPlainRecord(value)) return { errors: [\"subject must be an object\"] };\n\tconst id = value.id;\n\tconst type = value.type;\n\tconst errors: string[] = [];\n\tif (typeof id !== \"string\" || id.length === 0) errors.push(\"subject.id must be non-empty\");\n\tif (type !== undefined && (typeof type !== \"string\" || type.length === 0)) {\n\t\terrors.push(\"subject.type must be a non-empty string when present\");\n\t}\n\tif (errors.length > 0) return { errors };\n\treturn {\n\t\tsubject: Object.freeze({\n\t\t\tid: id as string,\n\t\t\t...(type === undefined ? {} : { type: type as string }),\n\t\t}),\n\t\terrors,\n\t};\n}\n\nfunction validateAssertionObject(value: unknown): {\n\treadonly object?: KnowledgeAssertionObject;\n\treadonly errors: readonly string[];\n} {\n\tif (!isPlainRecord(value)) return { errors: [\"object must be an object\"] };\n\tconst kind = value.kind;\n\tconst errors: string[] = [];\n\tif (kind === \"entity\") {\n\t\tif (typeof value.id !== \"string\" || value.id.length === 0) {\n\t\t\terrors.push(\"object.id must be non-empty for entity objects\");\n\t\t}\n\t\tif (value.type !== undefined && (typeof value.type !== \"string\" || value.type.length === 0)) {\n\t\t\terrors.push(\"object.type must be a non-empty string when present\");\n\t\t}\n\t\tif (Object.hasOwn(value, \"value\")) errors.push(\"entity object must not include value\");\n\t\tif (errors.length > 0) return { errors };\n\t\treturn {\n\t\t\tobject: Object.freeze({\n\t\t\t\tkind: \"entity\",\n\t\t\t\tid: value.id as string,\n\t\t\t\t...(value.type === undefined ? {} : { type: value.type as string }),\n\t\t\t}),\n\t\t\terrors,\n\t\t};\n\t}\n\tif (kind === \"value\") {\n\t\tif (!Object.hasOwn(value, \"value\")) errors.push(\"value object must include value\");\n\t\telse {\n\t\t\ttry {\n\t\t\t\tassertStrictJsonValue(value.value, \"object.value\");\n\t\t\t} catch (error) {\n\t\t\t\terrors.push(errorMessage(error));\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\tvalue.valueType !== undefined &&\n\t\t\t(typeof value.valueType !== \"string\" || value.valueType.length === 0)\n\t\t) {\n\t\t\terrors.push(\"object.valueType must be a non-empty string when present\");\n\t\t}\n\t\tif (Object.hasOwn(value, \"id\")) errors.push(\"value object must not include id\");\n\t\tif (errors.length > 0) return { errors };\n\t\treturn {\n\t\t\tobject: Object.freeze({\n\t\t\t\tkind: \"value\",\n\t\t\t\tvalue: value.value as StrictJsonValue,\n\t\t\t\t...(value.valueType === undefined ? {} : { valueType: value.valueType as string }),\n\t\t\t}),\n\t\t\terrors,\n\t\t};\n\t}\n\treturn { errors: [\"object.kind must be entity or value\"] };\n}\n\nfunction kgShapeError(\n\tindex: number,\n\tdraft: unknown,\n\t...validationErrors: readonly string[]\n): Omit<AgenticMemoryKgProjectionError, \"cursor\"> {\n\treturn {\n\t\tcode: \"invalid-assertion-shape\",\n\t\tmessage: \"agenticMemoryKgProjectionBundle: draft assertion shape is invalid\",\n\t\tindex,\n\t\tdraft,\n\t\tvalidationErrors: Object.freeze([...validationErrors]),\n\t};\n}\n\nfunction kgErrorFromRecordError(\n\terror: Omit<AgenticMemoryError, \"cursor\">,\n): Omit<AgenticMemoryKgProjectionError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n\nfunction fragmentFrame<TJson extends StrictJsonValue>(\n\tfragment: MemoryFragment<TJson>,\n): AgenticMemoryFragmentFrame<TJson> {\n\treturn Object.freeze({\n\t\tid: fragment.id,\n\t\tpayload: fragment.payload,\n\t\ttNs: decimalBigIntString(fragment.tNs, \"fragment.tNs\"),\n\t\t...(fragment.validFrom === undefined\n\t\t\t? {}\n\t\t\t: { validFrom: decimalBigIntString(fragment.validFrom, \"fragment.validFrom\") }),\n\t\t...(fragment.validTo === undefined\n\t\t\t? {}\n\t\t\t: { validTo: decimalBigIntString(fragment.validTo, \"fragment.validTo\") }),\n\t\tconfidence: fragment.confidence,\n\t\ttags: Object.freeze([...fragment.tags]),\n\t\tsources: Object.freeze([...fragment.sources]),\n\t\t...(fragment.embedding === undefined\n\t\t\t? {}\n\t\t\t: { embedding: Object.freeze([...fragment.embedding]) }),\n\t\t...(fragment.parentFragmentId === undefined\n\t\t\t? {}\n\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t});\n}\n\nfunction recordFromFrame<TJson extends StrictJsonValue>(\n\tframe: AgenticMemoryRecordFrame<TJson>,\n): AgenticMemoryRecord<TJson> {\n\tconst fragment = frame.record.fragment;\n\tconst record: AgenticMemoryRecord<TJson> = {\n\t\tid: assertNonEmptyString(frame.record.id, \"record.id\"),\n\t\tkind: assertKindValue(frame.record.kind),\n\t\tpersistenceLevel: assertPersistenceLevelValue(frame.record.persistenceLevel),\n\t\tartifactKind: assertArtifactKindValue(frame.record.artifactKind),\n\t\t...(frame.record.scope === undefined ? {} : { scope: assertScopeFrame(frame.record.scope) }),\n\t\tfragment: {\n\t\t\tid: assertNonEmptyString(fragment.id, \"fragment.id\"),\n\t\t\tpayload: assertStrictJsonValue(fragment.payload, \"fragment.payload\") as TJson,\n\t\t\ttNs: parseDecimalBigInt(fragment.tNs, \"fragment.tNs\"),\n\t\t\t...(fragment.validFrom === undefined\n\t\t\t\t? {}\n\t\t\t\t: { validFrom: parseDecimalBigInt(fragment.validFrom, \"fragment.validFrom\") }),\n\t\t\t...(fragment.validTo === undefined\n\t\t\t\t? {}\n\t\t\t\t: { validTo: parseDecimalBigInt(fragment.validTo, \"fragment.validTo\") }),\n\t\t\tconfidence: assertConfidence(fragment.confidence, \"fragment.confidence\"),\n\t\t\ttags: assertStringArray(fragment.tags, \"fragment.tags\"),\n\t\t\tsources: assertStringArray(fragment.sources, \"fragment.sources\"),\n\t\t\t...(fragment.embedding === undefined\n\t\t\t\t? {}\n\t\t\t\t: { embedding: assertFiniteNumberArray(fragment.embedding, \"fragment.embedding\") }),\n\t\t\t...(fragment.parentFragmentId === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tparentFragmentId: assertNonEmptyString(fragment.parentFragmentId, \"parentFragmentId\"),\n\t\t\t\t\t}),\n\t\t\t...(fragment.provenance === undefined\n\t\t\t\t? {}\n\t\t\t\t: { provenance: assertString(fragment.provenance, \"provenance\") }),\n\t\t},\n\t};\n\tconst result = validateAndSnapshotRecord<TJson>(record, 0);\n\tif (result.errors.length > 0 || result.record === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`agenticMemoryRecordFrame: decoded record is invalid: ${result.errors\n\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\t}\n\treturn result.record;\n}\n\nfunction projectRetention<T>(\n\tvalue: unknown,\n\trecords: readonly AgenticMemoryRecord<T>[],\n): {\n\treadonly activeRecords: AgenticMemoryRecord<T>[];\n\treadonly archivedRecords: AgenticMemoryRecord<T>[];\n\treadonly consolidationRequests: AgenticMemoryConsolidationRequest[];\n\treadonly errors: Omit<AgenticMemoryRetentionError, \"cursor\">[];\n\treadonly validCommands: number;\n\treadonly invalidCommands: number;\n} {\n\tconst byId = new Map(records.map((record) => [record.id, record]));\n\tconst view = new Map(records.map((record) => [record.id, record]));\n\tconst requests: AgenticMemoryConsolidationRequest[] = [];\n\tconst errors: Omit<AgenticMemoryRetentionError, \"cursor\">[] = [];\n\tlet validCommands = 0;\n\tlet invalidCommands = 0;\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tactiveRecords: records.filter((record) => record.persistenceLevel !== \"archived\"),\n\t\t\tarchivedRecords: records.filter((record) => record.persistenceLevel === \"archived\"),\n\t\t\tconsolidationRequests: requests,\n\t\t\tvalidCommands,\n\t\t\tinvalidCommands: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: commands input must be an array\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tactiveRecords: records.filter((record) => record.persistenceLevel !== \"archived\"),\n\t\t\tarchivedRecords: records.filter((record) => record.persistenceLevel === \"archived\"),\n\t\t\tconsolidationRequests: requests,\n\t\t\tvalidCommands,\n\t\t\tinvalidCommands: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: commands input length could not be read\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst seenCommands = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = value[i];\n\t\t\tconst result = validateRetentionCommand(raw, i);\n\t\t\tif (result.errors.length > 0 || result.command === undefined) {\n\t\t\t\tinvalidCommands += 1;\n\t\t\t\terrors.push(...result.errors);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst command = result.command;\n\t\t\tif (seenCommands.has(command.id)) {\n\t\t\t\tinvalidCommands += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"duplicate-command-id\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: duplicate command id\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tcommandId: command.id,\n\t\t\t\t\tcommand: raw,\n\t\t\t\t\tvalidationErrors: [`duplicate command id '${command.id}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst missing = retentionMissingRecords(command, byId);\n\t\t\tif (missing.length > 0) {\n\t\t\t\tinvalidCommands += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-record-ref\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: command references missing records\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tcommandId: command.id,\n\t\t\t\t\trecordId: \"recordId\" in command ? command.recordId : undefined,\n\t\t\t\t\trecordIds: Object.freeze(missing),\n\t\t\t\t\tcommand: raw,\n\t\t\t\t\tvalidationErrors: Object.freeze(missing.map((id) => `record '${id}' is not projected`)),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tseenCommands.add(command.id);\n\t\t\tvalidCommands += 1;\n\t\t\tapplyRetentionCommand(command, byId, view, requests);\n\t\t} catch (error) {\n\t\t\tinvalidCommands += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: `agenticMemoryRetentionBundle: command access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tcommand: raw,\n\t\t\t\tvalidationErrors: [\"command access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\tconst projected = records.map((record) => view.get(record.id) ?? record);\n\treturn {\n\t\tactiveRecords: projected.filter((record) => record.persistenceLevel !== \"archived\"),\n\t\tarchivedRecords: projected.filter((record) => record.persistenceLevel === \"archived\"),\n\t\tconsolidationRequests: requests,\n\t\terrors,\n\t\tvalidCommands,\n\t\tinvalidCommands,\n\t};\n}\n\nfunction validateRetentionCommand(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly command?: AgenticMemoryRetentionCommand;\n\treadonly errors: Omit<AgenticMemoryRetentionError, \"cursor\">[];\n} {\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-command\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: command must be an object\",\n\t\t\t\t\tindex,\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst id = typeof value.id === \"string\" && value.id.length > 0 ? value.id : undefined;\n\tconst kind = value.kind;\n\tconst errors: string[] = [];\n\tif (id === undefined) errors.push(\"command.id must be a non-empty string\");\n\tif (\n\t\tkind !== \"archive\" &&\n\t\tkind !== \"restore\" &&\n\t\tkind !== \"setPersistenceLevel\" &&\n\t\tkind !== \"requestConsolidation\"\n\t) {\n\t\terrors.push(\"command.kind is invalid\");\n\t}\n\tif (value.reason !== undefined && typeof value.reason !== \"string\") {\n\t\terrors.push(\"command.reason must be a string when present\");\n\t}\n\tif (kind === \"archive\") {\n\t\tif (!isNonEmptyString(value.recordId)) errors.push(\"command.recordId must be non-empty\");\n\t} else if (kind === \"restore\") {\n\t\tif (!isNonEmptyString(value.recordId)) errors.push(\"command.recordId must be non-empty\");\n\t\tif (\n\t\t\tvalue.persistenceLevel !== undefined &&\n\t\t\t(!isAgenticMemoryPersistenceLevel(value.persistenceLevel) ||\n\t\t\t\tvalue.persistenceLevel === \"archived\")\n\t\t) {\n\t\t\terrors.push(\"restore.persistenceLevel must be a non-archived persistence level when present\");\n\t\t}\n\t} else if (kind === \"setPersistenceLevel\") {\n\t\tif (!isNonEmptyString(value.recordId)) errors.push(\"command.recordId must be non-empty\");\n\t\tif (!isAgenticMemoryPersistenceLevel(value.persistenceLevel)) {\n\t\t\terrors.push(\"setPersistenceLevel.persistenceLevel is invalid\");\n\t\t}\n\t} else if (kind === \"requestConsolidation\") {\n\t\tif (!isDenseArrayOf(value.recordIds, isNonEmptyString) || value.recordIds.length === 0) {\n\t\t\terrors.push(\"requestConsolidation.recordIds must be a non-empty string array\");\n\t\t}\n\t\tif (\n\t\t\tvalue.requestId !== undefined &&\n\t\t\t(typeof value.requestId !== \"string\" || value.requestId.length === 0)\n\t\t) {\n\t\t\terrors.push(\"requestConsolidation.requestId must be non-empty when present\");\n\t\t}\n\t}\n\tif (errors.length > 0 || id === undefined) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-command\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: command is invalid\",\n\t\t\t\t\tindex,\n\t\t\t\t\tcommandId: id,\n\t\t\t\t\tcommand: value,\n\t\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst base = { id, reason: value.reason as string | undefined };\n\tif (kind === \"archive\") {\n\t\treturn {\n\t\t\tcommand: Object.freeze({\n\t\t\t\t...base,\n\t\t\t\tkind,\n\t\t\t\trecordId: value.recordId as string,\n\t\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t\t}),\n\t\t\terrors: [],\n\t\t};\n\t}\n\tif (kind === \"restore\") {\n\t\treturn {\n\t\t\tcommand: Object.freeze({\n\t\t\t\t...base,\n\t\t\t\tkind,\n\t\t\t\trecordId: value.recordId as string,\n\t\t\t\t...(value.persistenceLevel === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tpersistenceLevel: value.persistenceLevel as Exclude<\n\t\t\t\t\t\t\t\tAgenticMemoryPersistenceLevel,\n\t\t\t\t\t\t\t\t\"archived\"\n\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t}),\n\t\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t\t}),\n\t\t\terrors: [],\n\t\t};\n\t}\n\tif (kind === \"setPersistenceLevel\") {\n\t\treturn {\n\t\t\tcommand: Object.freeze({\n\t\t\t\t...base,\n\t\t\t\tkind,\n\t\t\t\trecordId: value.recordId as string,\n\t\t\t\tpersistenceLevel: value.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t\t}),\n\t\t\terrors: [],\n\t\t};\n\t}\n\treturn {\n\t\tcommand: Object.freeze({\n\t\t\t...base,\n\t\t\tkind: \"requestConsolidation\",\n\t\t\trecordIds: Object.freeze([...(value.recordIds as readonly string[])]),\n\t\t\t...(value.requestId === undefined ? {} : { requestId: value.requestId as string }),\n\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t}),\n\t\terrors: [],\n\t};\n}\n\nfunction retentionMissingRecords(\n\tcommand: AgenticMemoryRetentionCommand,\n\trecords: ReadonlyMap<FactId, AgenticMemoryRecord>,\n): readonly FactId[] {\n\tif (\"recordId\" in command) return records.has(command.recordId) ? [] : [command.recordId];\n\treturn command.recordIds.filter((recordId) => !records.has(recordId));\n}\n\nfunction applyRetentionCommand<T>(\n\tcommand: AgenticMemoryRetentionCommand,\n\tsource: ReadonlyMap<FactId, AgenticMemoryRecord<T>>,\n\tview: Map<FactId, AgenticMemoryRecord<T>>,\n\trequests: AgenticMemoryConsolidationRequest[],\n): void {\n\tif (command.kind === \"requestConsolidation\") {\n\t\trequests.push(\n\t\t\tObject.freeze({\n\t\t\t\tid: command.requestId ?? command.id,\n\t\t\t\tcommandId: command.id,\n\t\t\t\trecordIds: Object.freeze([...command.recordIds]),\n\t\t\t\t...(command.reason === undefined ? {} : { reason: command.reason }),\n\t\t\t}),\n\t\t);\n\t\treturn;\n\t}\n\tconst record = view.get(command.recordId) ?? source.get(command.recordId);\n\tif (record === undefined) return;\n\tconst persistenceLevel =\n\t\tcommand.kind === \"archive\"\n\t\t\t? \"archived\"\n\t\t\t: command.kind === \"restore\"\n\t\t\t\t? (command.persistenceLevel ?? nonArchivedLevel(source.get(command.recordId) ?? record))\n\t\t\t\t: command.persistenceLevel;\n\tview.set(command.recordId, withPersistenceLevel(record, persistenceLevel));\n}\n\nfunction nonArchivedLevel(\n\trecord: AgenticMemoryRecord,\n): Exclude<AgenticMemoryPersistenceLevel, \"archived\"> {\n\treturn record.persistenceLevel === \"archived\" ? \"session\" : record.persistenceLevel;\n}\n\nfunction withPersistenceLevel<T>(\n\trecord: AgenticMemoryRecord<T>,\n\tpersistenceLevel: AgenticMemoryPersistenceLevel,\n): AgenticMemoryRecord<T> {\n\treturn Object.freeze({\n\t\t...record,\n\t\tpersistenceLevel,\n\t});\n}\n\nfunction retentionErrorFromRecordError(\n\terror: Omit<AgenticMemoryError, \"cursor\">,\n): Omit<AgenticMemoryRetentionError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n\nfunction validateConsolidationRequests<T>(\n\tvalue: unknown,\n\trecords: readonly AgenticMemoryRecord<T>[],\n): {\n\treadonly requests: readonly AgenticMemoryConsolidationRequest[];\n\treadonly errors: readonly Omit<AgenticMemoryRetentionError, \"cursor\">[];\n} {\n\tconst byId = new Map(records.map((record) => [record.id, record]));\n\tconst requests: AgenticMemoryConsolidationRequest[] = [];\n\tconst errors: Omit<AgenticMemoryRetentionError, \"cursor\">[] = [];\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\trequests,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: requests input must be an array\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\trequests,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: requests input length could not be read\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst seen = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\tif (!Object.hasOwn(value, i)) {\n\t\t\t\tthrow new TypeError(\"request array must be dense\");\n\t\t\t}\n\t\t\traw = value[i];\n\t\t} catch (error) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: `agenticMemoryConsolidationBundle: request access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalidationErrors: Object.freeze([\"request access failed\"]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!isPlainRecord(raw)) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: request must be an object\",\n\t\t\t\tindex: i,\n\t\t\t\tcommand: raw,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = isNonEmptyString(raw.id) ? raw.id : undefined;\n\t\tconst commandId = isNonEmptyString(raw.commandId) ? raw.commandId : undefined;\n\t\tconst recordIds = isDenseArrayOf(raw.recordIds, isNonEmptyString)\n\t\t\t? Object.freeze([...raw.recordIds])\n\t\t\t: undefined;\n\t\tconst validationErrors: string[] = [];\n\t\tif (id === undefined) validationErrors.push(\"request.id must be a non-empty string\");\n\t\tif (commandId === undefined) {\n\t\t\tvalidationErrors.push(\"request.commandId must be a non-empty string\");\n\t\t}\n\t\tif (recordIds === undefined || recordIds.length === 0) {\n\t\t\tvalidationErrors.push(\"request.recordIds must be a non-empty string array\");\n\t\t}\n\t\tif (raw.reason !== undefined && typeof raw.reason !== \"string\") {\n\t\t\tvalidationErrors.push(\"request.reason must be a string when present\");\n\t\t}\n\t\tif (id !== undefined && seen.has(id)) {\n\t\t\tvalidationErrors.push(`duplicate request id '${id}'`);\n\t\t}\n\t\tconst missing = (recordIds ?? []).filter((recordId) => !byId.has(recordId));\n\t\tif (missing.length > 0) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"missing-record-ref\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: request references missing records\",\n\t\t\t\tindex: i,\n\t\t\t\tcommandId,\n\t\t\t\trecordIds: Object.freeze(missing),\n\t\t\t\tcommand: raw,\n\t\t\t\tvalidationErrors: Object.freeze(\n\t\t\t\t\tmissing.map((recordId) => `record '${recordId}' is not projected`),\n\t\t\t\t),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (\n\t\t\tvalidationErrors.length > 0 ||\n\t\t\tid === undefined ||\n\t\t\tcommandId === undefined ||\n\t\t\trecordIds === undefined\n\t\t) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: request is invalid\",\n\t\t\t\tindex: i,\n\t\t\t\tcommandId,\n\t\t\t\trecordIds,\n\t\t\t\tcommand: raw,\n\t\t\t\tvalidationErrors: Object.freeze(validationErrors),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(id);\n\t\trequests.push(\n\t\t\tObject.freeze({\n\t\t\t\tid,\n\t\t\t\tcommandId,\n\t\t\t\trecordIds,\n\t\t\t\t...(raw.reason === undefined ? {} : { reason: raw.reason as string }),\n\t\t\t}),\n\t\t);\n\t}\n\treturn { requests: Object.freeze(requests), errors };\n}\n\nfunction projectConsolidationOutcomes<T>(\n\tvalue: unknown,\n\trequests: readonly AgenticMemoryConsolidationRequest[],\n\tevaluation: number,\n): {\n\treadonly results: readonly AgenticMemoryConsolidationResult[];\n\treadonly proposedRecordDrafts: readonly AgenticMemoryConsolidationRecordDraft<T>[];\n\treadonly commands: readonly AgenticMemoryConsolidationCommand[];\n\treadonly errors: readonly Omit<AgenticMemoryConsolidationError, \"cursor\">[];\n\treadonly validOutcomes: number;\n\treadonly invalidOutcomes: number;\n} {\n\tconst byRequest = new Map(requests.map((request) => [request.id, request]));\n\tconst results: AgenticMemoryConsolidationResult[] = [];\n\tconst proposedRecordDrafts: AgenticMemoryConsolidationRecordDraft<T>[] = [];\n\tconst commands: AgenticMemoryConsolidationCommand[] = [];\n\tconst errors: Omit<AgenticMemoryConsolidationError, \"cursor\">[] = [];\n\tlet validOutcomes = 0;\n\tlet invalidOutcomes = 0;\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tresults,\n\t\t\tproposedRecordDrafts,\n\t\t\tcommands,\n\t\t\tvalidOutcomes,\n\t\t\tinvalidOutcomes: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-outcomes-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcomes input must be an array\",\n\t\t\t\t\toutcome: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tresults,\n\t\t\tproposedRecordDrafts,\n\t\t\tcommands,\n\t\t\tvalidOutcomes,\n\t\t\tinvalidOutcomes: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-outcomes-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcomes input length could not be read\",\n\t\t\t\t\toutcome: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst seenOutcomes = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\tlet outcome: {\n\t\t\treadonly outcome?: AgenticMemoryConsolidationOutcome<T>;\n\t\t\treadonly error?: Omit<AgenticMemoryConsolidationError, \"cursor\">;\n\t\t};\n\t\ttry {\n\t\t\tif (!Object.hasOwn(value, i)) {\n\t\t\t\tthrow new TypeError(\"outcome array must be dense\");\n\t\t\t}\n\t\t\traw = value[i];\n\t\t\toutcome = validateConsolidationOutcome<T>(raw, i);\n\t\t} catch (error) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-outcome\",\n\t\t\t\tmessage: `agenticMemoryConsolidationBundle: outcome access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\toutcome: raw,\n\t\t\t\tvalidationErrors: Object.freeze([\"outcome access failed\"]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (outcome.error !== undefined || outcome.outcome === undefined) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\tif (outcome.error !== undefined) errors.push(outcome.error);\n\t\t\tcontinue;\n\t\t}\n\t\tconst validOutcome = outcome.outcome;\n\t\tif (seenOutcomes.has(validOutcome.id)) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-outcome-id\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: duplicate outcome id\",\n\t\t\t\tindex: i,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcome: raw,\n\t\t\t\tvalidationErrors: Object.freeze([`duplicate outcome id '${validOutcome.id}'`]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst request = byRequest.get(validOutcome.requestId);\n\t\tif (request === undefined) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"missing-request-ref\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcome references missing request\",\n\t\t\t\tindex: i,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcome: raw,\n\t\t\t\tvalidationErrors: Object.freeze([`request '${validOutcome.requestId}' is not projected`]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseenOutcomes.add(validOutcome.id);\n\t\tvalidOutcomes += 1;\n\t\tif (validOutcome.kind === \"failed\") {\n\t\t\tconst resultId = `${validOutcome.requestId}:${validOutcome.id}`;\n\t\t\tresults.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: resultId,\n\t\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\t\tstate: \"failed\",\n\t\t\t\t\tsourceRecordIds: request.recordIds,\n\t\t\t\t\tproposedRecordIds: Object.freeze([]),\n\t\t\t\t\tmessage: validOutcome.message,\n\t\t\t\t\t...(validOutcome.provenance === undefined ? {} : { provenance: validOutcome.provenance }),\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcommands.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: `${resultId}:markFailed`,\n\t\t\t\t\tkind: \"markFailed\",\n\t\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\t\tmessage: validOutcome.message,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst draftIds = validOutcome.records.map(\n\t\t\t(record) => `${validOutcome.requestId}:${validOutcome.id}:${record.id}`,\n\t\t);\n\t\tfor (let recordIndex = 0; recordIndex < validOutcome.records.length; recordIndex += 1) {\n\t\t\tproposedRecordDrafts.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: draftIds[recordIndex] as FactId,\n\t\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\t\trecord: validOutcome.records[recordIndex] as AgenticMemoryRecord<T>,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tconst resultId = `${validOutcome.requestId}:${validOutcome.id}`;\n\t\tresults.push(\n\t\t\tObject.freeze({\n\t\t\t\tid: resultId,\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\tstate: \"proposed\",\n\t\t\t\tsourceRecordIds: request.recordIds,\n\t\t\t\tproposedRecordIds: Object.freeze(validOutcome.records.map((record) => record.id)),\n\t\t\t\t...(validOutcome.provenance === undefined ? {} : { provenance: validOutcome.provenance }),\n\t\t\t}),\n\t\t);\n\t\tcommands.push(\n\t\t\tObject.freeze({\n\t\t\t\tid: `${resultId}:proposeRecords`,\n\t\t\t\tkind: \"proposeRecords\",\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\tdraftIds: Object.freeze(draftIds),\n\t\t\t}),\n\t\t);\n\t}\n\tvoid evaluation;\n\treturn {\n\t\tresults: Object.freeze(results),\n\t\tproposedRecordDrafts: Object.freeze(proposedRecordDrafts),\n\t\tcommands: Object.freeze(commands),\n\t\terrors,\n\t\tvalidOutcomes,\n\t\tinvalidOutcomes,\n\t};\n}\n\nfunction validateConsolidationOutcome<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly outcome?: AgenticMemoryConsolidationOutcome<T>;\n\treadonly error?: Omit<AgenticMemoryConsolidationError, \"cursor\">;\n} {\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-outcome\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcome must be an object\",\n\t\t\t\tindex,\n\t\t\t\toutcome: value,\n\t\t\t},\n\t\t};\n\t}\n\tconst errors: string[] = [];\n\tconst id = isNonEmptyString(value.id) ? value.id : undefined;\n\tconst requestId = isNonEmptyString(value.requestId) ? value.requestId : undefined;\n\tif (id === undefined) errors.push(\"outcome.id must be a non-empty string\");\n\tif (requestId === undefined) errors.push(\"outcome.requestId must be a non-empty string\");\n\tif (value.kind !== \"proposedRecords\" && value.kind !== \"failed\") {\n\t\terrors.push(\"outcome.kind must be proposedRecords or failed\");\n\t}\n\tif (value.provenance !== undefined && typeof value.provenance !== \"string\") {\n\t\terrors.push(\"outcome.provenance must be a string when present\");\n\t}\n\tif (value.kind === \"failed\" && !isNonEmptyString(value.message)) {\n\t\terrors.push(\"failed outcome.message must be a non-empty string\");\n\t}\n\tconst records: AgenticMemoryRecord<T>[] = [];\n\tif (value.kind === \"proposedRecords\") {\n\t\tif (!Array.isArray(value.records)) {\n\t\t\terrors.push(\"proposedRecords.records must be a non-empty array\");\n\t\t} else {\n\t\t\tconst recordsLength = safeArrayLength(value.records);\n\t\t\tconst seenRecordIds = new Set<FactId>();\n\t\t\tif (recordsLength === undefined || recordsLength === 0) {\n\t\t\t\terrors.push(\"proposedRecords.records must be a non-empty array\");\n\t\t\t}\n\t\t\tfor (let i = 0; i < (recordsLength ?? 0); i += 1) {\n\t\t\t\tlet result: {\n\t\t\t\t\treadonly record?: AgenticMemoryRecord<T>;\n\t\t\t\t\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tif (!Object.hasOwn(value.records, i)) {\n\t\t\t\t\t\tthrow new TypeError(\"proposedRecords.records must be dense\");\n\t\t\t\t\t}\n\t\t\t\t\tresult = validateAndSnapshotRecord<T>(value.records[i], i);\n\t\t\t\t} catch (error) {\n\t\t\t\t\terrors.push(`records[${i}]: record access failed: ${errorMessage(error)}`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (result.record === undefined || result.errors.length > 0) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t...result.errors\n\t\t\t\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t\t\t\t.map((error) => `records[${i}]: ${error}`),\n\t\t\t\t\t);\n\t\t\t\t} else if (seenRecordIds.has(result.record.id)) {\n\t\t\t\t\terrors.push(`records[${i}]: duplicate proposed record id '${result.record.id}'`);\n\t\t\t\t} else {\n\t\t\t\t\tseenRecordIds.add(result.record.id);\n\t\t\t\t\trecords.push(result.record);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (errors.length > 0 || id === undefined || requestId === undefined) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: value.kind === \"proposedRecords\" ? \"invalid-proposed-record\" : \"invalid-outcome\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcome is invalid\",\n\t\t\t\tindex,\n\t\t\t\toutcomeId: id,\n\t\t\t\trequestId,\n\t\t\t\toutcome: value,\n\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t},\n\t\t};\n\t}\n\tif (value.kind === \"failed\") {\n\t\treturn {\n\t\t\toutcome: Object.freeze({\n\t\t\t\tid,\n\t\t\t\trequestId,\n\t\t\t\tkind: \"failed\",\n\t\t\t\tmessage: value.message as string,\n\t\t\t\t...(value.provenance === undefined ? {} : { provenance: value.provenance as string }),\n\t\t\t}),\n\t\t};\n\t}\n\treturn {\n\t\toutcome: Object.freeze({\n\t\t\tid,\n\t\t\trequestId,\n\t\t\tkind: \"proposedRecords\",\n\t\t\trecords: Object.freeze(records),\n\t\t\t...(value.provenance === undefined ? {} : { provenance: value.provenance as string }),\n\t\t}),\n\t};\n}\n\nfunction consolidationErrorFromRecordError(\n\terror: Omit<AgenticMemoryError, \"cursor\">,\n): Omit<AgenticMemoryConsolidationError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n\nfunction consolidationErrorFromRetentionError(\n\terror: Omit<AgenticMemoryRetentionError, \"cursor\">,\n): Omit<AgenticMemoryConsolidationError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n\nfunction packContext(\n\tcontextValue: unknown,\n\ttextsValue: unknown,\n\tpolicyValue: unknown,\n\tevaluation: number,\n): AgenticMemoryContextPackingSnapshot {\n\tconst errors: Omit<AgenticMemoryContextPackingError, \"cursor\">[] = [];\n\tconst context = validatePackingContext(contextValue, errors);\n\tconst texts = validateContextTexts(textsValue, errors);\n\tconst policy = validatePackingPolicy(policyValue, errors);\n\tconst packedEntries: AgenticMemoryPackedContextEntry[] = [];\n\tlet omittedEntries = 0;\n\tlet totalChars = 0;\n\tlet totalCost = 0;\n\tif (context !== undefined && policy !== undefined) {\n\t\tfor (const entry of context.entries) {\n\t\t\tconst textFact = texts.get(entry.fragmentId);\n\t\t\tif (textFact === undefined) {\n\t\t\t\tomittedEntries += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-text\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: missing text projection for context entry\",\n\t\t\t\t\tfragmentId: entry.fragmentId,\n\t\t\t\t\tvalidationErrors: [`missing text for fragment '${entry.fragmentId}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst cost = textFact.cost ?? textFact.text.length;\n\t\t\tconst nextEntries = packedEntries.length + 1;\n\t\t\tconst separatorChars = packedEntries.length === 0 ? 0 : 2;\n\t\t\tconst nextChars = totalChars + separatorChars + textFact.text.length;\n\t\t\tconst nextCost = totalCost + cost;\n\t\t\tconst exceeds =\n\t\t\t\t(policy.maxEntries !== undefined && nextEntries > policy.maxEntries) ||\n\t\t\t\t(policy.maxChars !== undefined && nextChars > policy.maxChars) ||\n\t\t\t\t(policy.maxCost !== undefined && nextCost > policy.maxCost);\n\t\t\tif (exceeds) {\n\t\t\t\tomittedEntries += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst packedEntry: AgenticMemoryPackedContextEntry = Object.freeze({\n\t\t\t\tfragmentId: entry.fragmentId,\n\t\t\t\ttext: textFact.text,\n\t\t\t\tcost,\n\t\t\t\tchars: textFact.text.length,\n\t\t\t\t...(entry.record === undefined ? {} : { record: entry.record }),\n\t\t\t\t...(policy.includeMetadata && textFact.metadata !== undefined\n\t\t\t\t\t? { metadata: textFact.metadata }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tpackedEntries.push(packedEntry);\n\t\t\ttotalChars = nextChars;\n\t\t\ttotalCost = nextCost;\n\t\t}\n\t}\n\tconst cursor: AgenticMemoryContextPackingCursor = Object.freeze({\n\t\tevaluation,\n\t\tinputEntries: context?.entries.length ?? 0,\n\t\tpackedEntries: packedEntries.length,\n\t\tomittedEntries,\n\t\ttotalChars,\n\t\ttotalCost,\n\t});\n\tconst errorFacts = Object.freeze(\n\t\terrors.map((error) =>\n\t\t\tfreezeError({\n\t\t\t\t...error,\n\t\t\t\tcursor,\n\t\t\t}),\n\t\t),\n\t);\n\tconst packedContext: AgenticMemoryPackedContext = Object.freeze({\n\t\tentries: Object.freeze(packedEntries),\n\t\ttext: packedEntries.map((entry) => entry.text).join(\"\\n\\n\"),\n\t\ttotalChars,\n\t\ttotalCost,\n\t\ttruncated: omittedEntries > 0,\n\t});\n\tconst status: AgenticMemoryContextPackingStatus = Object.freeze({\n\t\tstate: agenticStatusState(errorFacts.length, packedEntries.length),\n\t\tcursor,\n\t});\n\treturn Object.freeze({\n\t\tpackedContext,\n\t\tstatus,\n\t\terrors: errorFacts,\n\t\tcursor,\n\t});\n}\n\nfunction validatePackingContext(\n\tvalue: unknown,\n\terrors: Omit<AgenticMemoryContextPackingError, \"cursor\">[],\n): ValidatedPackingContext | undefined {\n\tif (!isPlainRecord(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: context must be an AgenticMemoryContext fact\",\n\t\t\tvalue,\n\t\t});\n\t\treturn undefined;\n\t}\n\tlet entriesValue: unknown;\n\ttry {\n\t\tentriesValue = value.entries;\n\t} catch (error) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: `agenticMemoryContextPackingBundle: context entries access failed: ${errorMessage(error)}`,\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"context entries access failed\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tif (!Array.isArray(entriesValue)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: context must be an AgenticMemoryContext fact\",\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"context.entries must be an array\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tconst length = safeArrayLength(entriesValue);\n\tif (length === undefined) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: context entries length could not be read\",\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"context.entries length could not be read\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tconst entries: AgenticMemoryContextEntry[] = [];\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = entriesValue[i];\n\t\t\tif (!isPlainRecord(raw) || !isNonEmptyString(raw.fragmentId)) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-context\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: context entry is invalid\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: [\"context entry fragmentId must be a non-empty string\"],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst record = validateRecordMetadata(raw.record);\n\t\t\tif (!record.ok) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-context\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: context entry record metadata is invalid\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tfragmentId: raw.fragmentId,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: Object.freeze(record.errors),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tentries.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tfragmentId: raw.fragmentId,\n\t\t\t\t\t...(record.metadata === undefined ? {} : { record: record.metadata }),\n\t\t\t\t}) as AgenticMemoryContextEntry,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-context\",\n\t\t\t\tmessage: `agenticMemoryContextPackingBundle: context entry access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalue: raw,\n\t\t\t\tvalidationErrors: [\"context entry access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\treturn Object.freeze({\n\t\tentries: Object.freeze(entries),\n\t});\n}\n\nfunction validateContextTexts(\n\tvalue: unknown,\n\terrors: Omit<AgenticMemoryContextPackingError, \"cursor\">[],\n): Map<FactId, AgenticMemoryContextText> {\n\tconst out = new Map<FactId, AgenticMemoryContextText>();\n\tif (!Array.isArray(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-texts-input\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: texts input must be an array\",\n\t\t\tvalue,\n\t\t});\n\t\treturn out;\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-texts-input\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: texts input length could not be read\",\n\t\t\tvalue,\n\t\t});\n\t\treturn out;\n\t}\n\tfor (let i = 0; i < length; i += 1) {\n\t\ttry {\n\t\t\tconst raw = value[i];\n\t\t\tconst result = validateContextText(raw, i);\n\t\t\tif (result.error !== undefined) {\n\t\t\t\terrors.push(result.error);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (result.text === undefined) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-text\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: text fact is invalid\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: [\"text validation returned no fact\"],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (out.has(result.text.fragmentId)) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"duplicate-text-fragment-id\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: duplicate text fragment id\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tfragmentId: result.text.fragmentId,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: [`duplicate text fragment id '${result.text.fragmentId}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tout.set(result.text.fragmentId, result.text);\n\t\t} catch (error) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-text\",\n\t\t\t\tmessage: `agenticMemoryContextPackingBundle: text access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalidationErrors: [\"text access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\treturn out;\n}\n\nfunction validateContextText(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly text?: AgenticMemoryContextText;\n\treadonly error?: Omit<AgenticMemoryContextPackingError, \"cursor\">;\n} {\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-text\",\n\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: text fact must be an object\",\n\t\t\t\tindex,\n\t\t\t\tvalue,\n\t\t\t},\n\t\t};\n\t}\n\tconst errors: string[] = [];\n\tif (!isNonEmptyString(value.fragmentId)) errors.push(\"fragmentId must be a non-empty string\");\n\tif (typeof value.text !== \"string\") errors.push(\"text must be a string\");\n\tif (\n\t\tvalue.cost !== undefined &&\n\t\t(typeof value.cost !== \"number\" || !Number.isFinite(value.cost) || value.cost < 0)\n\t) {\n\t\terrors.push(\"cost must be a finite number >= 0\");\n\t}\n\tif (value.metadata !== undefined) {\n\t\ttry {\n\t\t\tif (!isPlainRecord(value.metadata)) {\n\t\t\t\tthrow new TypeError(\"metadata must be a plain object when present\");\n\t\t\t}\n\t\t\tassertStrictJsonValue(value.metadata, \"metadata\");\n\t\t} catch (error) {\n\t\t\terrors.push(errorMessage(error));\n\t\t}\n\t}\n\tif (errors.length > 0) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-text\",\n\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: text fact is invalid\",\n\t\t\t\tindex,\n\t\t\t\tfragmentId: typeof value.fragmentId === \"string\" ? value.fragmentId : undefined,\n\t\t\t\tvalue,\n\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\ttext: Object.freeze({\n\t\t\tfragmentId: value.fragmentId as string,\n\t\t\ttext: value.text as string,\n\t\t\t...(value.cost === undefined ? {} : { cost: value.cost as number }),\n\t\t\t...(value.metadata === undefined\n\t\t\t\t? {}\n\t\t\t\t: { metadata: Object.freeze({ ...(value.metadata as Record<string, StrictJsonValue>) }) }),\n\t\t}),\n\t};\n}\n\nfunction validatePackingPolicy(\n\tvalue: unknown,\n\terrors: Omit<AgenticMemoryContextPackingError, \"cursor\">[],\n): AgenticMemoryContextPackingPolicy | undefined {\n\tif (!isPlainRecord(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-policy\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: policy must be an object\",\n\t\t\tvalue,\n\t\t});\n\t\treturn undefined;\n\t}\n\tconst validation: string[] = [];\n\tlet maxEntries: unknown;\n\tlet maxChars: unknown;\n\tlet maxCost: unknown;\n\tlet includeMetadata: unknown;\n\ttry {\n\t\tmaxEntries = value.maxEntries;\n\t\tmaxChars = value.maxChars;\n\t\tmaxCost = value.maxCost;\n\t\tincludeMetadata = value.includeMetadata;\n\t} catch (error) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-policy\",\n\t\t\tmessage: `agenticMemoryContextPackingBundle: policy access failed: ${errorMessage(error)}`,\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"policy access failed\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tif (\n\t\tmaxEntries !== undefined &&\n\t\t(typeof maxEntries !== \"number\" || !Number.isSafeInteger(maxEntries) || maxEntries < 0)\n\t) {\n\t\tvalidation.push(\"maxEntries must be a safe integer >= 0\");\n\t}\n\tif (\n\t\tmaxChars !== undefined &&\n\t\t(typeof maxChars !== \"number\" || !Number.isSafeInteger(maxChars) || maxChars < 0)\n\t) {\n\t\tvalidation.push(\"maxChars must be a safe integer >= 0\");\n\t}\n\tif (\n\t\tmaxCost !== undefined &&\n\t\t(typeof maxCost !== \"number\" || !Number.isFinite(maxCost) || maxCost < 0)\n\t) {\n\t\tvalidation.push(\"maxCost must be a finite number >= 0\");\n\t}\n\tif (includeMetadata !== undefined && typeof includeMetadata !== \"boolean\") {\n\t\tvalidation.push(\"includeMetadata must be a boolean when present\");\n\t}\n\tif (validation.length > 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-policy\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: policy is invalid\",\n\t\t\tvalue,\n\t\t\tvalidationErrors: Object.freeze(validation),\n\t\t});\n\t\treturn undefined;\n\t}\n\treturn Object.freeze({\n\t\t...(maxEntries === undefined ? {} : { maxEntries: maxEntries as number }),\n\t\t...(maxChars === undefined ? {} : { maxChars: maxChars as number }),\n\t\t...(maxCost === undefined ? {} : { maxCost: maxCost as number }),\n\t\t...(includeMetadata === undefined ? {} : { includeMetadata: includeMetadata as boolean }),\n\t});\n}\n\nfunction validateAndProjectRecords<T>(value: unknown): {\n\treadonly records: AgenticMemoryRecord<T>[];\n\treadonly fragments: MemoryFragment<T>[];\n\treadonly metadataByFragmentId: Record<FactId, AgenticMemoryRecordMetadata>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n\treadonly invalidRecordIndexes: Set<number>;\n} {\n\tconst records: AgenticMemoryRecord<T>[] = [];\n\tconst fragments: MemoryFragment<T>[] = [];\n\tconst metadataByFragmentId = Object.create(null) as Record<FactId, AgenticMemoryRecordMetadata>;\n\tconst errors: Omit<AgenticMemoryError, \"cursor\">[] = [];\n\tconst invalidRecordIndexes = new Set<number>();\n\tconst seenRecordIds = new Set<FactId>();\n\tconst seenFragmentIds = new Set<FactId>();\n\tif (!Array.isArray(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-records-input\",\n\t\t\tmessage: \"agenticMemoryBundle: records input must be an array\",\n\t\t\trecord: value,\n\t\t});\n\t\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-records-input\",\n\t\t\tmessage: \"agenticMemoryBundle: records input length could not be read\",\n\t\t\trecord: value,\n\t\t});\n\t\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n\t}\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = value[i];\n\t\t} catch (error) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-record\",\n\t\t\t\tmessage: `agenticMemoryBundle: record access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalidationErrors: Object.freeze([\"record access failed\"]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst result = validateAndSnapshotRecord<T>(raw, i);\n\t\tif (result.errors.length > 0) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push(...result.errors);\n\t\t\tcontinue;\n\t\t}\n\t\tif (result.record === undefined) continue;\n\t\tif (seenRecordIds.has(result.record.id)) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-record-id\",\n\t\t\t\tmessage: \"agenticMemoryBundle: duplicate record id\",\n\t\t\t\tindex: i,\n\t\t\t\trecordId: result.record.id,\n\t\t\t\trecord: raw,\n\t\t\t\tvalidationErrors: [`duplicate record id '${result.record.id}'`],\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (seenFragmentIds.has(result.record.fragment.id)) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-fragment-id\",\n\t\t\t\tmessage: \"agenticMemoryBundle: duplicate fragment id\",\n\t\t\t\tindex: i,\n\t\t\t\trecordId: result.record.id,\n\t\t\t\tfragmentId: result.record.fragment.id,\n\t\t\t\trecord: raw,\n\t\t\t\tvalidationErrors: [`duplicate fragment id '${result.record.fragment.id}'`],\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseenRecordIds.add(result.record.id);\n\t\tseenFragmentIds.add(result.record.fragment.id);\n\t\trecords.push(result.record);\n\t\tfragments.push(result.record.fragment);\n\t\tmetadataByFragmentId[result.record.fragment.id] = recordMetadata(result.record);\n\t}\n\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n}\n\nfunction validateAndSnapshotRecord<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly record?: AgenticMemoryRecord<T>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n} {\n\ttry {\n\t\treturn validateAndSnapshotRecordInner<T>(value, index);\n\t} catch (error) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-record\",\n\t\t\t\t\tmessage: `agenticMemoryBundle: record access failed: ${errorMessage(error)}`,\n\t\t\t\t\tindex,\n\t\t\t\t\trecord: value,\n\t\t\t\t\tvalidationErrors: Object.freeze([\"record access failed\"]),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n}\n\nfunction validateAndSnapshotRecordInner<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly record?: AgenticMemoryRecord<T>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n} {\n\tconst errors: Omit<AgenticMemoryError, \"cursor\">[] = [];\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-record\",\n\t\t\t\t\tmessage: \"agenticMemoryBundle: record must be an object\",\n\t\t\t\t\tindex,\n\t\t\t\t\trecord: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst record = value as Partial<AgenticMemoryRecord<T>> & Record<string, unknown>;\n\tconst recordId = typeof record.id === \"string\" ? record.id : undefined;\n\tif (recordId === undefined || recordId.length === 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record\",\n\t\t\tmessage: \"agenticMemoryBundle: record.id must be a non-empty string\",\n\t\t\tindex,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"record.id must be a non-empty string\"],\n\t\t});\n\t}\n\tif (!isAgenticMemoryKind(record.kind)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record-kind\",\n\t\t\tmessage: \"agenticMemoryBundle: record.kind is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"kind must be one of working, episodic, semantic, procedural, profile\"],\n\t\t});\n\t}\n\tif (!isAgenticMemoryPersistenceLevel(record.persistenceLevel)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-persistence-level\",\n\t\t\tmessage: \"agenticMemoryBundle: record.persistenceLevel is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\n\t\t\t\t\"persistenceLevel must be one of turn, session, project, longTerm, permanent, archived\",\n\t\t\t],\n\t\t});\n\t}\n\tif (!isAgenticMemoryArtifactKind(record.artifactKind)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-artifact-kind\",\n\t\t\tmessage: \"agenticMemoryBundle: record.artifactKind is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"artifactKind must be one of raw, insight, profile, procedure\"],\n\t\t});\n\t}\n\tconst scopeValidation = validateScope(record.scope);\n\tif (!scopeValidation.ok) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-scope\",\n\t\t\tmessage: \"agenticMemoryBundle: record.scope is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze(scopeValidation.errors),\n\t\t});\n\t}\n\tconst fragmentValidation = validateMemoryFragment(record.fragment);\n\tif (!fragmentValidation.ok) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-fragment\",\n\t\t\tmessage: \"agenticMemoryBundle: record.fragment is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\tfragmentId:\n\t\t\t\ttypeof record.fragment === \"object\" &&\n\t\t\t\trecord.fragment !== null &&\n\t\t\t\ttypeof (record.fragment as Partial<MemoryFragment>).id === \"string\"\n\t\t\t\t\t? (record.fragment as Partial<MemoryFragment>).id\n\t\t\t\t\t: undefined,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze([...fragmentValidation.errors]),\n\t\t});\n\t}\n\tconst forbiddenFields = [\n\t\t\"storageTier\",\n\t\t\"storageKey\",\n\t\t\"adapter\",\n\t\t\"collection\",\n\t\t\"collections\",\n\t\t\"ttl\",\n\t\t\"ttlMs\",\n\t\t\"ttlNs\",\n\t\t\"expiresAt\",\n\t\t\"timer\",\n\t\t\"scheduler\",\n\t\t\"schedule\",\n\t\t\"retentionTimer\",\n\t\t\"consolidationSchedule\",\n\t\t\"reflectionSchedule\",\n\t\t\"llm\",\n\t\t\"llmHandle\",\n\t\t\"tool\",\n\t\t\"toolHandle\",\n\t\t\"runner\",\n\t\t\"runnerHandle\",\n\t\t\"restore\",\n\t\t\"hydrate\",\n\t\t\"hydration\",\n\t\t\"graphMutation\",\n\t\t\"protocol\",\n\t] as const;\n\tconst presentForbidden = forbiddenFields.filter((field) => Object.hasOwn(record, field));\n\tif (presentForbidden.length > 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record\",\n\t\t\tmessage: \"agenticMemoryBundle: record contains forbidden runtime/persistence fields\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze(\n\t\t\t\tpresentForbidden.map((field) => `${field} is not part of AgenticMemoryRecord`),\n\t\t\t),\n\t\t});\n\t}\n\tif (errors.length > 0) return { errors };\n\tconst scope = scopeValidation.scope;\n\tconst fragment = snapshotFragment(record.fragment as MemoryFragment<T>);\n\treturn {\n\t\trecord: Object.freeze({\n\t\t\tid: recordId as FactId,\n\t\t\tkind: record.kind as AgenticMemoryKind,\n\t\t\tpersistenceLevel: record.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\tartifactKind: record.artifactKind as AgenticMemoryArtifactKind,\n\t\t\t...(scope === undefined ? {} : { scope }),\n\t\t\tfragment,\n\t\t}),\n\t\terrors,\n\t};\n}\n\nfunction snapshotFragment<T>(fragment: MemoryFragment<T>): MemoryFragment<T> {\n\treturn Object.freeze({\n\t\tid: fragment.id,\n\t\tpayload: fragment.payload,\n\t\ttNs: fragment.tNs,\n\t\t...(fragment.validFrom === undefined ? {} : { validFrom: fragment.validFrom }),\n\t\t...(fragment.validTo === undefined ? {} : { validTo: fragment.validTo }),\n\t\tconfidence: fragment.confidence,\n\t\ttags: Object.freeze([...fragment.tags]),\n\t\tsources: Object.freeze([...fragment.sources]),\n\t\t...(fragment.embedding === undefined\n\t\t\t? {}\n\t\t\t: { embedding: Object.freeze([...fragment.embedding]) }),\n\t\t...(fragment.parentFragmentId === undefined\n\t\t\t? {}\n\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t});\n}\n\nfunction recordMetadata(record: AgenticMemoryRecord): AgenticMemoryRecordMetadata {\n\treturn Object.freeze({\n\t\trecordId: record.id,\n\t\tkind: record.kind,\n\t\tpersistenceLevel: record.persistenceLevel,\n\t\tartifactKind: record.artifactKind,\n\t\t...(record.scope === undefined ? {} : { scope: record.scope }),\n\t});\n}\n\nfunction validateRecordMetadata(value: unknown): {\n\treadonly ok: boolean;\n\treadonly metadata?: AgenticMemoryRecordMetadata;\n\treadonly errors: readonly string[];\n} {\n\tif (value === undefined) return { ok: true, errors: [] };\n\tif (!isPlainRecord(value)) {\n\t\treturn { ok: false, errors: [\"record metadata must be an object when present\"] };\n\t}\n\tconst errors: string[] = [];\n\tfor (const key of Object.keys(value)) {\n\t\tif (\n\t\t\tkey !== \"recordId\" &&\n\t\t\tkey !== \"kind\" &&\n\t\t\tkey !== \"persistenceLevel\" &&\n\t\t\tkey !== \"artifactKind\" &&\n\t\t\tkey !== \"scope\"\n\t\t) {\n\t\t\terrors.push(`record.${key} is not part of AgenticMemoryRecordMetadata`);\n\t\t}\n\t}\n\tif (!isNonEmptyString(value.recordId)) {\n\t\terrors.push(\"record.recordId must be a non-empty string\");\n\t}\n\tif (!isAgenticMemoryKind(value.kind)) {\n\t\terrors.push(\"record.kind is invalid\");\n\t}\n\tif (!isAgenticMemoryPersistenceLevel(value.persistenceLevel)) {\n\t\terrors.push(\"record.persistenceLevel is invalid\");\n\t}\n\tif (!isAgenticMemoryArtifactKind(value.artifactKind)) {\n\t\terrors.push(\"record.artifactKind is invalid\");\n\t}\n\tconst scopeValidation = validateScope(value.scope);\n\tif (!scopeValidation.ok) {\n\t\terrors.push(...scopeValidation.errors.map((error) => `record.${error}`));\n\t}\n\tif (errors.length > 0) return { ok: false, errors };\n\treturn {\n\t\tok: true,\n\t\terrors,\n\t\tmetadata: Object.freeze({\n\t\t\trecordId: value.recordId as FactId,\n\t\t\tkind: value.kind as AgenticMemoryKind,\n\t\t\tpersistenceLevel: value.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\tartifactKind: value.artifactKind as AgenticMemoryArtifactKind,\n\t\t\t...(scopeValidation.scope === undefined ? {} : { scope: scopeValidation.scope }),\n\t\t}),\n\t};\n}\n\nfunction contextState(\n\tprojection: AgenticMemoryStatusState,\n\tretrieval: MemoryRetrievalStatus[\"state\"],\n): AgenticMemoryContextState {\n\tif (projection === \"error\" || retrieval === \"error\") return \"error\";\n\tif (projection === \"partial\" || retrieval === \"partial\") return \"partial\";\n\treturn retrieval;\n}\n\nfunction agenticStatusState(errorCount: number, validRecords: number): AgenticMemoryStatusState {\n\tif (errorCount > 0 && validRecords === 0) return \"error\";\n\tif (errorCount > 0) return \"partial\";\n\treturn validRecords > 0 ? \"ready\" : \"empty\";\n}\n\nfunction isAgenticMemoryKind(value: unknown): value is AgenticMemoryKind {\n\treturn (\n\t\tvalue === \"working\" ||\n\t\tvalue === \"episodic\" ||\n\t\tvalue === \"semantic\" ||\n\t\tvalue === \"procedural\" ||\n\t\tvalue === \"profile\"\n\t);\n}\n\nfunction isAgenticMemoryPersistenceLevel(value: unknown): value is AgenticMemoryPersistenceLevel {\n\treturn (\n\t\tvalue === \"turn\" ||\n\t\tvalue === \"session\" ||\n\t\tvalue === \"project\" ||\n\t\tvalue === \"longTerm\" ||\n\t\tvalue === \"permanent\" ||\n\t\tvalue === \"archived\"\n\t);\n}\n\nfunction isAgenticMemoryArtifactKind(value: unknown): value is AgenticMemoryArtifactKind {\n\treturn value === \"raw\" || value === \"insight\" || value === \"profile\" || value === \"procedure\";\n}\n\nfunction validateScope(value: unknown): {\n\treadonly ok: boolean;\n\treadonly scope?: AgenticMemoryScope;\n\treadonly errors: readonly string[];\n} {\n\tif (value === undefined) return { ok: true, errors: [] };\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn { ok: false, errors: [\"scope must be an object when present\"] };\n\t}\n\tconst scope = value as Record<string, unknown>;\n\tconst errors: string[] = [];\n\tconst allowed = new Set([\"sessionId\", \"projectId\", \"userId\", \"tenantId\"]);\n\tfor (const key of Object.keys(scope)) {\n\t\tif (!allowed.has(key)) errors.push(`scope.${key} is not part of AgenticMemoryScope`);\n\t}\n\tfor (const key of allowed) {\n\t\tif (scope[key] !== undefined && (typeof scope[key] !== \"string\" || scope[key].length === 0)) {\n\t\t\terrors.push(`scope.${key} must be a non-empty string when present`);\n\t\t}\n\t}\n\tif (errors.length > 0) return { ok: false, errors };\n\treturn {\n\t\tok: true,\n\t\terrors,\n\t\tscope: Object.freeze({\n\t\t\t...(scope.sessionId === undefined ? {} : { sessionId: scope.sessionId as string }),\n\t\t\t...(scope.projectId === undefined ? {} : { projectId: scope.projectId as string }),\n\t\t\t...(scope.userId === undefined ? {} : { userId: scope.userId as string }),\n\t\t\t...(scope.tenantId === undefined ? {} : { tenantId: scope.tenantId as string }),\n\t\t}),\n\t};\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction ownKeys(value: Record<string, unknown>): readonly string[] {\n\treturn Object.keys(value).sort();\n}\n\nfunction assertExactKeys(\n\tvalue: Record<string, unknown>,\n\texpected: readonly string[],\n\tlabel: string,\n): void {\n\tconst actual = ownKeys(value);\n\tconst want = [...expected].sort();\n\tif (actual.length !== want.length || actual.some((key, i) => key !== want[i])) {\n\t\tthrow new TypeError(`${label}: unexpected fields ${actual.join(\",\")}`);\n\t}\n}\n\nfunction assertAgenticMemoryRecordCodecShape(value: unknown): void {\n\tif (!isPlainRecord(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: record must be an object\");\n\t}\n\tassertNoSymbolKeys(value, \"agenticMemoryRecordFrame.record\");\n\tassertExactKeys(\n\t\tvalue,\n\t\tvalue.scope === undefined\n\t\t\t? [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\"]\n\t\t\t: [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\", \"scope\"],\n\t\t\"agenticMemoryRecordFrame.record\",\n\t);\n\tconst fragment = value.fragment;\n\tif (!isPlainRecord(fragment)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: fragment must be an object\");\n\t}\n\tassertNoSymbolKeys(fragment, \"agenticMemoryRecordFrame.record.fragment\");\n\tassertExactKeys(\n\t\tfragment,\n\t\t[\n\t\t\t\"id\",\n\t\t\t\"payload\",\n\t\t\t\"tNs\",\n\t\t\t...(fragment.validFrom === undefined ? [] : [\"validFrom\"]),\n\t\t\t...(fragment.validTo === undefined ? [] : [\"validTo\"]),\n\t\t\t\"confidence\",\n\t\t\t\"tags\",\n\t\t\t\"sources\",\n\t\t\t...(fragment.embedding === undefined ? [] : [\"embedding\"]),\n\t\t\t...(fragment.parentFragmentId === undefined ? [] : [\"parentFragmentId\"]),\n\t\t\t...(fragment.provenance === undefined ? [] : [\"provenance\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.fragment\",\n\t);\n\tassertStrictJsonValue(fragment.tags, \"record.fragment.tags\");\n\tassertStrictJsonValue(fragment.sources, \"record.fragment.sources\");\n\tif (fragment.embedding !== undefined) {\n\t\tassertStrictJsonValue(fragment.embedding, \"record.fragment.embedding\");\n\t}\n\tif (value.scope !== undefined) assertScopeFrame(value.scope);\n}\n\nfunction assertNoSymbolKeys(value: object, label: string): void {\n\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\tthrow new TypeError(`${label}: unexpected symbol fields`);\n\t}\n}\n\nfunction decimalBigIntString(value: bigint, label: string): string {\n\tconst out = value.toString(10);\n\tif (!/^-?(0|[1-9]\\d*)$/.test(out)) {\n\t\tthrow new TypeError(`${label} must encode as a canonical decimal bigint string`);\n\t}\n\treturn out;\n}\n\nfunction parseDecimalBigInt(value: unknown, label: string): bigint {\n\tif (typeof value !== \"string\" || !/^(0|-?[1-9]\\d*)$/.test(value)) {\n\t\tthrow new TypeError(`${label} must be a canonical decimal bigint string`);\n\t}\n\treturn BigInt(value);\n}\n\nfunction assertStrictJsonValue(value: unknown, label: string): StrictJsonValue {\n\ttry {\n\t\tstrictJsonCodec.encode(value);\n\t\treturn value as StrictJsonValue;\n\t} catch (error) {\n\t\tthrow new TypeError(`${label} must be strict JSON: ${errorMessage(error)}`);\n\t}\n}\n\nfunction assertScopeFrame(value: unknown): AgenticMemoryScope {\n\tif (!isPlainRecord(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: scope must be an object when present\");\n\t}\n\tassertStrictJsonValue(value, \"record.scope\");\n\tconst validation = validateScope(value);\n\tif (!validation.ok || validation.scope === undefined) {\n\t\tthrow new TypeError(`agenticMemoryRecordFrame: invalid scope: ${validation.errors.join(\"; \")}`);\n\t}\n\tassertExactKeys(\n\t\tvalue as Record<string, unknown>,\n\t\t[\n\t\t\t...((value as Record<string, unknown>).sessionId === undefined ? [] : [\"sessionId\"]),\n\t\t\t...((value as Record<string, unknown>).projectId === undefined ? [] : [\"projectId\"]),\n\t\t\t...((value as Record<string, unknown>).userId === undefined ? [] : [\"userId\"]),\n\t\t\t...((value as Record<string, unknown>).tenantId === undefined ? [] : [\"tenantId\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.scope\",\n\t);\n\treturn validation.scope;\n}\n\nfunction assertKindValue(value: unknown): AgenticMemoryKind {\n\tif (!isAgenticMemoryKind(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid memory kind\");\n\t}\n\treturn value;\n}\n\nfunction assertPersistenceLevelValue(value: unknown): AgenticMemoryPersistenceLevel {\n\tif (!isAgenticMemoryPersistenceLevel(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid persistence level\");\n\t}\n\treturn value;\n}\n\nfunction assertArtifactKindValue(value: unknown): AgenticMemoryArtifactKind {\n\tif (!isAgenticMemoryArtifactKind(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid artifact kind\");\n\t}\n\treturn value;\n}\n\nfunction assertNonEmptyString(value: unknown, label: string): string {\n\tif (!isNonEmptyString(value)) throw new TypeError(`${label} must be a non-empty string`);\n\treturn value;\n}\n\nfunction assertString(value: unknown, label: string): string {\n\tif (typeof value !== \"string\") throw new TypeError(`${label} must be a string`);\n\treturn value;\n}\n\nfunction assertConfidence(value: unknown, label: string): number {\n\tif (!Number.isFinite(value) || (value as number) < 0 || (value as number) > 1) {\n\t\tthrow new TypeError(`${label} must be a finite number in [0, 1]`);\n\t}\n\treturn value as number;\n}\n\nfunction assertStringArray(value: unknown, label: string): readonly string[] {\n\tif (!isDenseArrayOf(value, (item): item is string => typeof item === \"string\")) {\n\t\tthrow new TypeError(`${label} must be a readonly string array`);\n\t}\n\treturn Object.freeze([...value]);\n}\n\nfunction assertFiniteNumberArray(value: unknown, label: string): readonly number[] {\n\tif (!isDenseArrayOf(value, (item): item is number => Number.isFinite(item))) {\n\t\tthrow new TypeError(`${label} must be a finite number array`);\n\t}\n\treturn Object.freeze([...value]);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0;\n}\n\nfunction isDenseArrayOf<T>(value: unknown, predicate: (item: unknown) => item is T): value is T[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !predicate(value[i])) return false;\n\t}\n\treturn true;\n}\n\nfunction freezeError<T extends { readonly validationErrors?: readonly string[] }>(error: T): T {\n\treturn Object.freeze({\n\t\t...error,\n\t\t...(error.validationErrors === undefined\n\t\t\t? {}\n\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t}) as T;\n}\n\nfunction safeArrayLength(value: readonly unknown[]): number | undefined {\n\ttry {\n\t\treturn value.length;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCO,IAAM,WAAW;;;ACXjB,IAAM,gBAA+B,uBAAO,yBAAyB;AAoIrE,SAAS,SAAS,KAAU,UAAmD;AACrF,SAAO,IAAI,SAAS,QAAQ,KAAK,CAAC;AACnC;AAGO,SAAS,SAAS,KAAU,UAA6C;AAC/E,QAAM,QAAQ,SAAS,KAAK,QAAQ;AACpC,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,QAAM,YAAY,MAAM,KAAK,EAAE,OAAO,CAAC,MAAM,MAAM,QAAQ;AAC3D,SAAO,UAAU,WAAW,IAAI,CAAC,IAAI;AACtC;AAGO,SAAS,UAAU,KAAU,UAA2B;AAC9D,SAAO,IAAI,aAAa,GAAG,OAAO,QAAQ;AAC3C;;;ACtJA,IAAM,uBAAuB,KAAK;AAElC,SAAS,uBAAuB,OAAe,MAAoB;AAClE,MAAI,CAAC,OAAO,SAAS,KAAK,GAAG;AAC5B,UAAM,IAAI,UAAU,0CAA0C,IAAI,EAAE;AAAA,EACrE;AACD;AAEA,SAAS,uBAAuB,OAAe,MAAoB;AAClE,yBAAuB,OAAO,IAAI;AAClC,MAAI,OAAO,GAAG,OAAO,EAAE,GAAG;AACzB,UAAM,IAAI,UAAU,6CAA6C,IAAI,EAAE;AAAA,EACxE;AACA,QAAM,MAAM,KAAK,IAAI,KAAK;AAC1B,MAAI,MAAM,KAAK,MAAM,sBAAsB;AAC1C,UAAM,I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AAM,UAAU,OAAO,KAAK;AAC7D;","names":["out","compareBigIntDesc","isDenseArrayOf","compareBigIntDesc","safeArrayLength","errorMessage","isDenseArrayOf","resultId","snapshotFragment"]}