@fgv/ts-agent-memory 5.1.0-36

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 (331) hide show
  1. package/.rush/temp/chunked-rush-logs/ts-agent-memory.build.chunks.jsonl +9 -0
  2. package/.rush/temp/f6a88bfdd66517ccb98c2c7ae1be6e6fe9e15d38.tar.log +282 -0
  3. package/.rush/temp/operation/build/all.log +9 -0
  4. package/.rush/temp/operation/build/log-chunks.jsonl +9 -0
  5. package/.rush/temp/operation/build/state.json +3 -0
  6. package/.rush/temp/shrinkwrap-deps.json +688 -0
  7. package/LICENSE +21 -0
  8. package/README.md +45 -0
  9. package/config/api-extractor.json +343 -0
  10. package/config/jest.config.json +14 -0
  11. package/config/rig.json +4 -0
  12. package/dist/index.js +12 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/packlets/converters/bodyConverterRegistry.js +51 -0
  15. package/dist/packlets/converters/bodyConverterRegistry.js.map +1 -0
  16. package/dist/packlets/converters/envelopeConverter.js +159 -0
  17. package/dist/packlets/converters/envelopeConverter.js.map +1 -0
  18. package/dist/packlets/converters/index.js +7 -0
  19. package/dist/packlets/converters/index.js.map +1 -0
  20. package/dist/packlets/index/index.js +6 -0
  21. package/dist/packlets/index/index.js.map +1 -0
  22. package/dist/packlets/index/memoryIndex.js +170 -0
  23. package/dist/packlets/index/memoryIndex.js.map +1 -0
  24. package/dist/packlets/observe/index.js +7 -0
  25. package/dist/packlets/observe/index.js.map +1 -0
  26. package/dist/packlets/observe/memoryObservationStore.js +119 -0
  27. package/dist/packlets/observe/memoryObservationStore.js.map +1 -0
  28. package/dist/packlets/observe/observer.js +6 -0
  29. package/dist/packlets/observe/observer.js.map +1 -0
  30. package/dist/packlets/retrieve/hybridRetriever.js +135 -0
  31. package/dist/packlets/retrieve/hybridRetriever.js.map +1 -0
  32. package/dist/packlets/retrieve/index.js +12 -0
  33. package/dist/packlets/retrieve/index.js.map +1 -0
  34. package/dist/packlets/retrieve/linkTraversalRetriever.js +143 -0
  35. package/dist/packlets/retrieve/linkTraversalRetriever.js.map +1 -0
  36. package/dist/packlets/retrieve/recencyRetriever.js +33 -0
  37. package/dist/packlets/retrieve/recencyRetriever.js.map +1 -0
  38. package/dist/packlets/retrieve/retriever.js +110 -0
  39. package/dist/packlets/retrieve/retriever.js.map +1 -0
  40. package/dist/packlets/retrieve/semanticRetriever.js +86 -0
  41. package/dist/packlets/retrieve/semanticRetriever.js.map +1 -0
  42. package/dist/packlets/retrieve/structuredFilterRetriever.js +37 -0
  43. package/dist/packlets/retrieve/structuredFilterRetriever.js.map +1 -0
  44. package/dist/packlets/retrieve/tagRetriever.js +37 -0
  45. package/dist/packlets/retrieve/tagRetriever.js.map +1 -0
  46. package/dist/packlets/store/fileTreeMemoryStore.js +698 -0
  47. package/dist/packlets/store/fileTreeMemoryStore.js.map +1 -0
  48. package/dist/packlets/store/index.js +7 -0
  49. package/dist/packlets/store/index.js.map +1 -0
  50. package/dist/packlets/store/scopeEncoding.js +31 -0
  51. package/dist/packlets/store/scopeEncoding.js.map +1 -0
  52. package/dist/packlets/types/envelope.js +6 -0
  53. package/dist/packlets/types/envelope.js.map +1 -0
  54. package/dist/packlets/types/filenameSafety.js +52 -0
  55. package/dist/packlets/types/filenameSafety.js.map +1 -0
  56. package/dist/packlets/types/identityCodec.js +184 -0
  57. package/dist/packlets/types/identityCodec.js.map +1 -0
  58. package/dist/packlets/types/ids.js +67 -0
  59. package/dist/packlets/types/ids.js.map +1 -0
  60. package/dist/packlets/types/index.js +10 -0
  61. package/dist/packlets/types/index.js.map +1 -0
  62. package/dist/packlets/types/writePolicy.js +263 -0
  63. package/dist/packlets/types/writePolicy.js.map +1 -0
  64. package/dist/packlets/vector/inMemoryCosineIndex.js +150 -0
  65. package/dist/packlets/vector/inMemoryCosineIndex.js.map +1 -0
  66. package/dist/packlets/vector/index.js +7 -0
  67. package/dist/packlets/vector/index.js.map +1 -0
  68. package/dist/packlets/vector/vectorIndex.js +6 -0
  69. package/dist/packlets/vector/vectorIndex.js.map +1 -0
  70. package/dist/test/unit/converters/bodyConverterRegistry.test.js +72 -0
  71. package/dist/test/unit/converters/bodyConverterRegistry.test.js.map +1 -0
  72. package/dist/test/unit/converters/envelopeConverter.test.js +196 -0
  73. package/dist/test/unit/converters/envelopeConverter.test.js.map +1 -0
  74. package/dist/test/unit/index/memoryIndex.test.js +152 -0
  75. package/dist/test/unit/index/memoryIndex.test.js.map +1 -0
  76. package/dist/test/unit/observe/memoryObservationStore.test.js +118 -0
  77. package/dist/test/unit/observe/memoryObservationStore.test.js.map +1 -0
  78. package/dist/test/unit/retrieve/linkTraversalRetriever.test.js +182 -0
  79. package/dist/test/unit/retrieve/linkTraversalRetriever.test.js.map +1 -0
  80. package/dist/test/unit/retrieve/retrievers.test.js +506 -0
  81. package/dist/test/unit/retrieve/retrievers.test.js.map +1 -0
  82. package/dist/test/unit/store/embedOnWrite.test.js +260 -0
  83. package/dist/test/unit/store/embedOnWrite.test.js.map +1 -0
  84. package/dist/test/unit/store/fileTreeMemoryStore.test.js +647 -0
  85. package/dist/test/unit/store/fileTreeMemoryStore.test.js.map +1 -0
  86. package/dist/test/unit/store/observations.test.js +239 -0
  87. package/dist/test/unit/store/observations.test.js.map +1 -0
  88. package/dist/test/unit/store/scopeEncoding.test.js +24 -0
  89. package/dist/test/unit/store/scopeEncoding.test.js.map +1 -0
  90. package/dist/test/unit/types/identityCodec.test.js +187 -0
  91. package/dist/test/unit/types/identityCodec.test.js.map +1 -0
  92. package/dist/test/unit/types/ids.test.js +84 -0
  93. package/dist/test/unit/types/ids.test.js.map +1 -0
  94. package/dist/test/unit/types/writePolicy.test.js +241 -0
  95. package/dist/test/unit/types/writePolicy.test.js.map +1 -0
  96. package/dist/test/unit/vector/inMemoryCosineIndex.test.js +192 -0
  97. package/dist/test/unit/vector/inMemoryCosineIndex.test.js.map +1 -0
  98. package/dist/test/unit/vector/vectorIndex.test.js +42 -0
  99. package/dist/test/unit/vector/vectorIndex.test.js.map +1 -0
  100. package/dist/ts-agent-memory.d.ts +1901 -0
  101. package/dist/tsdoc-metadata.json +11 -0
  102. package/eslint.config.js +15 -0
  103. package/etc/ts-agent-memory.api.md +525 -0
  104. package/lib/index.d.ts +8 -0
  105. package/lib/index.d.ts.map +1 -0
  106. package/lib/index.js +28 -0
  107. package/lib/index.js.map +1 -0
  108. package/lib/packlets/converters/bodyConverterRegistry.d.ts +64 -0
  109. package/lib/packlets/converters/bodyConverterRegistry.d.ts.map +1 -0
  110. package/lib/packlets/converters/bodyConverterRegistry.js +55 -0
  111. package/lib/packlets/converters/bodyConverterRegistry.js.map +1 -0
  112. package/lib/packlets/converters/envelopeConverter.d.ts +70 -0
  113. package/lib/packlets/converters/envelopeConverter.d.ts.map +1 -0
  114. package/lib/packlets/converters/envelopeConverter.js +166 -0
  115. package/lib/packlets/converters/envelopeConverter.js.map +1 -0
  116. package/lib/packlets/converters/index.d.ts +3 -0
  117. package/lib/packlets/converters/index.d.ts.map +1 -0
  118. package/lib/packlets/converters/index.js +23 -0
  119. package/lib/packlets/converters/index.js.map +1 -0
  120. package/lib/packlets/index/index.d.ts +2 -0
  121. package/lib/packlets/index/index.d.ts.map +1 -0
  122. package/lib/packlets/index/index.js +22 -0
  123. package/lib/packlets/index/index.js.map +1 -0
  124. package/lib/packlets/index/memoryIndex.d.ts +127 -0
  125. package/lib/packlets/index/memoryIndex.d.ts.map +1 -0
  126. package/lib/packlets/index/memoryIndex.js +174 -0
  127. package/lib/packlets/index/memoryIndex.js.map +1 -0
  128. package/lib/packlets/observe/index.d.ts +3 -0
  129. package/lib/packlets/observe/index.d.ts.map +1 -0
  130. package/lib/packlets/observe/index.js +23 -0
  131. package/lib/packlets/observe/index.js.map +1 -0
  132. package/lib/packlets/observe/memoryObservationStore.d.ts +91 -0
  133. package/lib/packlets/observe/memoryObservationStore.d.ts.map +1 -0
  134. package/lib/packlets/observe/memoryObservationStore.js +123 -0
  135. package/lib/packlets/observe/memoryObservationStore.js.map +1 -0
  136. package/lib/packlets/observe/observer.d.ts +110 -0
  137. package/lib/packlets/observe/observer.d.ts.map +1 -0
  138. package/lib/packlets/observe/observer.js +7 -0
  139. package/lib/packlets/observe/observer.js.map +1 -0
  140. package/lib/packlets/retrieve/hybridRetriever.d.ts +79 -0
  141. package/lib/packlets/retrieve/hybridRetriever.d.ts.map +1 -0
  142. package/lib/packlets/retrieve/hybridRetriever.js +140 -0
  143. package/lib/packlets/retrieve/hybridRetriever.js.map +1 -0
  144. package/lib/packlets/retrieve/index.d.ts +8 -0
  145. package/lib/packlets/retrieve/index.d.ts.map +1 -0
  146. package/lib/packlets/retrieve/index.js +28 -0
  147. package/lib/packlets/retrieve/index.js.map +1 -0
  148. package/lib/packlets/retrieve/linkTraversalRetriever.d.ts +61 -0
  149. package/lib/packlets/retrieve/linkTraversalRetriever.d.ts.map +1 -0
  150. package/lib/packlets/retrieve/linkTraversalRetriever.js +147 -0
  151. package/lib/packlets/retrieve/linkTraversalRetriever.js.map +1 -0
  152. package/lib/packlets/retrieve/recencyRetriever.d.ts +21 -0
  153. package/lib/packlets/retrieve/recencyRetriever.d.ts.map +1 -0
  154. package/lib/packlets/retrieve/recencyRetriever.js +37 -0
  155. package/lib/packlets/retrieve/recencyRetriever.js.map +1 -0
  156. package/lib/packlets/retrieve/retriever.d.ts +133 -0
  157. package/lib/packlets/retrieve/retriever.d.ts.map +1 -0
  158. package/lib/packlets/retrieve/retriever.js +119 -0
  159. package/lib/packlets/retrieve/retriever.js.map +1 -0
  160. package/lib/packlets/retrieve/semanticRetriever.d.ts +69 -0
  161. package/lib/packlets/retrieve/semanticRetriever.d.ts.map +1 -0
  162. package/lib/packlets/retrieve/semanticRetriever.js +90 -0
  163. package/lib/packlets/retrieve/semanticRetriever.js.map +1 -0
  164. package/lib/packlets/retrieve/structuredFilterRetriever.d.ts +22 -0
  165. package/lib/packlets/retrieve/structuredFilterRetriever.d.ts.map +1 -0
  166. package/lib/packlets/retrieve/structuredFilterRetriever.js +41 -0
  167. package/lib/packlets/retrieve/structuredFilterRetriever.js.map +1 -0
  168. package/lib/packlets/retrieve/tagRetriever.d.ts +22 -0
  169. package/lib/packlets/retrieve/tagRetriever.d.ts.map +1 -0
  170. package/lib/packlets/retrieve/tagRetriever.js +41 -0
  171. package/lib/packlets/retrieve/tagRetriever.js.map +1 -0
  172. package/lib/packlets/store/fileTreeMemoryStore.d.ts +327 -0
  173. package/lib/packlets/store/fileTreeMemoryStore.d.ts.map +1 -0
  174. package/lib/packlets/store/fileTreeMemoryStore.js +702 -0
  175. package/lib/packlets/store/fileTreeMemoryStore.js.map +1 -0
  176. package/lib/packlets/store/index.d.ts +3 -0
  177. package/lib/packlets/store/index.d.ts.map +1 -0
  178. package/lib/packlets/store/index.js +23 -0
  179. package/lib/packlets/store/index.js.map +1 -0
  180. package/lib/packlets/store/scopeEncoding.d.ts +19 -0
  181. package/lib/packlets/store/scopeEncoding.d.ts.map +1 -0
  182. package/lib/packlets/store/scopeEncoding.js +34 -0
  183. package/lib/packlets/store/scopeEncoding.js.map +1 -0
  184. package/lib/packlets/types/envelope.d.ts +119 -0
  185. package/lib/packlets/types/envelope.d.ts.map +1 -0
  186. package/lib/packlets/types/envelope.js +7 -0
  187. package/lib/packlets/types/envelope.js.map +1 -0
  188. package/lib/packlets/types/filenameSafety.d.ts +16 -0
  189. package/lib/packlets/types/filenameSafety.d.ts.map +1 -0
  190. package/lib/packlets/types/filenameSafety.js +55 -0
  191. package/lib/packlets/types/filenameSafety.js.map +1 -0
  192. package/lib/packlets/types/identityCodec.d.ts +136 -0
  193. package/lib/packlets/types/identityCodec.d.ts.map +1 -0
  194. package/lib/packlets/types/identityCodec.js +190 -0
  195. package/lib/packlets/types/identityCodec.js.map +1 -0
  196. package/lib/packlets/types/ids.d.ts +55 -0
  197. package/lib/packlets/types/ids.d.ts.map +1 -0
  198. package/lib/packlets/types/ids.js +70 -0
  199. package/lib/packlets/types/ids.js.map +1 -0
  200. package/lib/packlets/types/index.d.ts +6 -0
  201. package/lib/packlets/types/index.d.ts.map +1 -0
  202. package/lib/packlets/types/index.js +26 -0
  203. package/lib/packlets/types/index.js.map +1 -0
  204. package/lib/packlets/types/writePolicy.d.ts +213 -0
  205. package/lib/packlets/types/writePolicy.d.ts.map +1 -0
  206. package/lib/packlets/types/writePolicy.js +268 -0
  207. package/lib/packlets/types/writePolicy.js.map +1 -0
  208. package/lib/packlets/vector/inMemoryCosineIndex.d.ts +69 -0
  209. package/lib/packlets/vector/inMemoryCosineIndex.d.ts.map +1 -0
  210. package/lib/packlets/vector/inMemoryCosineIndex.js +154 -0
  211. package/lib/packlets/vector/inMemoryCosineIndex.js.map +1 -0
  212. package/lib/packlets/vector/index.d.ts +3 -0
  213. package/lib/packlets/vector/index.d.ts.map +1 -0
  214. package/lib/packlets/vector/index.js +23 -0
  215. package/lib/packlets/vector/index.js.map +1 -0
  216. package/lib/packlets/vector/vectorIndex.d.ts +68 -0
  217. package/lib/packlets/vector/vectorIndex.d.ts.map +1 -0
  218. package/lib/packlets/vector/vectorIndex.js +7 -0
  219. package/lib/packlets/vector/vectorIndex.js.map +1 -0
  220. package/lib/test/unit/converters/bodyConverterRegistry.test.d.ts +2 -0
  221. package/lib/test/unit/converters/bodyConverterRegistry.test.d.ts.map +1 -0
  222. package/lib/test/unit/converters/bodyConverterRegistry.test.js +74 -0
  223. package/lib/test/unit/converters/bodyConverterRegistry.test.js.map +1 -0
  224. package/lib/test/unit/converters/envelopeConverter.test.d.ts +2 -0
  225. package/lib/test/unit/converters/envelopeConverter.test.d.ts.map +1 -0
  226. package/lib/test/unit/converters/envelopeConverter.test.js +198 -0
  227. package/lib/test/unit/converters/envelopeConverter.test.js.map +1 -0
  228. package/lib/test/unit/index/memoryIndex.test.d.ts +2 -0
  229. package/lib/test/unit/index/memoryIndex.test.d.ts.map +1 -0
  230. package/lib/test/unit/index/memoryIndex.test.js +154 -0
  231. package/lib/test/unit/index/memoryIndex.test.js.map +1 -0
  232. package/lib/test/unit/observe/memoryObservationStore.test.d.ts +2 -0
  233. package/lib/test/unit/observe/memoryObservationStore.test.d.ts.map +1 -0
  234. package/lib/test/unit/observe/memoryObservationStore.test.js +120 -0
  235. package/lib/test/unit/observe/memoryObservationStore.test.js.map +1 -0
  236. package/lib/test/unit/retrieve/linkTraversalRetriever.test.d.ts +2 -0
  237. package/lib/test/unit/retrieve/linkTraversalRetriever.test.d.ts.map +1 -0
  238. package/lib/test/unit/retrieve/linkTraversalRetriever.test.js +184 -0
  239. package/lib/test/unit/retrieve/linkTraversalRetriever.test.js.map +1 -0
  240. package/lib/test/unit/retrieve/retrievers.test.d.ts +2 -0
  241. package/lib/test/unit/retrieve/retrievers.test.d.ts.map +1 -0
  242. package/lib/test/unit/retrieve/retrievers.test.js +508 -0
  243. package/lib/test/unit/retrieve/retrievers.test.js.map +1 -0
  244. package/lib/test/unit/store/embedOnWrite.test.d.ts +2 -0
  245. package/lib/test/unit/store/embedOnWrite.test.d.ts.map +1 -0
  246. package/lib/test/unit/store/embedOnWrite.test.js +262 -0
  247. package/lib/test/unit/store/embedOnWrite.test.js.map +1 -0
  248. package/lib/test/unit/store/fileTreeMemoryStore.test.d.ts +2 -0
  249. package/lib/test/unit/store/fileTreeMemoryStore.test.d.ts.map +1 -0
  250. package/lib/test/unit/store/fileTreeMemoryStore.test.js +649 -0
  251. package/lib/test/unit/store/fileTreeMemoryStore.test.js.map +1 -0
  252. package/lib/test/unit/store/observations.test.d.ts +2 -0
  253. package/lib/test/unit/store/observations.test.d.ts.map +1 -0
  254. package/lib/test/unit/store/observations.test.js +241 -0
  255. package/lib/test/unit/store/observations.test.js.map +1 -0
  256. package/lib/test/unit/store/scopeEncoding.test.d.ts +2 -0
  257. package/lib/test/unit/store/scopeEncoding.test.d.ts.map +1 -0
  258. package/lib/test/unit/store/scopeEncoding.test.js +26 -0
  259. package/lib/test/unit/store/scopeEncoding.test.js.map +1 -0
  260. package/lib/test/unit/types/identityCodec.test.d.ts +2 -0
  261. package/lib/test/unit/types/identityCodec.test.d.ts.map +1 -0
  262. package/lib/test/unit/types/identityCodec.test.js +189 -0
  263. package/lib/test/unit/types/identityCodec.test.js.map +1 -0
  264. package/lib/test/unit/types/ids.test.d.ts +2 -0
  265. package/lib/test/unit/types/ids.test.d.ts.map +1 -0
  266. package/lib/test/unit/types/ids.test.js +86 -0
  267. package/lib/test/unit/types/ids.test.js.map +1 -0
  268. package/lib/test/unit/types/writePolicy.test.d.ts +2 -0
  269. package/lib/test/unit/types/writePolicy.test.d.ts.map +1 -0
  270. package/lib/test/unit/types/writePolicy.test.js +243 -0
  271. package/lib/test/unit/types/writePolicy.test.js.map +1 -0
  272. package/lib/test/unit/vector/inMemoryCosineIndex.test.d.ts +2 -0
  273. package/lib/test/unit/vector/inMemoryCosineIndex.test.d.ts.map +1 -0
  274. package/lib/test/unit/vector/inMemoryCosineIndex.test.js +194 -0
  275. package/lib/test/unit/vector/inMemoryCosineIndex.test.js.map +1 -0
  276. package/lib/test/unit/vector/vectorIndex.test.d.ts +2 -0
  277. package/lib/test/unit/vector/vectorIndex.test.d.ts.map +1 -0
  278. package/lib/test/unit/vector/vectorIndex.test.js +44 -0
  279. package/lib/test/unit/vector/vectorIndex.test.js.map +1 -0
  280. package/package.json +81 -0
  281. package/rush-logs/ts-agent-memory.build.cache.log +3 -0
  282. package/rush-logs/ts-agent-memory.build.log +9 -0
  283. package/src/index.ts +12 -0
  284. package/src/packlets/converters/bodyConverterRegistry.ts +105 -0
  285. package/src/packlets/converters/envelopeConverter.ts +210 -0
  286. package/src/packlets/converters/index.ts +7 -0
  287. package/src/packlets/index/index.ts +6 -0
  288. package/src/packlets/index/memoryIndex.ts +268 -0
  289. package/src/packlets/observe/index.ts +7 -0
  290. package/src/packlets/observe/memoryObservationStore.ts +153 -0
  291. package/src/packlets/observe/observer.ts +119 -0
  292. package/src/packlets/retrieve/hybridRetriever.ts +181 -0
  293. package/src/packlets/retrieve/index.ts +12 -0
  294. package/src/packlets/retrieve/linkTraversalRetriever.ts +169 -0
  295. package/src/packlets/retrieve/recencyRetriever.ts +54 -0
  296. package/src/packlets/retrieve/retriever.ts +207 -0
  297. package/src/packlets/retrieve/semanticRetriever.ts +147 -0
  298. package/src/packlets/retrieve/structuredFilterRetriever.ts +58 -0
  299. package/src/packlets/retrieve/tagRetriever.ts +58 -0
  300. package/src/packlets/store/fileTreeMemoryStore.ts +1073 -0
  301. package/src/packlets/store/index.ts +7 -0
  302. package/src/packlets/store/scopeEncoding.ts +36 -0
  303. package/src/packlets/types/envelope.ts +138 -0
  304. package/src/packlets/types/filenameSafety.ts +57 -0
  305. package/src/packlets/types/identityCodec.ts +263 -0
  306. package/src/packlets/types/ids.ts +124 -0
  307. package/src/packlets/types/index.ts +10 -0
  308. package/src/packlets/types/writePolicy.ts +447 -0
  309. package/src/packlets/vector/inMemoryCosineIndex.ts +173 -0
  310. package/src/packlets/vector/index.ts +7 -0
  311. package/src/packlets/vector/vectorIndex.ts +78 -0
  312. package/src/test/unit/converters/bodyConverterRegistry.test.ts +89 -0
  313. package/src/test/unit/converters/envelopeConverter.test.ts +261 -0
  314. package/src/test/unit/index/memoryIndex.test.ts +187 -0
  315. package/src/test/unit/observe/memoryObservationStore.test.ts +158 -0
  316. package/src/test/unit/retrieve/linkTraversalRetriever.test.ts +230 -0
  317. package/src/test/unit/retrieve/retrievers.test.ts +662 -0
  318. package/src/test/unit/store/embedOnWrite.test.ts +346 -0
  319. package/src/test/unit/store/fileTreeMemoryStore.test.ts +875 -0
  320. package/src/test/unit/store/observations.test.ts +290 -0
  321. package/src/test/unit/store/scopeEncoding.test.ts +37 -0
  322. package/src/test/unit/types/identityCodec.test.ts +266 -0
  323. package/src/test/unit/types/ids.test.ts +94 -0
  324. package/src/test/unit/types/writePolicy.test.ts +325 -0
  325. package/src/test/unit/vector/inMemoryCosineIndex.test.ts +242 -0
  326. package/src/test/unit/vector/vectorIndex.test.ts +48 -0
  327. package/temp/build/lint/_eslint-5eVG3S6w.json +182 -0
  328. package/temp/build/typescript/ts_8nwakTlr.json +1 -0
  329. package/temp/ts-agent-memory.api.json +12438 -0
  330. package/temp/ts-agent-memory.api.md +525 -0
  331. package/tsconfig.json +8 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"envelopeConverter.js","sourceRoot":"","sources":["../../../src/packlets/converters/envelopeConverter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAa,UAAU,EAAU,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC7E,OAAO,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAE,OAAO,EAAsE,MAAM,UAAU,CAAC;AAGvG,+CAA+C;AAC/C,yJAAyJ;AACzJ,MAAM,aAAa,GAAoB,UAAU,CAAC,OAAO,CAAO,CAAC,IAAa,EAAE,EAAE,CAChF,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,CACtD,CAAC;AAEF,mDAAmD;AACnD,+HAA+H;AAC/H,MAAM,YAAY,GAA6B,UAAU,CAAC,KAAK,CAAgB;IAC7E,UAAU,CAAC,MAAM;IACjB,aAAa;CACd,CAAC,CAAC;AAEH,iDAAiD;AACjD,wHAAwH;AACxH,MAAM,YAAY,GAA6B,UAAU,CAAC,KAAK,CAAgB;IAC7E,UAAU,CAAC,MAAM;IACjB,aAAa;CACd,CAAC,CAAC;AAEH;;;GAGG;AACH,MAAM,wBAAwB,GAA2B,UAAU,CAAC,MAAM,CACxE;IACE,MAAM,EAAE,UAAU,CAAC,MAAM;IACzB,EAAE,EAAE,UAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IAChC,KAAK,EAAE,UAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IACnC,UAAU,EAAE,UAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IACxC,WAAW,EAAE,OAAO,CAAC,QAAQ,CAAC,QAAQ,EAAE;CACzC,E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EAAE,CAAC;SACjE,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CACtB,QAAQ;SACL,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC;SAClC,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,QAAQ,CAAC,EAAE,oBAAoB,GAAG,EAAE,CAAC;SAC9E,SAAS,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,CACpD,CACJ,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,QAAyB,EAAE,IAAY;IACzE,OAAO,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC;SAChC,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,QAAQ,CAAC,EAAE,oCAAoC,GAAG,EAAE,CAAC;SAC9F,SAAS,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,OAAO,CAAC,eAAe,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Converter, Converters, Result, fail, succeed } from '@fgv/ts-utils';\nimport { Yaml } from '@fgv/ts-extras';\nimport { Convert, IEdge, IMemoryEnvelope, IMemoryRecord, IProvenance, ITemporalBlock } from '../types';\nimport { IBodyConverterRegistry } from './bodyConverterRegistry';\n\n/** Matches exactly the JSON `null` literal. */\n// eslint-disable-next-line @rushstack/no-new-null -- the envelope nullable fields (invalid_at, embeddingRef) carry meaningful null; design-lock §2.3-2.5\nconst nullConverter: Converter<null> = Converters.generic<null>((from: unknown) =>\n from === null ? succeed(null) : fail('expected null')\n);\n\n/** A nullable epoch-ms value (`number | null`). */\n// eslint-disable-next-line @rushstack/no-new-null -- meaningful null for IEdge/ITemporalBlock.invalid_at; design-lock §2.3-2.4\nconst numberOrNull: Converter<number | null> = Converters.oneOf<number | null>([\n Converters.number,\n nullConverter\n]);\n\n/** A nullable string value (`string | null`). */\n// eslint-disable-next-line @rushstack/no-new-null -- meaningful null for IMemoryEnvelope.embeddingRef; design-lock §2.5\nconst stringOrNull: Converter<string | null> = Converters.oneOf<string | null>([\n Converters.string,\n nullConverter\n]);\n\n/**\n * Converter for the known {@link IProvenance} fields. The full\n * {@link provenanceConverter} layers extension-key preservation on top.\n */\nconst knownProvenanceConverter: Converter<IProvenance> = Converters.object<IProvenance>(\n {\n source: Converters.string,\n by: Converters.string.optional(),\n model: Converters.string.optional(),\n confidence: Converters.number.optional(),\n derivedFrom: Convert.memoryId.optional()\n },\n { optionalFields: ['by', 'model', 'confidence', 'derivedFrom'] }\n);\n\n/**\n * Converter for {@link IProvenance}. Validates the known fields and preserves\n * any extension keys verbatim (the `[key: string]: unknown` opaque payload),\n * so a round-trip never drops consumer-attached data.\n * @public\n */\nexport const provenanceConverter: Converter<IProvenance> = Converters.generic<IProvenance>(\n (from: unknown): Result<IProvenance> =>\n knownProvenanceConverter.convert(from).onSuccess((known) => {\n // `from` is guaranteed to be a non-null object here — the known-field\n // converter only succeeds on objects. Spread the original keys first,\n // then the validated/normalized known fields on top, so extension keys\n // survive while the known fields carry their converted values.\n const merged: IProvenance = { ...(from as Record<string, unknown>), ...known };\n return succeed(merged);\n })\n);\n\n/**\n * Converter for an attributed {@link IEdge}.\n * @public\n */\nexport const edgeConverter: Converter<IEdge> = Converters.object<IEdge>(\n {\n type: Convert.linkType,\n target: Convert.memoryId,\n confidence: Converters.number.optional(),\n provenance: provenanceConverter.optional(),\n valid_at: Converters.number.optional(),\n invalid_at: numberOrNull.optional()\n },\n { optionalFields: ['confidence', 'provenance', 'valid_at', 'invalid_at'] }\n);\n\n/**\n * Converter for the optional {@link ITemporalBlock}.\n * @public\n */\nexport const temporalConverter: Converter<ITemporalBlock> = Converters.object<ITemporalBlock>(\n {\n valid_at: Converters.number.optional(),\n invalid_at: numberOrNull.optional()\n },\n { optionalFields: ['valid_at', 'invalid_at'] }\n);\n\n/**\n * Converter for the invariant {@link IMemoryEnvelope}. Validates a plain\n * object (e.g. parsed YAML frontmatter) into a typed envelope.\n * @public\n */\nexport const envelopeConverter: Converter<IMemoryEnvelope> = Converters.object<IMemoryEnvelope>(\n {\n id: Convert.memoryId,\n entityId: Convert.entityId,\n kind: Convert.kind,\n tags: Converters.arrayOf(Convert.tag),\n links: Converters.arrayOf(edgeConverter),\n created: Converters.number,\n updated: Converters.number,\n seq: Converters.number,\n contentHash: Converters.string,\n provenance: provenanceConverter,\n temporal: temporalConverter.optional(),\n embeddingRef: stringOrNull.optional()\n },\n { optionalFields: ['temporal', 'embeddingRef'] }\n);\n\n/**\n * Converter that parses a YAML frontmatter string into an\n * {@link IMemoryEnvelope}.\n * @public\n */\nexport const envelopeYamlConverter: Converter<IMemoryEnvelope> = Yaml.yamlConverter(envelopeConverter);\n\n/** The frontmatter delimiter line. */\nconst FRONTMATTER_DELIMITER: string = '---';\n\n/**\n * The two parts of a memory file: the YAML frontmatter (between the `---`\n * delimiters) and the markdown body (everything after the closing delimiter).\n * @public\n */\nexport interface IMemoryFileParts {\n /** The raw YAML frontmatter (delimiters stripped). */\n readonly frontmatter: string;\n /** The raw body text following the closing delimiter. */\n readonly body: string;\n}\n\n/**\n * Split a `---\\n<yaml>\\n---\\n<body>` memory file into its frontmatter and\n * body parts. Pure string handling — no external dependency.\n * @public\n */\nexport function splitFrontmatter(raw: string): Result<IMemoryFileParts> {\n // Split on '\\n' and strip a trailing '\\r' per line so CRLF-authored files\n // parse identically to LF — otherwise the '\\r' would ride along into the\n // returned frontmatter (perturbing YAML parsing) and body (corrupting\n // round-trip fidelity).\n const lines: string[] = raw.split('\\n').map((line) => (line.endsWith('\\r') ? line.slice(0, -1) : line));\n if (lines[0].trim() !== FRONTMATTER_DELIMITER) {\n return fail(\"memory file: missing opening frontmatter delimiter '---'\");\n }\n let closeIndex: number = -1;\n for (let i = 1; i < lines.length; i++) {\n if (lines[i].trim() === FRONTMATTER_DELIMITER) {\n closeIndex = i;\n break;\n }\n }\n if (closeIndex === -1) {\n return fail(\"memory file: missing closing frontmatter delimiter '---'\");\n }\n return succeed({\n frontmatter: lines.slice(1, closeIndex).join('\\n'),\n body: lines.slice(closeIndex + 1).join('\\n')\n });\n}\n\n/**\n * Join a YAML frontmatter string and a body into the canonical\n * `---\\n<yaml>\\n---\\n<body>` memory-file format.\n * @public\n */\nexport function joinFrontmatter(frontmatter: string, body: string): string {\n const normalized: string = frontmatter.endsWith('\\n') ? frontmatter : `${frontmatter}\\n`;\n return `${FRONTMATTER_DELIMITER}\\n${normalized}${FRONTMATTER_DELIMITER}\\n${body}`;\n}\n\n/**\n * Parse a complete memory file into a typed {@link IMemoryRecord}. Splits the\n * frontmatter, validates the envelope, and dispatches the body through the\n * registered Converter for the envelope's kind.\n * @public\n */\nexport function parseMemoryFile(\n raw: string,\n registry: IBodyConverterRegistry\n): Result<IMemoryRecord<unknown>> {\n return splitFrontmatter(raw).onSuccess((parts) =>\n envelopeYamlConverter\n .convert(parts.frontmatter)\n .withErrorFormat((msg) => `memory file: invalid envelope: ${msg}`)\n .onSuccess((envelope) =>\n registry\n .convert(envelope.kind, parts.body)\n .withErrorFormat((msg) => `memory file '${envelope.id}': invalid body: ${msg}`)\n .onSuccess((body) => succeed({ envelope, body }))\n )\n );\n}\n\n/**\n * Serialize an envelope and its rendered body text into a memory file. The\n * envelope is emitted as YAML frontmatter; the body is written verbatim after\n * the closing delimiter.\n * @public\n */\nexport function serializeMemoryFile(envelope: IMemoryEnvelope, body: string): Result<string> {\n return Yaml.yamlStringify(envelope)\n .withErrorFormat((msg) => `memory file '${envelope.id}': failed to serialize envelope: ${msg}`)\n .onSuccess((frontmatter) => succeed(joinFrontmatter(frontmatter, body)));\n}\n"]}
