@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/patterns/index.ts","../../src/patterns/inspection.ts","../../src/patterns/semantic-memory.ts","../../src/protocol/messages.ts","../../src/ctx/types.ts","../../src/patterns/semantic-memory-graph.ts"],"sourcesContent":["/**\n * Horizontal reusable graph patterns.\n *\n * Former preset material lands here only when it is not a vertical solution\n * and has been re-derived onto clean-slate APIs.\n */\n\nexport {\n\ttype ProfileSummary,\n\ttype ProfileSummaryNode,\n\tprofileSummary,\n} from \"./inspection.js\";\nexport {\n\ttype AdmissionFilter,\n\ttype AdmissionScore3DOptions,\n\ttype AdmissionScoredOptions,\n\ttype AdmissionScores,\n\ttype AdmissionThresholds,\n\tadmissionFilter3D,\n\tadmissionScored,\n\ttype CollectionEntry,\n\ttype CollectionScoreFn,\n\tcosineSimilarity,\n\ttype DecayPolicy,\n\ttype FactId,\n\ttype FactStore,\n\tfilterMemoryFragments,\n\tisMemoryFragment,\n\ttype KnowledgeAssertion,\n\ttype KnowledgeAssertionObject,\n\ttype KnowledgeAssertionStrictJsonValue,\n\ttype KnowledgeAssertionSubject,\n\ttype MemoryAnswer,\n\ttype MemoryFragment,\n\ttype MemoryFragmentValidation,\n\ttype MemoryQuery,\n\tmemoryFragmentMatchesQuery,\n\tmemoryFragmentValidAt,\n\ttype OutcomeSignal,\n\ttype RankedCollectionEntry,\n\ttype RetrievalEntry,\n\ttype RetrievalQuery,\n\ttype RetrievalTrace,\n\ttype ScoringPolicy,\n\ttype ShardByTenantConfig,\n\ttype ShardByTenantOptions,\n\ttype ShardKey,\n\ttype StoreReadHandle,\n\tshardByTenant,\n\ttype VectorSearchResult,\n\tvalidateMemoryFragment,\n} from \"./semantic-memory.js\";\nexport {\n\ttype KnowledgeGraphCursor,\n\ttype KnowledgeGraphEntity,\n\ttype KnowledgeGraphError,\n\ttype KnowledgeGraphErrorCode,\n\ttype KnowledgeGraphIndex,\n\ttype KnowledgeGraphPolicy,\n\ttype KnowledgeGraphReducerBundle,\n\ttype KnowledgeGraphReducerBundleOptions,\n\ttype KnowledgeGraphRelation,\n\ttype KnowledgeGraphSnapshot,\n\ttype KnowledgeGraphStatus,\n\ttype KnowledgeGraphStatusState,\n\ttype KnowledgeGraphTopic,\n\tknowledgeGraphReducerBundle,\n\ttype MemoryRetrievalBundle,\n\ttype MemoryRetrievalBundleOptions,\n\ttype MemoryRetrievalCursor,\n\ttype MemoryRetrievalError,\n\ttype MemoryRetrievalErrorCode,\n\ttype MemoryRetrievalFact,\n\ttype MemoryRetrievalIndex,\n\ttype MemoryRetrievalQuery,\n\ttype MemoryRetrievalSnapshot,\n\ttype MemoryRetrievalStatus,\n\ttype MemoryRetrievalStatusState,\n\tmemoryRetrievalBundle,\n} from \"./semantic-memory-graph.js\";\n","/**\n * Horizontal inspection patterns re-derived from old presets (B62 / D125).\n *\n * These helpers compose the clean-slate graph inspection egresses. They do not\n * add graph nodes, hidden subscriptions, policy gates, or storage ownership.\n */\n\nimport type { Graph } from \"../graph/graph.js\";\nimport type { NodeProfile } from \"../graph/inspect.js\";\n\nexport interface ProfileSummaryNode {\n\tpath: string;\n\tinvokes: number;\n\ttotalDurationNs: number;\n\tlastDurationNs: number;\n\tstatus: NodeProfile[\"status\"];\n}\n\nexport interface ProfileSummary {\n\t/** Number of nodes in describe(), including nodes with zero invokes. */\n\tnodeCount: number;\n\ttotalInvokes: number;\n\tbyStatus: Partial<Record<NodeProfile[\"status\"], number>>;\n\t/** Nodes sorted by invokes desc, then path asc. */\n\thotNodes: ProfileSummaryNode[];\n}\n\n/**\n * Summarize an opt-in Graph.profile() snapshot while keeping describe() as the\n * source of node cardinality. No counters are stored on nodes (R-profile).\n */\nexport function profileSummary(graph: Graph, opts: { limit?: number } = {}): ProfileSummary {\n\tconst profile = graph.profile();\n\tconst described = graph.describe();\n\tconst nodeIds = new Set(described.nodes.map((node) => node.id));\n\tfor (const id of Object.keys(profile.nodes)) nodeIds.add(id);\n\n\tconst byStatus: Partial<Record<NodeProfile[\"status\"], number>> = {};\n\tconst hotNodes: ProfileSummaryNode[] = [];\n\tfor (const path of [...nodeIds].sort()) {\n\t\tconst nodeProfile = profile.nodes[path];\n\t\tif (nodeProfile === undefined) continue;\n\t\tbyStatus[nodeProfile.status] = (byStatus[nodeProfile.status] ?? 0) + 1;\n\t\thotNodes.push({\n\t\t\tpath,\n\t\t\tinvokes: nodeProfile.invokes,\n\t\t\ttotalDurationNs: nodeProfile.totalDurationNs,\n\t\t\tlastDurationNs: nodeProfile.lastDurationNs,\n\t\t\tstatus: nodeProfile.status,\n\t\t});\n\t}\n\thotNodes.sort((a, b) => b.invokes - a.invokes || a.path.localeCompare(b.path));\n\treturn {\n\t\tnodeCount: nodeIds.size,\n\t\ttotalInvokes: profile.totalInvokes,\n\t\tbyStatus,\n\t\thotNodes: hotNodes.slice(0, opts.limit ?? hotNodes.length),\n\t};\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 * 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 * 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC+BO,SAAS,eAAe,OAAc,OAA2B,CAAC,GAAmB;AAC3F,QAAM,UAAU,MAAM,QAAQ;AAC9B,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,UAAU,IAAI,IAAI,UAAU,MAAM,IAAI,CAAC,SAAS,KAAK,EAAE,CAAC;AAC9D,aAAW,MAAM,OAAO,KAAK,QAAQ,KAAK,EAAG,SAAQ,IAAI,EAAE;AAE3D,QAAM,WAA2D,CAAC;AAClE,QAAM,WAAiC,CAAC;AACxC,aAAW,QAAQ,CAAC,GAAG,OAAO,EAAE,KAAK,GAAG;AACvC,UAAM,cAAc,QAAQ,MAAM,IAAI;AACtC,QAAI,gBAAgB,OAAW;AAC/B,aAAS,YAAY,MAAM,KAAK,SAAS,YAAY,MAAM,KAAK,KAAK;AACrE,aAAS,KAAK;AAAA,MACb;AAAA,MACA,SAAS,YAAY;AAAA,MACrB,iBAAiB,YAAY;AAAA,MAC7B,gBAAgB,Y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AAO,UAAU,YAAY,MAAM,SAAS;AACpD;AAEA,SAAS,aAAa,OAAwB;AAC7C,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC7D;AAEA,SAAS,cAAc,GAAW,GAAmB;AACpD,SAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI;AACjC;AAEA,SAASC,mBAAkB,GAAW,GAAmB;AACxD,MAAI,MAAM,EAAG,QAAO;AACpB,SAAO,IAAI,IAAI,KAAK;AACrB;","names":["isDenseArrayOf","compareBigIntDesc"]}
@@ -0,0 +1,39 @@
1
+ import { N as NodeProfile, d as Graph } from '../graph-s23RbbFO.cjs';
2
+ export { A as AdmissionFilter, r as AdmissionScore3DOptions, s as AdmissionScoredOptions, t as AdmissionScores, u as AdmissionThresholds, C as CollectionEntry, v as CollectionScoreFn, D as DecayPolicy, F as FactId, w as FactStore, K as KnowledgeAssertion, a as KnowledgeAssertionObject, b as KnowledgeAssertionStrictJsonValue, c as KnowledgeAssertionSubject, d as KnowledgeGraphCursor, e as KnowledgeGraphEntity, f as KnowledgeGraphError, g as KnowledgeGraphErrorCode, h as KnowledgeGraphIndex, i as KnowledgeGraphPolicy, j as KnowledgeGraphReducerBundle, k as KnowledgeGraphReducerBundleOptions, l as KnowledgeGraphRelation, m as KnowledgeGraphSnapshot, n as KnowledgeGraphStatus, o as KnowledgeGraphStatusState, p as KnowledgeGraphTopic, M as MemoryAnswer, x as MemoryFragment, y as MemoryFragmentValidation, z as MemoryQuery, B as MemoryRetrievalBundle, E as MemoryRetrievalBundleOptions, G as MemoryRetrievalCursor, H as MemoryRetrievalError, I as MemoryRetrievalErrorCode, J as MemoryRetrievalFact, L as MemoryRetrievalIndex, N as MemoryRetrievalQuery, O as MemoryRetrievalSnapshot, P as MemoryRetrievalStatus, Q as MemoryRetrievalStatusState, R as OutcomeSignal, S as RankedCollectionEntry, T as RetrievalEntry, U as RetrievalQuery, V as RetrievalTrace, W as ScoringPolicy, X as ShardByTenantConfig, Y as ShardByTenantOptions, Z as ShardKey, _ as StoreReadHandle, $ as VectorSearchResult, a0 as admissionFilter3D, a1 as admissionScored, a2 as cosineSimilarity, a3 as filterMemoryFragments, a4 as isMemoryFragment, q as knowledgeGraphReducerBundle, a5 as memoryFragmentMatchesQuery, a6 as memoryFragmentValidAt, a7 as memoryRetrievalBundle, a8 as shardByTenant, a9 as validateMemoryFragment } from '../semantic-memory-graph-BYoIlP35.cjs';
3
+ import '../core/index.cjs';
4
+ import '../types-bNMSWKqF.cjs';
5
+ import '../messages-BZqrGGm1.cjs';
6
+ import '../codec-BB7p8fJc.cjs';
7
+ import '../describe-Ciu8SUnN.cjs';
8
+
9
+ /**
10
+ * Horizontal inspection patterns re-derived from old presets (B62 / D125).
11
+ *
12
+ * These helpers compose the clean-slate graph inspection egresses. They do not
13
+ * add graph nodes, hidden subscriptions, policy gates, or storage ownership.
14
+ */
15
+
16
+ interface ProfileSummaryNode {
17
+ path: string;
18
+ invokes: number;
19
+ totalDurationNs: number;
20
+ lastDurationNs: number;
21
+ status: NodeProfile["status"];
22
+ }
23
+ interface ProfileSummary {
24
+ /** Number of nodes in describe(), including nodes with zero invokes. */
25
+ nodeCount: number;
26
+ totalInvokes: number;
27
+ byStatus: Partial<Record<NodeProfile["status"], number>>;
28
+ /** Nodes sorted by invokes desc, then path asc. */
29
+ hotNodes: ProfileSummaryNode[];
30
+ }
31
+ /**
32
+ * Summarize an opt-in Graph.profile() snapshot while keeping describe() as the
33
+ * source of node cardinality. No counters are stored on nodes (R-profile).
34
+ */
35
+ declare function profileSummary(graph: Graph, opts?: {
36
+ limit?: number;
37
+ }): ProfileSummary;
38
+
39
+ export { type ProfileSummary, type ProfileSummaryNode, profileSummary };
@@ -0,0 +1,39 @@
1
+ import { N as NodeProfile, d as Graph } from '../graph-DfdF9zy4.js';
2
+ export { A as AdmissionFilter, r as AdmissionScore3DOptions, s as AdmissionScoredOptions, t as AdmissionScores, u as AdmissionThresholds, C as CollectionEntry, v as CollectionScoreFn, D as DecayPolicy, F as FactId, w as FactStore, K as KnowledgeAssertion, a as KnowledgeAssertionObject, b as KnowledgeAssertionStrictJsonValue, c as KnowledgeAssertionSubject, d as KnowledgeGraphCursor, e as KnowledgeGraphEntity, f as KnowledgeGraphError, g as KnowledgeGraphErrorCode, h as KnowledgeGraphIndex, i as KnowledgeGraphPolicy, j as KnowledgeGraphReducerBundle, k as KnowledgeGraphReducerBundleOptions, l as KnowledgeGraphRelation, m as KnowledgeGraphSnapshot, n as KnowledgeGraphStatus, o as KnowledgeGraphStatusState, p as KnowledgeGraphTopic, M as MemoryAnswer, x as MemoryFragment, y as MemoryFragmentValidation, z as MemoryQuery, B as MemoryRetrievalBundle, E as MemoryRetrievalBundleOptions, G as MemoryRetrievalCursor, H as MemoryRetrievalError, I as MemoryRetrievalErrorCode, J as MemoryRetrievalFact, L as MemoryRetrievalIndex, N as MemoryRetrievalQuery, O as MemoryRetrievalSnapshot, P as MemoryRetrievalStatus, Q as MemoryRetrievalStatusState, R as OutcomeSignal, S as RankedCollectionEntry, T as RetrievalEntry, U as RetrievalQuery, V as RetrievalTrace, W as ScoringPolicy, X as ShardByTenantConfig, Y as ShardByTenantOptions, Z as ShardKey, _ as StoreReadHandle, $ as VectorSearchResult, a0 as admissionFilter3D, a1 as admissionScored, a2 as cosineSimilarity, a3 as filterMemoryFragments, a4 as isMemoryFragment, q as knowledgeGraphReducerBundle, a5 as memoryFragmentMatchesQuery, a6 as memoryFragmentValidAt, a7 as memoryRetrievalBundle, a8 as shardByTenant, a9 as validateMemoryFragment } from '../semantic-memory-graph-CxyXLms3.js';
3
+ import '../core/index.js';
4
+ import '../types-h12mNYbq.js';
5
+ import '../messages-BZqrGGm1.js';
6
+ import '../codec-BB7p8fJc.js';
7
+ import '../describe-BZb7AS2y.js';
8
+
9
+ /**
10
+ * Horizontal inspection patterns re-derived from old presets (B62 / D125).
11
+ *
12
+ * These helpers compose the clean-slate graph inspection egresses. They do not
13
+ * add graph nodes, hidden subscriptions, policy gates, or storage ownership.
14
+ */
15
+
16
+ interface ProfileSummaryNode {
17
+ path: string;
18
+ invokes: number;
19
+ totalDurationNs: number;
20
+ lastDurationNs: number;
21
+ status: NodeProfile["status"];
22
+ }
23
+ interface ProfileSummary {
24
+ /** Number of nodes in describe(), including nodes with zero invokes. */
25
+ nodeCount: number;
26
+ totalInvokes: number;
27
+ byStatus: Partial<Record<NodeProfile["status"], number>>;
28
+ /** Nodes sorted by invokes desc, then path asc. */
29
+ hotNodes: ProfileSummaryNode[];
30
+ }
31
+ /**
32
+ * Summarize an opt-in Graph.profile() snapshot while keeping describe() as the
33
+ * source of node cardinality. No counters are stored on nodes (R-profile).
34
+ */
35
+ declare function profileSummary(graph: Graph, opts?: {
36
+ limit?: number;
37
+ }): ProfileSummary;
38
+
39
+ export { type ProfileSummary, type ProfileSummaryNode, profileSummary };
@@ -0,0 +1,33 @@
1
+ import {
2
+ profileSummary
3
+ } from "../chunk-SCRFRCGR.js";
4
+ import {
5
+ admissionFilter3D,
6
+ admissionScored,
7
+ cosineSimilarity,
8
+ filterMemoryFragments,
9
+ isMemoryFragment,
10
+ knowledgeGraphReducerBundle,
11
+ memoryFragmentMatchesQuery,
12
+ memoryFragmentValidAt,
13
+ memoryRetrievalBundle,
14
+ shardByTenant,
15
+ validateMemoryFragment
16
+ } from "../chunk-JIMUDQN3.js";
17
+ import "../chunk-SWTLEQL6.js";
18
+ import "../chunk-DK554R7P.js";
19
+ export {
20
+ admissionFilter3D,
21
+ admissionScored,
22
+ cosineSimilarity,
23
+ filterMemoryFragments,
24
+ isMemoryFragment,
25
+ knowledgeGraphReducerBundle,
26
+ memoryFragmentMatchesQuery,
27
+ memoryFragmentValidAt,
28
+ memoryRetrievalBundle,
29
+ profileSummary,
30
+ shardByTenant,
31
+ validateMemoryFragment
32
+ };
33
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}