@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/semantic-memory.ts","../src/patterns/semantic-memory-graph.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;AAiMO,SAAS,iBAAiB,GAAsB,GAA8B;AACpF,QAAM,IAAI,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM;AACrC,MAAI,MAAM;AACV,MAAI,KAAK;AACT,MAAI,KAAK;AACT,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG;AAC9B,UAAM,KAAK,EAAE,CAAC,KAAK;AACnB,UAAM,KAAK,EAAE,CAAC,KAAK;AACnB,WAAO,KAAK;AACZ,UAAM,KAAK;AACX,UAAM,KAAK;AAAA,EACZ;AACA,MAAI,OAAO,KAAK,OAAO,EAAG,QAAO;AACjC,QAAM,QAAQ,MAAM,KAAK,KAAK,KAAK,EAAE;AACrC,SAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AACzC;AAQO,SAAS,sBAAsB,UAA0B,MAAwB;AACvF,MAAI,SAAS,OAAW,QAAO,SAAS,YAAY,UAAa,SAAS,cAAc;AACxF,MAAI,SAAS,cAAc,UAAa,SAAS,YAAY,KAAM,QAAO;AAC1E,MAAI,SAAS,YAAY,UAAa,SAAS,WAAW,KAAM,QAAO;AACvE,SAAO;AACR;AAGO,SAAS,2BACf,UACA,QAAqB,CAAC,GACZ;AACV,MAAI,CAAC,sBAAsB,UAAU,MAAM,IAAI,EAAG,QAAO;AACzD,MAAI,MAAM,kBAAk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 -0,0 +1,462 @@
1
+ import {
2
+ fromAny,
3
+ fromAsyncIter,
4
+ fromIter,
5
+ fromPromise,
6
+ interval,
7
+ of,
8
+ timer
9
+ } from "./chunk-G4M3NHRJ.js";
10
+ import {
11
+ filter,
12
+ initNode,
13
+ map,
14
+ merge
15
+ } from "./chunk-PKVBHGBM.js";
16
+ import {
17
+ CTX_NODE_BINDING,
18
+ depBatch,
19
+ depCount,
20
+ depTerminal,
21
+ isTerminalComplete,
22
+ isTerminalError,
23
+ terminalErrorValue
24
+ } from "./chunk-SWTLEQL6.js";
25
+ import {
26
+ errorPayload
27
+ } from "./chunk-DK554R7P.js";
28
+
29
+ // src/graph/higher-order.ts
30
+ function uniqueNodes(nodes) {
31
+ const seen = /* @__PURE__ */ new Set();
32
+ const out = [];
33
+ for (const n of nodes) {
34
+ if (seen.has(n)) continue;
35
+ seen.add(n);
36
+ out.push(n);
37
+ }
38
+ return out;
39
+ }
40
+ function cleanupAllInners(ctx, st, body) {
41
+ for (const inner of uniqueNodes(st.inners)) ctx.rewireNext.unsubscribeDep(inner, body);
42
+ st.inners = [];
43
+ st.queue.length = 0;
44
+ st.sourceDone = true;
45
+ ctx.state.set(st);
46
+ }
47
+ function firstErrorTerminal(ctx) {
48
+ for (let i = 0; i < depCount(ctx); i++) {
49
+ const terminal = depTerminal(ctx, i);
50
+ if (isTerminalError(terminal)) return terminalErrorValue(terminal);
51
+ }
52
+ return void 0;
53
+ }
54
+ function fromAnyInCtx(ctx, input) {
55
+ const binding = ctx[CTX_NODE_BINDING];
56
+ if (isNode(input)) return input;
57
+ const nodeOpts = binding ? { dispatcher: binding.dispatcher } : {};
58
+ const make = (op) => binding ? binding.create(() => initNode(op, [], nodeOpts)) : initNode(op, [], nodeOpts);
59
+ if (isThenable(input)) return make(fromPromise(input));
60
+ if (input !== null && input !== void 0) {
61
+ const candidate = input;
62
+ if (typeof candidate[Symbol.asyncIterator] === "function") {
63
+ return make(fromAsyncIter(input));
64
+ }
65
+ if (typeof candidate[Symbol.iterator] === "function") {
66
+ return make(fromIter(input));
67
+ }
68
+ }
69
+ return make(of(input));
70
+ }
71
+ function isNode(x) {
72
+ return x != null && typeof x === "object" && "cache" in x && typeof x.subscribe === "function";
73
+ }
74
+ function isThenable(x) {
75
+ return x != null && typeof x.then === "function";
76
+ }
77
+ function normalizeConcurrent(factory, concurrent) {
78
+ if (concurrent === void 0 || concurrent === Number.POSITIVE_INFINITY) {
79
+ return Number.POSITIVE_INFINITY;
80
+ }
81
+ if (!Number.isInteger(concurrent) || concurrent < 1) {
82
+ throw new RangeError(`${factory}: concurrent must be a positive integer or Infinity`);
83
+ }
84
+ return concurrent;
85
+ }
86
+ function mapOperator(factory, project, mode, opts = {}) {
87
+ const maxConcurrent = normalizeConcurrent(factory, opts.concurrent);
88
+ const body = (ctx) => {
89
+ let st;
90
+ try {
91
+ st = ctx.state.get() ?? {
92
+ inners: [],
93
+ queue: [],
94
+ sourceDone: false
95
+ };
96
+ let inners = st.inners;
97
+ const queue = st.queue;
98
+ for (let i = 1; i < depCount(ctx); i++) {
99
+ const b = depBatch(ctx, i);
100
+ if (b && b.length > 0) for (const v of b) ctx.down([["DATA", v]]);
101
+ }
102
+ const terminalError = firstErrorTerminal(ctx);
103
+ if (terminalError !== void 0) {
104
+ cleanupAllInners(ctx, st, body);
105
+ ctx.down([["ERROR", terminalError]]);
106
+ return;
107
+ }
108
+ if (isTerminalComplete(depTerminal(ctx, 0))) st.sourceDone = true;
109
+ const toRemove = [];
110
+ const survivors = [];
111
+ for (let i = 0; i < inners.length; i++) {
112
+ if (isTerminalComplete(depTerminal(ctx, i + 1))) toRemove.push(inners[i]);
113
+ else survivors.push(inners[i]);
114
+ }
115
+ inners = survivors;
116
+ const toAdd = [];
117
+ const make = (v) => fromAnyInCtx(ctx, project(v));
118
+ const isRemovedThisWave = (inner) => toRemove.includes(inner);
119
+ const canTrackInner = (inner) => !inners.includes(inner) && !isRemovedThisWave(inner);
120
+ const enqueueMerge = (v) => {
121
+ if (maxConcurrent === Number.POSITIVE_INFINITY && queue.length === 0) {
122
+ const inner = make(v);
123
+ if (!canTrackInner(inner)) return;
124
+ inners.push(inner);
125
+ toAdd.push(inner);
126
+ return;
127
+ }
128
+ queue.push(v);
129
+ };
130
+ const drainMergeQueue = () => {
131
+ while (queue.length > 0 && inners.length < maxConcurrent) {
132
+ const inner = make(queue.shift());
133
+ if (!canTrackInner(inner)) continue;
134
+ inners.push(inner);
135
+ toAdd.push(inner);
136
+ }
137
+ };
138
+ const sb = depBatch(ctx, 0);
139
+ if (sb && sb.length > 0) {
140
+ if (mode === "switch") {
141
+ const inner = make(sb[sb.length - 1]);
142
+ for (const live of inners) if (live !== inner) toRemove.push(live);
143
+ if (isRemovedThisWave(inner)) {
144
+ inners = [];
145
+ } else {
146
+ if (!inners.includes(inner)) toAdd.push(inner);
147
+ inners = [inner];
148
+ }
149
+ } else if (mode === "merge") {
150
+ for (const v of sb) {
151
+ enqueueMerge(v);
152
+ }
153
+ } else if (mode === "concat") {
154
+ for (const v of sb) queue.push(v);
155
+ } else {
156
+ if (inners.length === 0) {
157
+ const inner = make(sb[0]);
158
+ if (canTrackInner(inner)) {
159
+ inners.push(inner);
160
+ toAdd.push(inner);
161
+ }
162
+ }
163
+ }
164
+ }
165
+ if (mode === "merge" && queue.length > 0) drainMergeQueue();
166
+ if (mode === "concat" && inners.length === 0 && toAdd.length === 0 && queue.length > 0) {
167
+ const inner = make(queue.shift());
168
+ if (canTrackInner(inner)) {
169
+ inners.push(inner);
170
+ toAdd.push(inner);
171
+ }
172
+ }
173
+ ctx.state.set({ inners, queue, sourceDone: st.sourceDone });
174
+ for (const r of toRemove) ctx.rewireNext.unsubscribeDep(r, body);
175
+ for (const a of toAdd) ctx.rewireNext.subscribeDep(a, body);
176
+ if (st.sourceDone && inners.length === 0 && toAdd.length === 0 && queue.length === 0) {
177
+ ctx.down([["COMPLETE"]]);
178
+ }
179
+ } catch (e) {
180
+ if (st) cleanupAllInners(ctx, st, body);
181
+ ctx.down([["ERROR", errorPayload(e, "projector threw without a valid error payload")]]);
182
+ }
183
+ };
184
+ return {
185
+ factory,
186
+ body,
187
+ // D47/D81 folding: the operator owns completion + terminal ERROR cleanup.
188
+ opts: { completeWhenDepsComplete: false, terminalAsRealInput: true, errorWhenDepsError: false }
189
+ };
190
+ }
191
+ function switchMap(project) {
192
+ return mapOperator("switchMap", project, "switch");
193
+ }
194
+ function mergeMap(project, opts = {}) {
195
+ return mapOperator("mergeMap", project, "merge", opts);
196
+ }
197
+ function flatMap(project, opts = {}) {
198
+ return mapOperator("flatMap", project, "merge", opts);
199
+ }
200
+ function concatMap(project) {
201
+ return mapOperator("concatMap", project, "concat");
202
+ }
203
+ function exhaustMap(project) {
204
+ return mapOperator("exhaustMap", project, "exhaust");
205
+ }
206
+ function repeat(factory, count) {
207
+ if (!Number.isInteger(count) || count < 1) {
208
+ throw new RangeError(`repeat: count must be a positive integer (got ${count})`);
209
+ }
210
+ const body = (ctx) => {
211
+ try {
212
+ const st = ctx.state.get() ?? {
213
+ started: false,
214
+ round: 0,
215
+ inner: null
216
+ };
217
+ for (let i = 0; i < depCount(ctx); i++) {
218
+ const b = depBatch(ctx, i);
219
+ if (b && b.length > 0) for (const v of b) ctx.down([["DATA", v]]);
220
+ }
221
+ if (!st.started) {
222
+ st.started = true;
223
+ st.round = 0;
224
+ const inner = fromAnyInCtx(ctx, factory());
225
+ st.inner = inner;
226
+ ctx.state.set(st);
227
+ ctx.rewireNext.subscribeDep(inner, body);
228
+ return;
229
+ }
230
+ if (st.inner !== null && isTerminalComplete(depTerminal(ctx, 0))) {
231
+ const old = st.inner;
232
+ ctx.rewireNext.unsubscribeDep(old, body);
233
+ if (st.round + 1 < count) {
234
+ st.round += 1;
235
+ const next = fromAnyInCtx(ctx, factory());
236
+ st.inner = next;
237
+ ctx.state.set(st);
238
+ ctx.rewireNext.subscribeDep(next, body);
239
+ } else {
240
+ st.inner = null;
241
+ ctx.state.set(st);
242
+ ctx.down([["COMPLETE"]]);
243
+ }
244
+ }
245
+ } catch (e) {
246
+ ctx.down([["ERROR", errorPayload(e, "repeat threw without a valid error payload")]]);
247
+ }
248
+ };
249
+ return {
250
+ factory: "repeat",
251
+ body,
252
+ opts: { completeWhenDepsComplete: false, terminalAsRealInput: true }
253
+ };
254
+ }
255
+
256
+ // src/graph/time.ts
257
+ function delayedValue(v, ms) {
258
+ return initNode(
259
+ map(() => v),
260
+ [initNode(timer(ms), [])]
261
+ );
262
+ }
263
+ function throttleWindow(v, ms) {
264
+ const silentTimer = initNode(
265
+ filter(() => false),
266
+ [initNode(timer(ms), [])]
267
+ );
268
+ return initNode(merge(), [initNode(of(v), []), silentTimer]);
269
+ }
270
+ function delay(ms) {
271
+ return { ...mergeMap((v) => delayedValue(v, ms)), factory: "delay" };
272
+ }
273
+ function debounce(ms) {
274
+ return { ...switchMap((v) => delayedValue(v, ms)), factory: "debounce" };
275
+ }
276
+ function debounceTime(ms) {
277
+ return { ...switchMap((v) => delayedValue(v, ms)), factory: "debounceTime" };
278
+ }
279
+ function throttle(ms) {
280
+ return { ...exhaustMap((v) => throttleWindow(v, ms)), factory: "throttle" };
281
+ }
282
+ function throttleTime(ms) {
283
+ return { ...exhaustMap((v) => throttleWindow(v, ms)), factory: "throttleTime" };
284
+ }
285
+ function audit(durationSelector) {
286
+ const body = (ctx) => {
287
+ try {
288
+ const st = ctx.state.get() ?? {
289
+ windowOpen: false,
290
+ latest: void 0,
291
+ notifier: null
292
+ };
293
+ const sourceBatch = depBatch(ctx, 0);
294
+ const notifierBatch = depBatch(ctx, 1);
295
+ const sourceTerminal = depTerminal(ctx, 0);
296
+ const notifierTerminal = depTerminal(ctx, 1);
297
+ const sb = sourceBatch;
298
+ if (sb) for (const v of sb) st.latest = { v };
299
+ const notifierFired = st.windowOpen && (notifierBatch != null && notifierBatch.length > 0 || isTerminalComplete(notifierTerminal));
300
+ if (notifierFired) {
301
+ if (st.latest !== void 0) ctx.down([["DATA", st.latest.v]]);
302
+ const old = st.notifier;
303
+ st.windowOpen = false;
304
+ st.notifier = null;
305
+ st.latest = void 0;
306
+ if (old) ctx.rewireNext.unsubscribeDep(old, body);
307
+ }
308
+ const sourceError = isTerminalError(sourceTerminal);
309
+ const notifierError = isTerminalError(notifierTerminal);
310
+ if (sourceError || notifierError) {
311
+ const err = terminalErrorValue(sourceError ? sourceTerminal : notifierTerminal);
312
+ if (st.notifier) ctx.rewireNext.unsubscribeDep(st.notifier, body);
313
+ ctx.state.set({ windowOpen: false, latest: void 0, notifier: null });
314
+ ctx.down([["ERROR", err]]);
315
+ return;
316
+ }
317
+ if (isTerminalComplete(sourceTerminal)) {
318
+ if (st.windowOpen && st.latest !== void 0) ctx.down([["DATA", st.latest.v]]);
319
+ if (st.notifier) ctx.rewireNext.unsubscribeDep(st.notifier, body);
320
+ ctx.state.set({ windowOpen: false, latest: void 0, notifier: null });
321
+ ctx.down([["COMPLETE"]]);
322
+ return;
323
+ }
324
+ if (!st.windowOpen && sb != null && sb.length > 0 && st.latest !== void 0) {
325
+ const n = fromAny(durationSelector(st.latest.v), { iter: true });
326
+ st.windowOpen = true;
327
+ st.notifier = n;
328
+ ctx.rewireNext.subscribeDep(n, body);
329
+ }
330
+ ctx.state.set(st);
331
+ } catch (e) {
332
+ ctx.down([["ERROR", errorPayload(e, "audit threw without a valid error payload")]]);
333
+ }
334
+ };
335
+ return {
336
+ factory: "audit",
337
+ body,
338
+ opts: {
339
+ partial: true,
340
+ completeWhenDepsComplete: false,
341
+ errorWhenDepsError: false,
342
+ terminalAsRealInput: true
343
+ }
344
+ };
345
+ }
346
+ function auditTime(ms) {
347
+ return { ...audit(() => initNode(timer(ms), [])), factory: "auditTime" };
348
+ }
349
+ function timeout(source, ms) {
350
+ const makeTimer = () => initNode(timer(ms), []);
351
+ const initial = makeTimer();
352
+ const body = (ctx) => {
353
+ try {
354
+ const st = ctx.state.get() ?? { timer: initial };
355
+ const srcBatch = depBatch(ctx, 0);
356
+ const srcTerminal = depTerminal(ctx, 0);
357
+ const sb = srcBatch;
358
+ if (sb != null && sb.length > 0) {
359
+ for (const v of sb) ctx.down([["DATA", v]]);
360
+ const old = st.timer;
361
+ const next = makeTimer();
362
+ st.timer = next;
363
+ ctx.state.set(st);
364
+ if (old) ctx.rewireNext.unsubscribeDep(old, body);
365
+ ctx.rewireNext.subscribeDep(next, body);
366
+ return;
367
+ }
368
+ if (isTerminalComplete(srcTerminal)) {
369
+ if (st.timer) ctx.rewireNext.unsubscribeDep(st.timer, body);
370
+ ctx.down([["COMPLETE"]]);
371
+ return;
372
+ }
373
+ if (isTerminalError(srcTerminal)) {
374
+ if (st.timer) ctx.rewireNext.unsubscribeDep(st.timer, body);
375
+ ctx.down([["ERROR", terminalErrorValue(srcTerminal)]]);
376
+ return;
377
+ }
378
+ const timerBatch = depBatch(ctx, 1);
379
+ if (timerBatch != null && timerBatch.length > 0 || isTerminalComplete(depTerminal(ctx, 1))) {
380
+ ctx.down([["ERROR", new Error(`timeout: no value within ${ms}ms`)]]);
381
+ return;
382
+ }
383
+ ctx.state.set(st);
384
+ } catch (e) {
385
+ ctx.down([["ERROR", errorPayload(e, "timeout threw without a valid error payload")]]);
386
+ }
387
+ };
388
+ return initNode(
389
+ {
390
+ factory: "timeout",
391
+ body,
392
+ opts: {
393
+ partial: true,
394
+ completeWhenDepsComplete: false,
395
+ errorWhenDepsError: false,
396
+ terminalAsRealInput: true
397
+ }
398
+ },
399
+ [source, initial]
400
+ );
401
+ }
402
+ function bufferTime(source, ms) {
403
+ const iv = initNode(interval(ms), []);
404
+ const body = (ctx) => {
405
+ const srcBatch = depBatch(ctx, 0);
406
+ const tickBatch = depBatch(ctx, 1);
407
+ const srcTerminal = depTerminal(ctx, 0);
408
+ const buf = ctx.state.get() ?? [];
409
+ if (srcBatch) for (const v of srcBatch) buf.push(v);
410
+ if (isTerminalComplete(srcTerminal)) {
411
+ if (buf.length > 0) ctx.down([["DATA", [...buf]]]);
412
+ ctx.state.set([]);
413
+ ctx.rewireNext.unsubscribeDep(iv, body);
414
+ ctx.down([["COMPLETE"]]);
415
+ return;
416
+ }
417
+ if (isTerminalError(srcTerminal)) {
418
+ ctx.state.set([]);
419
+ ctx.rewireNext.unsubscribeDep(iv, body);
420
+ ctx.down([["ERROR", terminalErrorValue(srcTerminal)]]);
421
+ return;
422
+ }
423
+ if (tickBatch && tickBatch.length > 0) {
424
+ ctx.down([["DATA", [...buf]]]);
425
+ ctx.state.set([]);
426
+ return;
427
+ }
428
+ ctx.state.set(buf);
429
+ };
430
+ return initNode(
431
+ {
432
+ factory: "bufferTime",
433
+ body,
434
+ opts: {
435
+ partial: true,
436
+ completeWhenDepsComplete: false,
437
+ errorWhenDepsError: false,
438
+ terminalAsRealInput: true
439
+ }
440
+ },
441
+ [source, iv]
442
+ );
443
+ }
444
+
445
+ export {
446
+ switchMap,
447
+ mergeMap,
448
+ flatMap,
449
+ concatMap,
450
+ exhaustMap,
451
+ repeat,
452
+ delay,
453
+ debounce,
454
+ debounceTime,
455
+ throttle,
456
+ throttleTime,
457
+ audit,
458
+ auditTime,
459
+ timeout,
460
+ bufferTime
461
+ };
462
+ //# sourceMappingURL=chunk-JR4IKCR2.js.map