@@ -0,0 +1,7 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+ export * from './bodyConverterRegistry';
6
+ export * from './envelopeConverter';
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/converters/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,cAAc,yBAAyB,CAAC;AACxC,cAAc,qBAAqB,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nexport * from './bodyConverterRegistry';\nexport * from './envelopeConverter';\n"]}
@@ -0,0 +1,6 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+ export * from './memoryIndex';
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/index/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,cAAc,eAAe,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nexport * from './memoryIndex';\n"]}
@@ -0,0 +1,170 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+ import { succeed } from '@fgv/ts-utils';
6
+ /** Shared empty key set for `byKind` / `byTag` misses (avoids per-call allocation). */
7
+ const EMPTY_KEY_SET = new Set();
8
+ /**
9
+ * Default in-memory {@link IMemoryIndex}. Maintains the derived `byKind` /
10
+ * `byTag` / `byRecency` / `backlinks` views incrementally; a `'put'` for an
11
+ * already-indexed key first removes the prior entry's associations so a changed
12
+ * kind / tag / link set never leaves a stale reference behind.
13
+ * @public
14
+ */
15
+ export class MemoryIndex {
16
+ constructor() {
17
+ this._byKey = new Map();
18
+ this._byKind = new Map();
19
+ this._byTag = new Map();
20
+ this._backlinks = new Map();
21
+ }
22
+ /** Family-convention factory. */
23
+ static create() {
24
+ return succeed(new MemoryIndex());
25
+ }
26
+ /**
27
+ * The composite primary key for an entry: scope + id, NUL-separated. NUL
28
+ * is excluded from both components (scope segments pass
29
+ * `assertPortableFilenameStem`; `MemoryId` is portable-filename-safe), so it
30
+ * is a collision-proof separator across every scope/id pair the codecs produce.
31
+ */
32
+ static _keyOf(scope, id) {
33
+ return `${scope}\0${id}`;
34
+ }
35
+ /** {@inheritDoc IMemoryIndex.rebuild} */
36
+ rebuild(entries) {
37
+ this._byKey.clear();
38
+ this._byKind.clear();
39
+ this._byTag.clear();
40
+ this._backlinks.clear();
41
+ for (const entry of entries) {
42
+ this._add(entry);
43
+ }
44
+ return succeed(this._byKey.size);
45
+ }
46
+ /** {@inheritDoc IMemoryIndex.patch} */
47
+ patch(op, entry) {
48
+ const key = MemoryIndex._keyOf(entry.scope, entry.record.envelope.id);
49
+ // Always drop any prior associations for this key first, so a 'put' that
50
+ // changes kind/tags/links cannot strand a stale reference.
51
+ this._remove(key);
52
+ if (op === 'put') {
53
+ this._add(entry);
54
+ }
55
+ return succeed(entry);
56
+ }
57
+ /** {@inheritDoc IMemoryIndex.entries} */
58
+ entries() {
59
+ return Array.from(this._byKey.values());
60
+ }
61
+ /** {@inheritDoc IMemoryIndex.byKind} */
62
+ byKind(kind) {
63
+ var _a;
64
+ return this._recencyOrdered((_a = this._byKind.get(kind)) !== null && _a !== void 0 ? _a : EMPTY_KEY_SET);
65
+ }
66
+ /** {@inheritDoc IMemoryIndex.byTag} */
67
+ byTag(tag) {
68
+ var _a;
69
+ return this._recencyOrdered((_a = this._byTag.get(tag)) !== null && _a !== void 0 ? _a : EMPTY_KEY_SET);
70
+ }
71
+ /** {@inheritDoc IMemoryIndex.byRecency} */
72
+ byRecency() {
73
+ return this._recencyOrdered(this._byKey.keys());
74
+ }
75
+ /** {@inheritDoc IMemoryIndex.backlinks} */
76
+ backlinks(target) {
77
+ const sources = this._backlinks.get(target);
78
+ return sources === undefined ? [] : Array.from(sources.values());
79
+ }
80
+ /**
81
+ * Resolve a set of composite keys to their records, ordered
82
+ * most-recently-updated first (with a `seq` tiebreak so equal-`updated`
83
+ * records sort deterministically).
84
+ */
85
+ _recencyOrdered(keys) {
86
+ const records = [];
87
+ for (const key of keys) {
88
+ const entry = this._byKey.get(key);
89
+ if (entry !== undefined) {
90
+ records.push(entry.record);
91
+ }
92
+ }
93
+ return records.sort((a, b) => {
94
+ const byUpdated = b.envelope.updated - a.envelope.updated;
95
+ return byUpdated !== 0 ? byUpdated : b.envelope.seq - a.envelope.seq;
96
+ });
97
+ }
98
+ /** Insert an entry and register all its derived associations. */
99
+ _add(entry) {
100
+ const key = MemoryIndex._keyOf(entry.scope, entry.record.envelope.id);
101
+ const envelope = entry.record.envelope;
102
+ this._byKey.set(key, entry);
103
+ this._addToSetMap(this._byKind, envelope.kind, key);
104
+ for (const tag of envelope.tags) {
105
+ this._addToSetMap(this._byTag, tag, key);
106
+ }
107
+ for (const edge of envelope.links) {
108
+ this._addBacklink(edge.target, key, envelope.id);
109
+ }
110
+ }
111
+ /** Remove the entry at `key` (if present) and all its derived associations. */
112
+ _remove(key) {
113
+ const entry = this._byKey.get(key);
114
+ if (entry === undefined) {
115
+ return;
116
+ }
117
+ const envelope = entry.record.envelope;
118
+ this._byKey.delete(key);
119
+ this._removeFromSetMap(this._byKind, envelope.kind, key);
120
+ for (const tag of envelope.tags) {
121
+ this._removeFromSetMap(this._byTag, tag, key);
122
+ }
123
+ for (const edge of envelope.links) {
124
+ this._removeBacklink(edge.target, key);
125
+ }
126
+ }
127
+ /** Register `sourceId` (keyed by its composite `sourceKey`) as linking at `target`. */
128
+ _addBacklink(target, sourceKey, sourceId) {
129
+ const existing = this._backlinks.get(target);
130
+ if (existing === undefined) {
131
+ this._backlinks.set(target, new Map([[sourceKey, sourceId]]));
132
+ }
133
+ else {
134
+ existing.set(sourceKey, sourceId);
135
+ }
136
+ }
137
+ /** Drop the backlink from `sourceKey` to `target`, removing the target map when empty. */
138
+ _removeBacklink(target, sourceKey) {
139
+ const existing = this._backlinks.get(target);
140
+ if (existing === undefined) {
141
+ return;
142
+ }
143
+ existing.delete(sourceKey);
144
+ if (existing.size === 0) {
145
+ this._backlinks.delete(target);
146
+ }
147
+ }
148
+ /** Add `member` to the set at `mapKey`, creating the set on first use. */
149
+ _addToSetMap(map, mapKey, member) {
150
+ const existing = map.get(mapKey);
151
+ if (existing === undefined) {
152
+ map.set(mapKey, new Set([member]));
153
+ }
154
+ else {
155
+ existing.add(member);
156
+ }
157
+ }
158
+ /** Remove `member` from the set at `mapKey`, dropping the set when empty. */
159
+ _removeFromSetMap(map, mapKey, member) {
160
+ const existing = map.get(mapKey);
161
+ if (existing === undefined) {
162
+ return;
163
+ }
164
+ existing.delete(member);
165
+ if (existing.size === 0) {
166
+ map.delete(mapKey);
167
+ }
168
+ }
169
+ }
170
+ //# sourceMappingURL=memoryIndex.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memoryIndex.js","sourceRoot":"","sources":["../../../src/packlets/index/memoryIndex.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAU,OAAO,EAAE,MAAM,eAAe,CAAC;AAUhD,uFAAuF;AACvF,MAAM,aAAa,GAAwB,IAAI,GAAG,EAAU,CAAC;AAgE7D;;;;;;GAMG;AACH,MAAM,OAAO,WAAW;IAetB;QACE,IAAI,CAAC,MAAM,GAAG,IAAI,GAAG,EAAgC,CAAC;QACtD,IAAI,CAAC,OAAO,GAAG,IAAI,GAAG,EAAqB,CAAC;QAC5C,IAAI,CAAC,MAAM,GAAG,IAAI,GAAG,EAAoB,CAAC;QAC1C,IAAI,CAAC,UAAU,GAAG,IAAI,GAAG,EAAmC,CAAC;IAC/D,CAAC;IAED,iCAAiC;IAC1B,MAAM,CAAC,MAAM;QAClB,OAAO,OAAO,CAAC,IAAI,WAAW,EAAE,CAAC,CAAC;IACpC,CAAC;IAED;;;;;OAKG;IACK,MAAM,CAAC,MAAM,CAAC,KAAqB,EAAE,EAAY;QACvD,OAAO,GAAG,KA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MAAM,CAAC,CAAC,CAAC,CAAC;QACxC,CAAC;aAAM,CAAC;YACN,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;IAED,6EAA6E;IACrE,iBAAiB,CAAO,GAAmB,EAAE,MAAS,EAAE,MAAS;QACvE,MAAM,QAAQ,GAAuB,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACrD,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,OAAO;QACT,CAAC;QACD,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QACxB,IAAI,QAAQ,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;YACxB,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QACrB,CAAC;IACH,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result, succeed } from '@fgv/ts-utils';\nimport { IMemoryRecord, Kind, MemoryId, MemoryScopeKey, Tag } from '../types';\n\n/**\n * The mutation a {@link IMemoryIndex.patch | patch} applies: a record was\n * written (`'put'`) or removed (`'delete'`).\n * @public\n */\nexport type MemoryIndexPatchOp = 'put' | 'delete';\n\n/** Shared empty key set for `byKind` / `byTag` misses (avoids per-call allocation). */\nconst EMPTY_KEY_SET: ReadonlySet<string> = new Set<string>();\n\n/**\n * A memory record paired with the {@link MemoryScopeKey | scope} it lives\n * under. The scope is not carried on the {@link IMemoryEnvelope} (it is derived\n * from the entity id by the codec), so the store threads it alongside the\n * record when patching or rebuilding the index. The `(scope, id)` pair is the\n * index's primary key, keeping records distinct across scopes that reuse a\n * filename stem (e.g. `turn-0` under different conversations in Phase C).\n * @public\n */\nexport interface IIndexedMemoryRecord {\n /** The scope the record is stored under. */\n readonly scope: MemoryScopeKey;\n /** The memory record itself. */\n readonly record: IMemoryRecord<unknown>;\n}\n\n/**\n * The derived, in-memory secondary indexes the store maintains over its\n * records. Never the source of truth — the FileTree is. The index is fully\n * rebuildable from a walk of the store ({@link IMemoryIndex.rebuild}) and is\n * patched incrementally on every write ({@link IMemoryIndex.patch}).\n *\n * @remarks\n * B1 builds the maps; link-traversal BFS over {@link IMemoryIndex.backlinks}\n * is B2. The accessors return records (not bare ids) so the B2 retrievers can\n * consume them directly.\n * @public\n */\nexport interface IMemoryIndex {\n /**\n * Replace the entire index from a full set of records (a store walk).\n * @returns The number of records indexed.\n */\n rebuild(entries: ReadonlyArray<IIndexedMemoryRecord>): Result<number>;\n\n /**\n * Apply a single incremental change. `'put'` inserts or replaces the entry\n * at its `(scope, id)` key (removing any prior associations first); `'delete'`\n * removes it.\n * @returns The entry that was applied.\n */\n patch(op: MemoryIndexPatchOp, entry: IIndexedMemoryRecord): Result<IIndexedMemoryRecord>;\n\n /** Every indexed entry (scope + record). Primary read surface for the store. */\n entries(): ReadonlyArray<IIndexedMemoryRecord>;\n\n /** Records of the given kind, in recency order (most-recently-updated first). */\n byKind(kind: Kind): ReadonlyArray<IMemoryRecord<unknown>>;\n\n /** Records carrying the given tag, in recency order. */\n byTag(tag: Tag): ReadonlyArray<IMemoryRecord<unknown>>;\n\n /** All records in recency order (most-recently-updated first). */\n byRecency(): ReadonlyArray<IMemoryRecord<unknown>>;\n\n /**\n * The ids of records whose `links` point AT `target` (inbound edges).\n * The seed map for B2 link-traversal.\n */\n backlinks(target: MemoryId): ReadonlyArray<MemoryId>;\n}\n\n/**\n * Default in-memory {@link IMemoryIndex}. Maintains the derived `byKind` /\n * `byTag` / `byRecency` / `backlinks` views incrementally; a `'put'` for an\n * already-indexed key first removes the prior entry's associations so a changed\n * kind / tag / link set never leaves a stale reference behind.\n * @public\n */\nexport class MemoryIndex implements IMemoryIndex {\n /** Primary store: `(scope, id)` composite key → indexed entry. */\n private readonly _byKey: Map<string, IIndexedMemoryRecord>;\n /** kind → set of composite keys. */\n private readonly _byKind: Map<Kind, Set<string>>;\n /** tag → set of composite keys. */\n private readonly _byTag: Map<Tag, Set<string>>;\n /**\n * link target id → (source composite key → source id). Keyed by the source's\n * `(scope, id)` composite — NOT its bare id — so two distinct source records\n * that share an id across scopes (e.g. `turn-0` in different conversations)\n * are tracked independently and removing one never drops the other's edge.\n */\n private readonly _backlinks: Map<MemoryId, Map<string, MemoryId>>;\n\n private constructor() {\n this._byKey = new Map<string, IIndexedMemoryRecord>();\n this._byKind = new Map<Kind, Set<string>>();\n this._byTag = new Map<Tag, Set<string>>();\n this._backlinks = new Map<MemoryId, Map<string, MemoryId>>();\n }\n\n /** Family-convention factory. */\n public static create(): Result<MemoryIndex> {\n return succeed(new MemoryIndex());\n }\n\n /**\n * The composite primary key for an entry: scope + id, NUL-separated. NUL\n * is excluded from both components (scope segments pass\n * `assertPortableFilenameStem`; `MemoryId` is portable-filename-safe), so it\n * is a collision-proof separator across every scope/id pair the codecs produce.\n */\n private static _keyOf(scope: MemoryScopeKey, id: MemoryId): string {\n return `${scope}\\0${id}`;\n }\n\n /** {@inheritDoc IMemoryIndex.rebuild} */\n public rebuild(entries: ReadonlyArray<IIndexedMemoryRecord>): Result<number> {\n this._byKey.clear();\n this._byKind.clear();\n this._byTag.clear();\n this._backlinks.clear();\n for (const entry of entries) {\n this._add(entry);\n }\n return succeed(this._byKey.size);\n }\n\n /** {@inheritDoc IMemoryIndex.patch} */\n public patch(op: MemoryIndexPatchOp, entry: IIndexedMemoryRecord): Result<IIndexedMemoryRecord> {\n const key: string = MemoryIndex._keyOf(entry.scope, entry.record.envelope.id);\n // Always drop any prior associations for this key first, so a 'put' that\n // changes kind/tags/links cannot strand a stale reference.\n this._remove(key);\n if (op === 'put') {\n this._add(entry);\n }\n return succeed(entry);\n }\n\n /** {@inheritDoc IMemoryIndex.entries} */\n public entries(): ReadonlyArray<IIndexedMemoryRecord> {\n return Array.from(this._byKey.values());\n }\n\n /** {@inheritDoc IMemoryIndex.byKind} */\n public byKind(kind: Kind): ReadonlyArray<IMemoryRecord<unknown>> {\n return this._recencyOrdered(this._byKind.get(kind) ?? EMPTY_KEY_SET);\n }\n\n /** {@inheritDoc IMemoryIndex.byTag} */\n public byTag(tag: Tag): ReadonlyArray<IMemoryRecord<unknown>> {\n return this._recencyOrdered(this._byTag.get(tag) ?? EMPTY_KEY_SET);\n }\n\n /** {@inheritDoc IMemoryIndex.byRecency} */\n public byRecency(): ReadonlyArray<IMemoryRecord<unknown>> {\n return this._recencyOrdered(this._byKey.keys());\n }\n\n /** {@inheritDoc IMemoryIndex.backlinks} */\n public backlinks(target: MemoryId): ReadonlyArray<MemoryId> {\n const sources: Map<string, MemoryId> | undefined = this._backlinks.get(target);\n return sources === undefined ? [] : Array.from(sources.values());\n }\n\n /**\n * Resolve a set of composite keys to their records, ordered\n * most-recently-updated first (with a `seq` tiebreak so equal-`updated`\n * records sort deterministically).\n */\n private _recencyOrdered(keys: Iterable<string>): ReadonlyArray<IMemoryRecord<unknown>> {\n const records: IMemoryRecord<unknown>[] = [];\n for (const key of keys) {\n const entry: IIndexedMemoryRecord | undefined = this._byKey.get(key);\n if (entry !== undefined) {\n records.push(entry.record);\n }\n }\n return records.sort((a, b) => {\n const byUpdated: number = b.envelope.updated - a.envelope.updated;\n return byUpdated !== 0 ? byUpdated : b.envelope.seq - a.envelope.seq;\n });\n }\n\n /** Insert an entry and register all its derived associations. */\n private _add(entry: IIndexedMemoryRecord): void {\n const key: string = MemoryIndex._keyOf(entry.scope, entry.record.envelope.id);\n const envelope: IMemoryRecord<unknown>['envelope'] = entry.record.envelope;\n this._byKey.set(key, entry);\n this._addToSetMap(this._byKind, envelope.kind, key);\n for (const tag of envelope.tags) {\n this._addToSetMap(this._byTag, tag, key);\n }\n for (const edge of envelope.links) {\n this._addBacklink(edge.target, key, envelope.id);\n }\n }\n\n /** Remove the entry at `key` (if present) and all its derived associations. */\n private _remove(key: string): void {\n const entry: IIndexedMemoryRecord | undefined = this._byKey.get(key);\n if (entry === undefined) {\n return;\n }\n const envelope: IMemoryRecord<unknown>['envelope'] = entry.record.envelope;\n this._byKey.delete(key);\n this._removeFromSetMap(this._byKind, envelope.kind, key);\n for (const tag of envelope.tags) {\n this._removeFromSetMap(this._byTag, tag, key);\n }\n for (const edge of envelope.links) {\n this._removeBacklink(edge.target, key);\n }\n }\n\n /** Register `sourceId` (keyed by its composite `sourceKey`) as linking at `target`. */\n private _addBacklink(target: MemoryId, sourceKey: string, sourceId: MemoryId): void {\n const existing: Map<string, MemoryId> | undefined = this._backlinks.get(target);\n if (existing === undefined) {\n this._backlinks.set(target, new Map<string, MemoryId>([[sourceKey, sourceId]]));\n } else {\n existing.set(sourceKey, sourceId);\n }\n }\n\n /** Drop the backlink from `sourceKey` to `target`, removing the target map when empty. */\n private _removeBacklink(target: MemoryId, sourceKey: string): void {\n const existing: Map<string, MemoryId> | undefined = this._backlinks.get(target);\n if (existing === undefined) {\n return;\n }\n existing.delete(sourceKey);\n if (existing.size === 0) {\n this._backlinks.delete(target);\n }\n }\n\n /** Add `member` to the set at `mapKey`, creating the set on first use. */\n private _addToSetMap<K, M>(map: Map<K, Set<M>>, mapKey: K, member: M): void {\n const existing: Set<M> | undefined = map.get(mapKey);\n if (existing === undefined) {\n map.set(mapKey, new Set<M>([member]));\n } else {\n existing.add(member);\n }\n }\n\n /** Remove `member` from the set at `mapKey`, dropping the set when empty. */\n private _removeFromSetMap<K, M>(map: Map<K, Set<M>>, mapKey: K, member: M): void {\n const existing: Set<M> | undefined = map.get(mapKey);\n if (existing === undefined) {\n return;\n }\n existing.delete(member);\n if (existing.size === 0) {\n map.delete(mapKey);\n }\n }\n}\n"]}
@@ -0,0 +1,7 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+ export * from './observer';
6
+ export * from './memoryObservationStore';
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/observe/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nexport * from './observer';\nexport * from './memoryObservationStore';\n"]}
@@ -0,0 +1,119 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+ import { Collections, fail, succeed } from '@fgv/ts-utils';
6
+ /**
7
+ * The default in-memory observation store: an {@link IMemoryObserver} that
8
+ * retains the records it observes in a bounded ring and answers schema-aware
9
+ * {@link MemoryObservationStore.query | queries} over them.
10
+ *
11
+ * @remarks
12
+ * **Privacy posture — this store is most-permissive by design.** It retains
13
+ * every field of every record verbatim, including any `provenance` and
14
+ * `querySnapshot`. The library bakes in **no** redaction, retention, or
15
+ * field-stripping policy — that is deployment policy, not library policy. A
16
+ * deployment that must redact wraps this store with its own
17
+ * {@link IMemoryObserver} that transforms records before forwarding, or
18
+ * substitutes a different observer entirely. Size is the only bounded
19
+ * dimension, via `maxRecords`.
20
+ *
21
+ * The store composes `RetainingRingBuffer` from `@fgv/ts-utils` (it does not
22
+ * hand-roll a ring) and implements {@link IMemoryObserver} directly — `observe`
23
+ * (the hook) and `query` (the read surface) live on the same class. Wire it via
24
+ * {@link IFileTreeMemoryStoreCreateParams.observers}. `seq` and `timestamp` are
25
+ * assigned by the firing authority (the store) before `observe`, so this store
26
+ * never mints them.
27
+ * @public
28
+ */
29
+ export class MemoryObservationStore {
30
+ /**
31
+ * @param buffer - The pre-constructed backing ring buffer.
32
+ * @internal
33
+ */
34
+ constructor(buffer) {
35
+ this._buffer = buffer;
36
+ }
37
+ /**
38
+ * The highest `seq` observed so far. Hold this value and pass it as
39
+ * `sinceSeq` to {@link MemoryObservationStore.query | query} to page only
40
+ * records observed afterward. Stable across ring eviction and
41
+ * {@link MemoryObservationStore.clear | clear}.
42
+ */
43
+ get lastSeq() {
44
+ return this._buffer.lastSeq;
45
+ }
46
+ /**
47
+ * The number of records currently retained.
48
+ */
49
+ get size() {
50
+ return this._buffer.size;
51
+ }
52
+ /**
53
+ * Family-convention factory.
54
+ * @param params - {@link IMemoryObservationStoreCreateParams | Construction options}.
55
+ * @returns On success, a new store. Fails if `maxRecords` is supplied and is
56
+ * not a positive integer.
57
+ */
58
+ static create(params) {
59
+ const maxRecords = params === null || params === void 0 ? void 0 : params.maxRecords;
60
+ if (maxRecords !== undefined && (!Number.isInteger(maxRecords) || maxRecords < 1)) {
61
+ return fail(`MemoryObservationStore: maxRecords must be a positive integer (got ${maxRecords})`);
62
+ }
63
+ return succeed(new MemoryObservationStore(new Collections.RetainingRingBuffer({ maxRecords })));
64
+ }
65
+ /**
66
+ * {@inheritDoc IMemoryObserver.observe}
67
+ */
68
+ observe(record) {
69
+ this._buffer.push(record);
70
+ return Promise.resolve(succeed(record));
71
+ }
72
+ /**
73
+ * Returns retained records, oldest-first, narrowed by the supplied criteria.
74
+ * @param criteria - {@link IMemoryObservationQuery | AND-combined filter criteria}.
75
+ * @returns The matching records, oldest-first.
76
+ */
77
+ query(criteria) {
78
+ return this._buffer.query({
79
+ sinceSeq: criteria === null || criteria === void 0 ? void 0 : criteria.sinceSeq,
80
+ limit: criteria === null || criteria === void 0 ? void 0 : criteria.limit,
81
+ filter: criteria === undefined ? undefined : (record) => MemoryObservationStore._matches(record, criteria)
82
+ });
83
+ }
84
+ /**
85
+ * Clears all retained records. Does NOT reset
86
+ * {@link MemoryObservationStore.lastSeq | lastSeq}, so a held `sinceSeq`
87
+ * cursor never re-sees a sequence number.
88
+ */
89
+ clear() {
90
+ this._buffer.clear();
91
+ }
92
+ /**
93
+ * Tests a record against the non-`seq`/`limit` criteria (those are applied by
94
+ * the ring buffer itself).
95
+ * @internal
96
+ */
97
+ static _matches(record, criteria) {
98
+ if (criteria.since !== undefined && record.timestamp < criteria.since) {
99
+ return false;
100
+ }
101
+ if (criteria.until !== undefined && record.timestamp > criteria.until) {
102
+ return false;
103
+ }
104
+ if (criteria.scope !== undefined && record.scope !== criteria.scope) {
105
+ return false;
106
+ }
107
+ if (criteria.kind !== undefined && record.kind !== criteria.kind) {
108
+ return false;
109
+ }
110
+ if (criteria.phase !== undefined && record.phase !== criteria.phase) {
111
+ return false;
112
+ }
113
+ if (criteria.outcome !== undefined && record.outcome !== criteria.outcome) {
114
+ return false;
115
+ }
116
+ return true;
117
+ }
118
+ }
119
+ //# sourceMappingURL=memoryObservationStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memoryObservationStore.js","sourceRoot":"","sources":["../../../src/packlets/observe/memoryObservationStore.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAU,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAenE;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,OAAO,sBAAsB;IASjC;;;OAGG;IACH,YAAoB,MAAiE;QACnF,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;IAED;;;;;OAKG;IACH,IAAW,OAAO;QAChB,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;IAC9B,CAAC;IAED;;OAEG;IACH,IAAW,IAAI;QACb,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IAC3B,CAAC;IAED;;;;;OAKG;IACI,MAAM,CAAC,MAAM,CAAC,MAA4C;QAC/D,MAAM,UAAU,GAAuB,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,UAAU,CAAC;QAC1D,IAAI,UAAU,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,UAAU,GAAG,CAAC,CAAC,EAAE,CAAC;YAClF,OAAO,IAAI,CAAC,sEAAsE,UAAU,GAAG,CAAC,CAAC;QACnG,CAAC;QACD,OAAO,OAAO,CACZ,IAAI,sBAAsB,CACxB,IAAI,WAAW,CAAC,mBAAmB,CAA2B,EAAE,UAAU,EAAE,CAAC,CAC9E,CACF,CAA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AAC,IAAI,KAAK,QAAQ,CAAC,IAAI,EAAE,CAAC;YACjE,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IAAI,QAAQ,CAAC,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK,KAAK,QAAQ,CAAC,KAAK,EAAE,CAAC;YACpE,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IAAI,QAAQ,CAAC,OAAO,KAAK,SAAS,IAAI,MAAM,CAAC,OAAO,KAAK,QAAQ,CAAC,OAAO,EAAE,CAAC;YAC1E,OAAO,KAAK,CAAC;QACf,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Collections, Result, fail, succeed } from '@fgv/ts-utils';\nimport { IMemoryObservationQuery, IMemoryObservationRecord, IMemoryObserver } from './observer';\n\n/**\n * Construction options for {@link MemoryObservationStore.create}.\n * @public\n */\nexport interface IMemoryObservationStoreCreateParams {\n /**\n * Maximum number of observation records retained before the oldest is\n * overwritten. Defaults to `1000`. Must be a positive integer if supplied.\n */\n readonly maxRecords?: number;\n}\n\n/**\n * The default in-memory observation store: an {@link IMemoryObserver} that\n * retains the records it observes in a bounded ring and answers schema-aware\n * {@link MemoryObservationStore.query | queries} over them.\n *\n * @remarks\n * **Privacy posture — this store is most-permissive by design.** It retains\n * every field of every record verbatim, including any `provenance` and\n * `querySnapshot`. The library bakes in **no** redaction, retention, or\n * field-stripping policy — that is deployment policy, not library policy. A\n * deployment that must redact wraps this store with its own\n * {@link IMemoryObserver} that transforms records before forwarding, or\n * substitutes a different observer entirely. Size is the only bounded\n * dimension, via `maxRecords`.\n *\n * The store composes `RetainingRingBuffer` from `@fgv/ts-utils` (it does not\n * hand-roll a ring) and implements {@link IMemoryObserver} directly — `observe`\n * (the hook) and `query` (the read surface) live on the same class. Wire it via\n * {@link IFileTreeMemoryStoreCreateParams.observers}. `seq` and `timestamp` are\n * assigned by the firing authority (the store) before `observe`, so this store\n * never mints them.\n * @public\n */\nexport class MemoryObservationStore implements IMemoryObserver {\n /**\n * The bounded ring of observed records. The firing authority assigns each\n * record's `seq`, so the ring's monotonic-`seq` cursor contract is satisfied\n * by that authority's per-instance counter.\n * @internal\n */\n private readonly _buffer: Collections.RetainingRingBuffer<IMemoryObservationRecord>;\n\n /**\n * @param buffer - The pre-constructed backing ring buffer.\n * @internal\n */\n private constructor(buffer: Collections.RetainingRingBuffer<IMemoryObservationRecord>) {\n this._buffer = buffer;\n }\n\n /**\n * The highest `seq` observed so far. Hold this value and pass it as\n * `sinceSeq` to {@link MemoryObservationStore.query | query} to page only\n * records observed afterward. Stable across ring eviction and\n * {@link MemoryObservationStore.clear | clear}.\n */\n public get lastSeq(): number {\n return this._buffer.lastSeq;\n }\n\n /**\n * The number of records currently retained.\n */\n public get size(): number {\n return this._buffer.size;\n }\n\n /**\n * Family-convention factory.\n * @param params - {@link IMemoryObservationStoreCreateParams | Construction options}.\n * @returns On success, a new store. Fails if `maxRecords` is supplied and is\n * not a positive integer.\n */\n public static create(params?: IMemoryObservationStoreCreateParams): Result<MemoryObservationStore> {\n const maxRecords: number | undefined = params?.maxRecords;\n if (maxRecords !== undefined && (!Number.isInteger(maxRecords) || maxRecords < 1)) {\n return fail(`MemoryObservationStore: maxRecords must be a positive integer (got ${maxRecords})`);\n }\n return succeed(\n new MemoryObservationStore(\n new Collections.RetainingRingBuffer<IMemoryObservationRecord>({ maxRecords })\n )\n );\n }\n\n /**\n * {@inheritDoc IMemoryObserver.observe}\n */\n public observe(record: IMemoryObservationRecord): Promise<Result<unknown>> {\n this._buffer.push(record);\n return Promise.resolve(succeed(record));\n }\n\n /**\n * Returns retained records, oldest-first, narrowed by the supplied criteria.\n * @param criteria - {@link IMemoryObservationQuery | AND-combined filter criteria}.\n * @returns The matching records, oldest-first.\n */\n public query(criteria?: IMemoryObservationQuery): ReadonlyArray<IMemoryObservationRecord> {\n return this._buffer.query({\n sinceSeq: criteria?.sinceSeq,\n limit: criteria?.limit,\n filter:\n criteria === undefined ? undefined : (record) => MemoryObservationStore._matches(record, criteria)\n });\n }\n\n /**\n * Clears all retained records. Does NOT reset\n * {@link MemoryObservationStore.lastSeq | lastSeq}, so a held `sinceSeq`\n * cursor never re-sees a sequence number.\n */\n public clear(): void {\n this._buffer.clear();\n }\n\n /**\n * Tests a record against the non-`seq`/`limit` criteria (those are applied by\n * the ring buffer itself).\n * @internal\n */\n private static _matches(record: IMemoryObservationRecord, criteria: IMemoryObservationQuery): boolean {\n if (criteria.since !== undefined && record.timestamp < criteria.since) {\n return false;\n }\n if (criteria.until !== undefined && record.timestamp > criteria.until) {\n return false;\n }\n if (criteria.scope !== undefined && record.scope !== criteria.scope) {\n return false;\n }\n if (criteria.kind !== undefined && record.kind !== criteria.kind) {\n return false;\n }\n if (criteria.phase !== undefined && record.phase !== criteria.phase) {\n return false;\n }\n if (criteria.outcome !== undefined && record.outcome !== criteria.outcome) {\n return false;\n }\n return true;\n }\n}\n"]}
@@ -0,0 +1,6 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=observer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observer.js","sourceRoot":"","sources":["../../../src/packlets/observe/observer.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result } from '@fgv/ts-utils';\nimport { IProvenance, Kind, MemoryId, MemoryScopeKey } from '../types';\n\n/**\n * The store/retriever operation an observation record describes.\n *\n * @remarks\n * `'read'` / `'write'` / `'delete'` are fired post-op by\n * {@link FileTreeMemoryStore} (on `get` / `put` / `delete` respectively) when\n * observers are wired. `'retrieve'` is reserved for retriever-fired\n * observations; no B2 retriever fires one (a single seq authority per\n * observation store is the supported topology), so it never appears in B2 but\n * is part of the vocabulary so a future retriever-firing hook is additive.\n * @public\n */\nexport type MemoryObservationPhase = 'read' | 'write' | 'delete' | 'retrieve';\n\n/**\n * The outcome of the observed operation.\n * @public\n */\nexport type MemoryObservationOutcome = 'success' | 'failure';\n\n/**\n * A single audit record produced by an observed store (or retriever) operation.\n *\n * @remarks\n * `seq` and `timestamp` are assigned by the firing authority (the store) before\n * fan-out, so the same record carries the same `seq` across every observer it\n * lands in. `seq` is strictly increasing per authority, satisfying the\n * `RetainingRingBuffer` cursor contract that {@link MemoryObservationStore}\n * relies on.\n * @public\n */\nexport interface IMemoryObservationRecord {\n /**\n * Monotonic 1-based sequence number assigned by the firing authority, stable\n * across a store's ring eviction. The ordering / paging key.\n */\n readonly seq: number;\n /** Milliseconds since epoch when the firing authority produced the record. */\n readonly timestamp: number;\n /** Which operation this record describes. */\n readonly phase: MemoryObservationPhase;\n /** The scope the operation touched, when resolvable. */\n readonly scope?: MemoryScopeKey;\n /** The record id the operation touched, when resolvable. */\n readonly id?: MemoryId;\n /** The kind the operation targeted, when known. */\n readonly kind?: Kind;\n /** Whether the operation succeeded. */\n readonly outcome: MemoryObservationOutcome;\n /** Present on failure: the failure `Result`'s message. */\n readonly error?: string;\n /** Structured provenance of the write, when the operation carried one. */\n readonly provenance?: IProvenance;\n /**\n * For `'retrieve'` observations: an opaque snapshot of the query that drove\n * the retrieval. Carried verbatim; never interpreted by the store.\n */\n readonly querySnapshot?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Single-method async observer hook. The store fires `observe` once per public\n * `get` / `put` / `delete` call when observers are wired.\n *\n * @remarks\n * Observer errors never affect the store operation — the store swallows a\n * failed `Result` or a thrown / rejected `observe`, logging it to the injected\n * diagnostic logger at `warn`.\n * @public\n */\nexport interface IMemoryObserver {\n /**\n * When `true`, the store dispatches `observe` without awaiting it, so a slow\n * remote observer (SIEM, network sink) does not extend the store operation's\n * latency. Defaults to `false` (awaited), which is correct for the cheap\n * in-memory default {@link MemoryObservationStore}. Errors are swallowed\n * either way.\n */\n readonly fireAndForget?: boolean;\n /**\n * Receives a fully-formed observation record.\n * @param record - The observation record.\n * @returns A `Result` whose failure is swallowed (logged to the store's\n * diagnostic logger). A rejected promise is likewise swallowed.\n */\n observe(record: IMemoryObservationRecord): Promise<Result<unknown>>;\n}\n\n/**\n * Query criteria for {@link MemoryObservationStore.query}. All supplied criteria\n * are AND-combined.\n * @public\n */\nexport interface IMemoryObservationQuery {\n /** Only records with `seq > sinceSeq` (incremental paging cursor). */\n readonly sinceSeq?: number;\n /** Return at most this many records — the most-recent N, still oldest-first. */\n readonly limit?: number;\n /** Only records with `timestamp >= since`. */\n readonly since?: number;\n /** Only records with `timestamp <= until`. */\n readonly until?: number;\n /** Only records that touched this scope. */\n readonly scope?: MemoryScopeKey;\n /** Only records that targeted this kind. */\n readonly kind?: Kind;\n /** Only records of this phase. */\n readonly phase?: MemoryObservationPhase;\n /** Only records with this outcome. */\n readonly outcome?: MemoryObservationOutcome;\n}\n"]}
@@ -0,0 +1,135 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+ import { fail, mapResults, succeed } from '@fgv/ts-utils';
6
+ import { guardRetrieverCapabilities, limitRecords, recencyCompare } from './retriever';
7
+ /**
8
+ * The reference {@link IMergeStrategy}: a score-union. Every record is scored by
9
+ * the number of composed result sets it appears in (deduplicated by
10
+ * {@link IMemoryEnvelope.id | id}); the merged result is ordered by descending
11
+ * score, then by recency. Records surfaced by more retrievers rank higher.
12
+ *
13
+ * @remarks
14
+ * Dedup is by `id` alone, which is unambiguous for the flat (one-file-per-entity)
15
+ * kinds B2 ships. Phase-C versioned kinds that reuse a stem across scopes will
16
+ * extend the dedup key — additive, no API change.
17
+ * @public
18
+ */
19
+ export class ScoreUnionMergeStrategy {
20
+ constructor() { }
21
+ /** Family-convention factory. */
22
+ static create() {
23
+ return succeed(new ScoreUnionMergeStrategy());
24
+ }
25
+ /** {@inheritDoc IMergeStrategy.merge} */
26
+ merge(resultSets) {
27
+ const scored = new Map();
28
+ for (const set of resultSets) {
29
+ // Count each id at most once per result set, so the score is "how many
30
+ // retrievers surfaced this record" rather than "how many copies total".
31
+ const seenInSet = new Set();
32
+ for (const record of set) {
33
+ const id = record.envelope.id;
34
+ if (seenInSet.has(id)) {
35
+ continue;
36
+ }
37
+ seenInSet.add(id);
38
+ const existing = scored.get(id);
39
+ if (existing === undefined) {
40
+ scored.set(id, { record, score: 1 });
41
+ }
42
+ else {
43
+ existing.score += 1;
44
+ }
45
+ }
46
+ }
47
+ const merged = Array.from(scored.values())
48
+ .sort((a, b) => (b.score !== a.score ? b.score - a.score : recencyCompare(a.record, b.record)))
49
+ .map((entry) => entry.record);
50
+ return succeed(merged);
51
+ }
52
+ }
53
+ /**
54
+ * Composes several retrievers, dispatches a query to each, and merges their
55
+ * results via an injectable {@link IMergeStrategy}. Its capabilities are the
56
+ * union of the composed retrievers' capabilities.
57
+ *
58
+ * @remarks
59
+ * The hybrid enforces the loud-degradation contract against its OWN (union)
60
+ * capabilities, then projects the query for each child: a child that does not
61
+ * support the `semantic` (or `asOf`) axis is handed a query with that axis
62
+ * stripped, so it returns its normal results instead of loud-failing on a field
63
+ * a sibling handles. A child that genuinely fails (e.g. a wired semantic backend
64
+ * erroring) propagates — the hybrid never silently drops a failure.
65
+ * @public
66
+ */
67
+ export class HybridRetriever {
68
+ constructor(retrievers, mergeStrategy, capabilities) {
69
+ this._retrievers = retrievers;
70
+ this._mergeStrategy = mergeStrategy;
71
+ this._capabilities = capabilities;
72
+ }
73
+ /** {@inheritDoc IMemoryRetriever.capabilities} */
74
+ get capabilities() {
75
+ return this._capabilities;
76
+ }
77
+ /**
78
+ * Family-convention factory.
79
+ * @param retrievers - The retrievers to compose (at least one).
80
+ * @param mergeStrategy - How to combine their results.
81
+ */
82
+ static create(retrievers, mergeStrategy) {
83
+ if (retrievers.length === 0) {
84
+ return fail('HybridRetriever: at least one retriever is required');
85
+ }
86
+ // Snapshot the caller's array so a later mutation cannot make `retrieve()`
87
+ // and the cached `capabilities` disagree.
88
+ const stableRetrievers = [...retrievers];
89
+ const capabilities = {
90
+ supportsSemanticRecall: stableRetrievers.some((r) => r.capabilities.supportsSemanticRecall),
91
+ supportsTemporalQuery: stableRetrievers.some((r) => r.capabilities.supportsTemporalQuery),
92
+ supportsLinkTraversal: stableRetrievers.some((r) => r.capabilities.supportsLinkTraversal)
93
+ };
94
+ return succeed(new HybridRetriever(stableRetrievers, mergeStrategy, capabilities));
95
+ }
96
+ /** {@inheritDoc IMemoryRetriever.retrieve} */
97
+ async retrieve(query) {
98
+ return guardRetrieverCapabilities(query, this._capabilities).thenOnSuccess(async () => {
99
+ const perRetriever = await Promise.all(this._retrievers.map((retriever) => retriever.retrieve(this._projectQuery(query, retriever))));
100
+ return mapResults(perRetriever)
101
+ .onSuccess((resultSets) => this._mergeStrategy.merge(resultSets))
102
+ .onSuccess((merged) => succeed(limitRecords(merged, query.limit)));
103
+ });
104
+ }
105
+ /**
106
+ * Project the query for one child retriever. Two adjustments:
107
+ *
108
+ * - Strip axes the child does not support (`semantic` / `topK` for a
109
+ * non-semantic child, `asOf` for a non-temporal child, the link axes for a
110
+ * non-link child) so it returns its normal results rather than loud-failing
111
+ * on a field a sibling handles.
112
+ * - Strip `limit` unconditionally: limit is a post-merge concern. A child that
113
+ * pre-truncated its result set would starve the merge strategy of candidates
114
+ * it needs to score correctly (a record both children would surface must
115
+ * reach the merge to score 2). The hybrid applies `limit` once, after merge.
116
+ */
117
+ _projectQuery(query, retriever) {
118
+ const projected = Object.assign({}, query);
119
+ delete projected.limit;
120
+ if (!retriever.capabilities.supportsSemanticRecall) {
121
+ delete projected.semantic;
122
+ delete projected.topK;
123
+ }
124
+ if (!retriever.capabilities.supportsTemporalQuery) {
125
+ delete projected.asOf;
126
+ }
127
+ if (!retriever.capabilities.supportsLinkTraversal) {
128
+ delete projected.linkedFrom;
129
+ delete projected.linkedTo;
130
+ delete projected.hops;
131
+ }
132
+ return projected;
133
+ }
134
+ }
135
+ //# sourceMappingURL=hybridRetriever.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hybridRetriever.js","sourceRoot":"","sources":["../../../src/packlets/retrieve/hybridRetriever.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAU,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAElE,OAAO,EAIL,0BAA0B,EAC1B,YAAY,EACZ,cAAc,EACf,MAAM,aAAa,CAAC;AAkBrB;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,uBAAuB;IAClC,gBAAuB,CAAC;IAExB,iCAAiC;IAC1B,MAAM,CAAC,MAAM;QAClB,OAAO,OAAO,CAAC,IAAI,uBAAuB,EAAE,CAAC,CAAC;IAChD,CAAC;IAED,yCAAyC;IAClC,KAAK,CACV,UAAgE;QAEhE,MAAM,MAAM,GAA8E,IAAI,GAAG,EAAE,CAAC;QACpG,KAAK,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;YAC7B,uEAAuE;YACvE,wEAAwE;YACxE,MAAM,SAAS,GAAkB,IAAI,GAAG,EAAY,CAAC;YACrD,KAAK,MAAM,MAAM,IAAI,GAAG,EAAE,CAAC;gBACzB,MAAM,EAAE,GAAa,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACxC,IAAI,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC;oBACtB,SAAS;gBACX,CAAC;gBACD,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;gBAClB,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;gBAChC,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;oBAC3B,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;gBACvC,CAAC;qBAAM,CAAC;oBACN,QAAQ,CAAC,KAAK,IAAI,CAAC,CAAC;gBACt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AO,SAAS,CAAC,QAAQ,CAAC;YAC1B,OAAO,SAAS,CAAC,IAAI,CAAC;QACxB,CAAC;QACD,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAC;YAClD,OAAO,SAAS,CAAC,IAAI,CAAC;QACxB,CAAC;QACD,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAC;YAClD,OAAO,SAAS,CAAC,UAAU,CAAC;YAC5B,OAAO,SAAS,CAAC,QAAQ,CAAC;YAC1B,OAAO,SAAS,CAAC,IAAI,CAAC;QACxB,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result, fail, mapResults, succeed } from '@fgv/ts-utils';\nimport { IMemoryRecord, MemoryId } from '../types';\nimport {\n IMemoryQuery,\n IMemoryRetriever,\n IMemoryRetrieverCapabilities,\n guardRetrieverCapabilities,\n limitRecords,\n recencyCompare\n} from './retriever';\n\n/**\n * Strategy for combining the result sets of the retrievers a\n * {@link HybridRetriever} composes. Injectable so a consumer can weight,\n * re-rank, or intersect instead of the default union.\n * @public\n */\nexport interface IMergeStrategy {\n /**\n * Merge the per-retriever result sets into a single ordered result.\n * @param resultSets - One entry per composed retriever, in composition order.\n */\n merge(\n resultSets: ReadonlyArray<ReadonlyArray<IMemoryRecord<unknown>>>\n ): Result<ReadonlyArray<IMemoryRecord<unknown>>>;\n}\n\n/**\n * The reference {@link IMergeStrategy}: a score-union. Every record is scored by\n * the number of composed result sets it appears in (deduplicated by\n * {@link IMemoryEnvelope.id | id}); the merged result is ordered by descending\n * score, then by recency. Records surfaced by more retrievers rank higher.\n *\n * @remarks\n * Dedup is by `id` alone, which is unambiguous for the flat (one-file-per-entity)\n * kinds B2 ships. Phase-C versioned kinds that reuse a stem across scopes will\n * extend the dedup key — additive, no API change.\n * @public\n */\nexport class ScoreUnionMergeStrategy implements IMergeStrategy {\n private constructor() {}\n\n /** Family-convention factory. */\n public static create(): Result<ScoreUnionMergeStrategy> {\n return succeed(new ScoreUnionMergeStrategy());\n }\n\n /** {@inheritDoc IMergeStrategy.merge} */\n public merge(\n resultSets: ReadonlyArray<ReadonlyArray<IMemoryRecord<unknown>>>\n ): Result<ReadonlyArray<IMemoryRecord<unknown>>> {\n const scored: Map<MemoryId, { readonly record: IMemoryRecord<unknown>; score: number }> = new Map();\n for (const set of resultSets) {\n // Count each id at most once per result set, so the score is \"how many\n // retrievers surfaced this record\" rather than \"how many copies total\".\n const seenInSet: Set<MemoryId> = new Set<MemoryId>();\n for (const record of set) {\n const id: MemoryId = record.envelope.id;\n if (seenInSet.has(id)) {\n continue;\n }\n seenInSet.add(id);\n const existing = scored.get(id);\n if (existing === undefined) {\n scored.set(id, { record, score: 1 });\n } else {\n existing.score += 1;\n }\n }\n }\n const merged: IMemoryRecord<unknown>[] = Array.from(scored.values())\n .sort((a, b) => (b.score !== a.score ? b.score - a.score : recencyCompare(a.record, b.record)))\n .map((entry) => entry.record);\n return succeed(merged);\n }\n}\n\n/**\n * Composes several retrievers, dispatches a query to each, and merges their\n * results via an injectable {@link IMergeStrategy}. Its capabilities are the\n * union of the composed retrievers' capabilities.\n *\n * @remarks\n * The hybrid enforces the loud-degradation contract against its OWN (union)\n * capabilities, then projects the query for each child: a child that does not\n * support the `semantic` (or `asOf`) axis is handed a query with that axis\n * stripped, so it returns its normal results instead of loud-failing on a field\n * a sibling handles. A child that genuinely fails (e.g. a wired semantic backend\n * erroring) propagates — the hybrid never silently drops a failure.\n * @public\n */\nexport class HybridRetriever implements IMemoryRetriever {\n private readonly _retrievers: ReadonlyArray<IMemoryRetriever>;\n private readonly _mergeStrategy: IMergeStrategy;\n private readonly _capabilities: IMemoryRetrieverCapabilities;\n\n private constructor(\n retrievers: ReadonlyArray<IMemoryRetriever>,\n mergeStrategy: IMergeStrategy,\n capabilities: IMemoryRetrieverCapabilities\n ) {\n this._retrievers = retrievers;\n this._mergeStrategy = mergeStrategy;\n this._capabilities = capabilities;\n }\n\n /** {@inheritDoc IMemoryRetriever.capabilities} */\n public get capabilities(): IMemoryRetrieverCapabilities {\n return this._capabilities;\n }\n\n /**\n * Family-convention factory.\n * @param retrievers - The retrievers to compose (at least one).\n * @param mergeStrategy - How to combine their results.\n */\n public static create(\n retrievers: ReadonlyArray<IMemoryRetriever>,\n mergeStrategy: IMergeStrategy\n ): Result<HybridRetriever> {\n if (retrievers.length === 0) {\n return fail('HybridRetriever: at least one retriever is required');\n }\n // Snapshot the caller's array so a later mutation cannot make `retrieve()`\n // and the cached `capabilities` disagree.\n const stableRetrievers: ReadonlyArray<IMemoryRetriever> = [...retrievers];\n const capabilities: IMemoryRetrieverCapabilities = {\n supportsSemanticRecall: stableRetrievers.some((r) => r.capabilities.supportsSemanticRecall),\n supportsTemporalQuery: stableRetrievers.some((r) => r.capabilities.supportsTemporalQuery),\n supportsLinkTraversal: stableRetrievers.some((r) => r.capabilities.supportsLinkTraversal)\n };\n return succeed(new HybridRetriever(stableRetrievers, mergeStrategy, capabilities));\n }\n\n /** {@inheritDoc IMemoryRetriever.retrieve} */\n public async retrieve(query: IMemoryQuery): Promise<Result<ReadonlyArray<IMemoryRecord<unknown>>>> {\n return guardRetrieverCapabilities(query, this._capabilities).thenOnSuccess(async () => {\n const perRetriever: Result<ReadonlyArray<IMemoryRecord<unknown>>>[] = await Promise.all(\n this._retrievers.map((retriever) => retriever.retrieve(this._projectQuery(query, retriever)))\n );\n return mapResults(perRetriever)\n .onSuccess((resultSets) => this._mergeStrategy.merge(resultSets))\n .onSuccess((merged) => succeed(limitRecords(merged, query.limit)));\n });\n }\n\n /**\n * Project the query for one child retriever. Two adjustments:\n *\n * - Strip axes the child does not support (`semantic` / `topK` for a\n * non-semantic child, `asOf` for a non-temporal child, the link axes for a\n * non-link child) so it returns its normal results rather than loud-failing\n * on a field a sibling handles.\n * - Strip `limit` unconditionally: limit is a post-merge concern. A child that\n * pre-truncated its result set would starve the merge strategy of candidates\n * it needs to score correctly (a record both children would surface must\n * reach the merge to score 2). The hybrid applies `limit` once, after merge.\n */\n private _projectQuery(query: IMemoryQuery, retriever: IMemoryRetriever): IMemoryQuery {\n const projected: { -readonly [K in keyof IMemoryQuery]: IMemoryQuery[K] } = { ...query };\n delete projected.limit;\n if (!retriever.capabilities.supportsSemanticRecall) {\n delete projected.semantic;\n delete projected.topK;\n }\n if (!retriever.capabilities.supportsTemporalQuery) {\n delete projected.asOf;\n }\n if (!retriever.capabilities.supportsLinkTraversal) {\n delete projected.linkedFrom;\n delete projected.linkedTo;\n delete projected.hops;\n }\n return projected;\n }\n}\n"]}
@@ -0,0 +1,12 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+ export * from './retriever';
6
+ export * from './recencyRetriever';
7
+ export * from './linkTraversalRetriever';
8
+ export * from './tagRetriever';
9
+ export * from './structuredFilterRetriever';
10
+ export * from './semanticRetriever';
11
+ export * from './hybridRetriever';
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/retrieve/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,cAAc,aAAa,CAAC;AAC5B,cAAc,oBAAoB,CAAC;AACnC,cAAc,0BAA0B,CAAC;AACzC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,6BAA6B,CAAC;AAC5C,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nexport * from './retriever';\nexport * from './recencyRetriever';\nexport * from './linkTraversalRetriever';\nexport * from './tagRetriever';\nexport * from './structuredFilterRetriever';\nexport * from './semanticRetriever';\nexport * from './hybridRetriever';\n"]}