@remnic/core 1.1.11 → 1.1.13

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 (1462) hide show
  1. package/README.md +3 -3
  2. package/dist/access-cli.d.ts +2 -1
  3. package/dist/access-cli.js +293 -104
  4. package/dist/access-cli.js.map +1 -1
  5. package/dist/access-http.d.ts +31 -62
  6. package/dist/access-http.js +53 -35
  7. package/dist/access-mcp.d.ts +31 -8
  8. package/dist/access-mcp.js +45 -34
  9. package/dist/access-schema.d.ts +197 -14
  10. package/dist/access-schema.js +16 -5
  11. package/dist/access-service-DcCDmNYC.d.ts +1542 -0
  12. package/dist/access-service.d.ts +30 -9
  13. package/dist/access-service.js +42 -32
  14. package/dist/action-confidence.d.ts +83 -0
  15. package/dist/action-confidence.js +22 -0
  16. package/dist/active-memory-bridge.d.ts +1 -1
  17. package/dist/active-memory-bridge.js +2 -2
  18. package/dist/active-recall.d.ts +1 -1
  19. package/dist/active-recall.js +11 -3
  20. package/dist/active-recall.js.map +1 -1
  21. package/dist/adapters/claude-code.d.ts +24 -0
  22. package/dist/adapters/claude-code.js +9 -0
  23. package/dist/adapters/codex.d.ts +25 -0
  24. package/dist/adapters/codex.js +9 -0
  25. package/dist/adapters/hermes.d.ts +35 -0
  26. package/dist/adapters/hermes.js +9 -0
  27. package/dist/adapters/index.d.ts +6 -0
  28. package/dist/adapters/index.js +26 -0
  29. package/dist/adapters/registry.d.ts +20 -0
  30. package/dist/adapters/registry.js +13 -0
  31. package/dist/adapters/replit.d.ts +28 -0
  32. package/dist/adapters/replit.js +9 -0
  33. package/dist/adapters/types.d.ts +43 -0
  34. package/dist/adapters/types.js +8 -0
  35. package/dist/behavior-learner.d.ts +1 -1
  36. package/dist/behavior-signals.d.ts +1 -1
  37. package/dist/bootstrap.d.ts +23 -6
  38. package/dist/boxes.d.ts +7 -0
  39. package/dist/boxes.js +1 -1
  40. package/dist/briefing.d.ts +5 -3
  41. package/dist/briefing.js +10 -7
  42. package/dist/buffer-surprise-report.d.ts +1 -1
  43. package/dist/buffer-surprise-report.js +1 -1
  44. package/dist/buffer.d.ts +18 -4
  45. package/dist/buffer.js +1 -1
  46. package/dist/calibration.d.ts +1 -1
  47. package/dist/calibration.js +6 -6
  48. package/dist/capsule-cli.d.ts +4 -4
  49. package/dist/capsule-cli.js +1 -1
  50. package/dist/capsule-crypto-5CYAGVC5.js +18 -0
  51. package/dist/capsule-merge-4MGKE7C5.js +189 -0
  52. package/dist/causal-behavior.d.ts +9 -29
  53. package/dist/causal-behavior.js +6 -3
  54. package/dist/causal-behavior.js.map +1 -1
  55. package/dist/causal-chain.js +3 -2
  56. package/dist/causal-consolidation.d.ts +2 -2
  57. package/dist/causal-consolidation.js +28 -17
  58. package/dist/causal-consolidation.js.map +1 -1
  59. package/dist/causal-retrieval.js +3 -3
  60. package/dist/causal-trajectory.js +1 -1
  61. package/dist/chunk-25MQ7IHJ.js +427 -0
  62. package/dist/chunk-25MQ7IHJ.js.map +1 -0
  63. package/dist/chunk-2F2W355T.js +256 -0
  64. package/dist/chunk-2F2W355T.js.map +1 -0
  65. package/dist/chunk-2KI4QFHU.js +228 -0
  66. package/dist/chunk-2KI4QFHU.js.map +1 -0
  67. package/dist/chunk-2PRQG7PV.js +86 -0
  68. package/dist/chunk-2PRQG7PV.js.map +1 -0
  69. package/dist/chunk-2QR3XXIC.js +2272 -0
  70. package/dist/chunk-2QR3XXIC.js.map +1 -0
  71. package/dist/chunk-2WWLHTZY.js +121 -0
  72. package/dist/chunk-326G7DJK.js +2185 -0
  73. package/dist/chunk-326G7DJK.js.map +1 -0
  74. package/dist/chunk-34DQE4KF.js +174 -0
  75. package/dist/chunk-34DQE4KF.js.map +1 -0
  76. package/dist/chunk-3APJ5EVB.js +601 -0
  77. package/dist/chunk-3APJ5EVB.js.map +1 -0
  78. package/dist/chunk-3HPAPHUK.js +51 -0
  79. package/dist/chunk-3HPAPHUK.js.map +1 -0
  80. package/dist/chunk-3JXBXXM2.js +69 -0
  81. package/dist/chunk-3JXBXXM2.js.map +1 -0
  82. package/dist/chunk-3KW65B36.js +681 -0
  83. package/dist/chunk-3KW65B36.js.map +1 -0
  84. package/dist/chunk-3UXOZBHV.js +20 -0
  85. package/dist/chunk-3UXOZBHV.js.map +1 -0
  86. package/dist/chunk-3VAL7ZL2.js +266 -0
  87. package/dist/chunk-3VAL7ZL2.js.map +1 -0
  88. package/dist/chunk-3Y4P7RXM.js +31 -0
  89. package/dist/chunk-3Y4P7RXM.js.map +1 -0
  90. package/dist/chunk-47VWKCAF.js +273 -0
  91. package/dist/chunk-47VWKCAF.js.map +1 -0
  92. package/dist/chunk-4CRG46BG.js +271 -0
  93. package/dist/chunk-4RA3C3EV.js +60 -0
  94. package/dist/chunk-4RA3C3EV.js.map +1 -0
  95. package/dist/chunk-5375UYTQ.js +914 -0
  96. package/dist/chunk-5375UYTQ.js.map +1 -0
  97. package/dist/chunk-56K5QLHX.js +506 -0
  98. package/dist/chunk-56K5QLHX.js.map +1 -0
  99. package/dist/chunk-5NXIJZFX.js +180 -0
  100. package/dist/chunk-5NXIJZFX.js.map +1 -0
  101. package/dist/chunk-5RGLBDQF.js +596 -0
  102. package/dist/chunk-5RGLBDQF.js.map +1 -0
  103. package/dist/chunk-5UZXUTVO.js +9 -0
  104. package/dist/chunk-5UZXUTVO.js.map +1 -0
  105. package/dist/chunk-65PG43EQ.js +105 -0
  106. package/dist/chunk-65PG43EQ.js.map +1 -0
  107. package/dist/chunk-66DHUKLO.js +57 -0
  108. package/dist/chunk-66DHUKLO.js.map +1 -0
  109. package/dist/chunk-6FC5EGNV.js +46 -0
  110. package/dist/chunk-6FC5EGNV.js.map +1 -0
  111. package/dist/chunk-6H2TESSP.js +62 -0
  112. package/dist/chunk-6H2TESSP.js.map +1 -0
  113. package/dist/chunk-6LVVDPJ4.js +32 -0
  114. package/dist/chunk-6LVVDPJ4.js.map +1 -0
  115. package/dist/chunk-6NKAQ74D.js +2237 -0
  116. package/dist/chunk-6NKAQ74D.js.map +1 -0
  117. package/dist/chunk-6RVI47ZR.js +159 -0
  118. package/dist/chunk-6RVI47ZR.js.map +1 -0
  119. package/dist/chunk-7AAT6G4Q.js +5117 -0
  120. package/dist/chunk-7AAT6G4Q.js.map +1 -0
  121. package/dist/chunk-7DTASS5T.js +29 -0
  122. package/dist/chunk-7DTASS5T.js.map +1 -0
  123. package/dist/chunk-7IASACLB.js +596 -0
  124. package/dist/chunk-7MNMYOFP.js +32 -0
  125. package/dist/chunk-7MNMYOFP.js.map +1 -0
  126. package/dist/chunk-7N4KAIGN.js +133 -0
  127. package/dist/chunk-7N4KAIGN.js.map +1 -0
  128. package/dist/chunk-7OZ53EXP.js +101 -0
  129. package/dist/chunk-7OZ53EXP.js.map +1 -0
  130. package/dist/chunk-7XYTQGCC.js +134 -0
  131. package/dist/chunk-7XYTQGCC.js.map +1 -0
  132. package/dist/chunk-A2XUIMJ3.js +341 -0
  133. package/dist/chunk-A2XUIMJ3.js.map +1 -0
  134. package/dist/chunk-AC5LO7IU.js +308 -0
  135. package/dist/chunk-AC5LO7IU.js.map +1 -0
  136. package/dist/chunk-AGZQD76C.js +201 -0
  137. package/dist/chunk-AGZQD76C.js.map +1 -0
  138. package/dist/chunk-AH2JUU6X.js +336 -0
  139. package/dist/chunk-AH2JUU6X.js.map +1 -0
  140. package/dist/chunk-APO3DCMU.js +361 -0
  141. package/dist/chunk-APO3DCMU.js.map +1 -0
  142. package/dist/chunk-BFBF3XEF.js +283 -0
  143. package/dist/chunk-BFBF3XEF.js.map +1 -0
  144. package/dist/chunk-BJ3KMYTB.js +1974 -0
  145. package/dist/chunk-BJ3KMYTB.js.map +1 -0
  146. package/dist/chunk-C5BCH4ZS.js +317 -0
  147. package/dist/chunk-C5BCH4ZS.js.map +1 -0
  148. package/dist/chunk-CHEL3SKB.js +6758 -0
  149. package/dist/chunk-CHEL3SKB.js.map +1 -0
  150. package/dist/chunk-CQZRLNMV.js +1491 -0
  151. package/dist/chunk-CQZRLNMV.js.map +1 -0
  152. package/dist/chunk-D46YSIYX.js +892 -0
  153. package/dist/chunk-D46YSIYX.js.map +1 -0
  154. package/dist/chunk-DB5A3NHS.js +906 -0
  155. package/dist/chunk-DB5A3NHS.js.map +1 -0
  156. package/dist/chunk-DINWEURR.js +648 -0
  157. package/dist/chunk-DINWEURR.js.map +1 -0
  158. package/dist/chunk-DK5LDEQM.js +530 -0
  159. package/dist/chunk-DK5LDEQM.js.map +1 -0
  160. package/dist/chunk-DOM4GKSW.js +34 -0
  161. package/dist/chunk-DOM4GKSW.js.map +1 -0
  162. package/dist/chunk-EDTHC6UD.js +1075 -0
  163. package/dist/chunk-EDTHC6UD.js.map +1 -0
  164. package/dist/chunk-EFJ3MQ4V.js +721 -0
  165. package/dist/chunk-EHRTFRWW.js +89 -0
  166. package/dist/chunk-EHRTFRWW.js.map +1 -0
  167. package/dist/chunk-FAJ7FZYM.js +11 -0
  168. package/dist/chunk-FAJ7FZYM.js.map +1 -0
  169. package/dist/chunk-FBYESMQ2.js +570 -0
  170. package/dist/chunk-FBYESMQ2.js.map +1 -0
  171. package/dist/chunk-FDU6HUUL.js +147 -0
  172. package/dist/chunk-FF4KLI5W.js +99 -0
  173. package/dist/chunk-FF4KLI5W.js.map +1 -0
  174. package/dist/chunk-FIT6DMX6.js +310 -0
  175. package/dist/chunk-FIT6DMX6.js.map +1 -0
  176. package/dist/chunk-FJ43PRLT.js +272 -0
  177. package/dist/chunk-FJ43PRLT.js.map +1 -0
  178. package/dist/chunk-FKFMOY3N.js +32 -0
  179. package/dist/chunk-FKFMOY3N.js.map +1 -0
  180. package/dist/chunk-FLTNHQK6.js +262 -0
  181. package/dist/chunk-FLTNHQK6.js.map +1 -0
  182. package/dist/chunk-GA454ALV.js +12436 -0
  183. package/dist/chunk-GA454ALV.js.map +1 -0
  184. package/dist/chunk-GGKRUQOO.js +228 -0
  185. package/dist/chunk-GIF42EW3.js +63 -0
  186. package/dist/chunk-GIF42EW3.js.map +1 -0
  187. package/dist/chunk-GL6I6MEQ.js +647 -0
  188. package/dist/chunk-H3ME6L6D.js +709 -0
  189. package/dist/chunk-H3ME6L6D.js.map +1 -0
  190. package/dist/chunk-HHLLAQGZ.js +1 -0
  191. package/dist/chunk-HXXBL2KD.js +2040 -0
  192. package/dist/chunk-I5V2VDIW.js +219 -0
  193. package/dist/chunk-I5V2VDIW.js.map +1 -0
  194. package/dist/chunk-I6K5FBRQ.js +35 -0
  195. package/dist/chunk-I6K5FBRQ.js.map +1 -0
  196. package/dist/chunk-ICRIXAP2.js +121 -0
  197. package/dist/chunk-ICRIXAP2.js.map +1 -0
  198. package/dist/chunk-J4EB7DNW.js +11 -0
  199. package/dist/chunk-J4EB7DNW.js.map +1 -0
  200. package/dist/chunk-JLFA7DQG.js +62 -0
  201. package/dist/chunk-JLFA7DQG.js.map +1 -0
  202. package/dist/chunk-KJTKLXTH.js +9 -0
  203. package/dist/chunk-KJTKLXTH.js.map +1 -0
  204. package/dist/chunk-KLAO5DGL.js +917 -0
  205. package/dist/chunk-KLAO5DGL.js.map +1 -0
  206. package/dist/chunk-KNKUID7G.js +183 -0
  207. package/dist/chunk-KOSORCJG.js +624 -0
  208. package/dist/chunk-KOSORCJG.js.map +1 -0
  209. package/dist/chunk-KUJVMMZQ.js +1262 -0
  210. package/dist/chunk-KUJVMMZQ.js.map +1 -0
  211. package/dist/chunk-LCR46JY5.js +123 -0
  212. package/dist/chunk-LCR46JY5.js.map +1 -0
  213. package/dist/chunk-LLQ2LLWF.js +148 -0
  214. package/dist/chunk-LLQ2LLWF.js.map +1 -0
  215. package/dist/chunk-LPMVBPA3.js +236 -0
  216. package/dist/chunk-LT3NLYSI.js +50 -0
  217. package/dist/chunk-LT3NLYSI.js.map +1 -0
  218. package/dist/chunk-LUDTDZLK.js +287 -0
  219. package/dist/chunk-LUDTDZLK.js.map +1 -0
  220. package/dist/chunk-M23FSH32.js +3963 -0
  221. package/dist/chunk-M23FSH32.js.map +1 -0
  222. package/dist/chunk-MC26UJIM.js +118 -0
  223. package/dist/chunk-ME6ESPZU.js +119 -0
  224. package/dist/chunk-ME6ESPZU.js.map +1 -0
  225. package/dist/chunk-MGKYQQYF.js +272 -0
  226. package/dist/chunk-MGKYQQYF.js.map +1 -0
  227. package/dist/chunk-MJFNCJXV.js +66 -0
  228. package/dist/chunk-MJFNCJXV.js.map +1 -0
  229. package/dist/chunk-MSWG7JI6.js +237 -0
  230. package/dist/chunk-MSWG7JI6.js.map +1 -0
  231. package/dist/chunk-MT25YHYH.js +141 -0
  232. package/dist/chunk-MT25YHYH.js.map +1 -0
  233. package/dist/chunk-MT4HVDUZ.js +53 -0
  234. package/dist/chunk-MY6TPVXW.js +219 -0
  235. package/dist/chunk-N2D6GXBM.js +267 -0
  236. package/dist/chunk-N2D6GXBM.js.map +1 -0
  237. package/dist/chunk-NJ3MJQZX.js +46 -0
  238. package/dist/chunk-NJ3MJQZX.js.map +1 -0
  239. package/dist/chunk-NMZY542O.js +335 -0
  240. package/dist/chunk-NMZY542O.js.map +1 -0
  241. package/dist/chunk-NNVTUXEB.js +23 -0
  242. package/dist/chunk-NZL6GGQE.js +375 -0
  243. package/dist/chunk-NZL6GGQE.js.map +1 -0
  244. package/dist/chunk-OAZ5MFUB.js +4124 -0
  245. package/dist/chunk-OAZ5MFUB.js.map +1 -0
  246. package/dist/chunk-OIGNEXKZ.js +237 -0
  247. package/dist/chunk-OIGNEXKZ.js.map +1 -0
  248. package/dist/chunk-OZKZ2TRP.js +3729 -0
  249. package/dist/chunk-OZKZ2TRP.js.map +1 -0
  250. package/dist/chunk-P4NEIHUT.js +108 -0
  251. package/dist/chunk-P7FMDTKL.js +103 -0
  252. package/dist/chunk-P7FMDTKL.js.map +1 -0
  253. package/dist/chunk-PD6O7AXF.js +110 -0
  254. package/dist/chunk-PD6O7AXF.js.map +1 -0
  255. package/dist/chunk-PHK3HARR.js +32 -0
  256. package/dist/chunk-PHK3HARR.js.map +1 -0
  257. package/dist/chunk-PIRJPV5T.js +98 -0
  258. package/dist/chunk-PIRJPV5T.js.map +1 -0
  259. package/dist/chunk-PK7H5L6Y.js +159 -0
  260. package/dist/chunk-PK7H5L6Y.js.map +1 -0
  261. package/dist/chunk-PR5FBTFU.js +233 -0
  262. package/dist/chunk-PR5FBTFU.js.map +1 -0
  263. package/dist/chunk-PU63GXWS.js +174 -0
  264. package/dist/chunk-PU63GXWS.js.map +1 -0
  265. package/dist/chunk-PYPOFEMK.js +294 -0
  266. package/dist/chunk-PYPOFEMK.js.map +1 -0
  267. package/dist/chunk-PZIAX57I.js +124 -0
  268. package/dist/chunk-PZIAX57I.js.map +1 -0
  269. package/dist/chunk-Q7P4WJDP.js +26 -0
  270. package/dist/chunk-Q7P4WJDP.js.map +1 -0
  271. package/dist/chunk-QDZ2RLEC.js +908 -0
  272. package/dist/chunk-QDZ2RLEC.js.map +1 -0
  273. package/dist/chunk-QQUAB63I.js +63 -0
  274. package/dist/chunk-QQUAB63I.js.map +1 -0
  275. package/dist/chunk-QRNI5JBH.js +18 -0
  276. package/dist/chunk-RHY3HH7P.js +601 -0
  277. package/dist/chunk-RHY3HH7P.js.map +1 -0
  278. package/dist/chunk-RK6F44Y6.js +84 -0
  279. package/dist/chunk-RK6F44Y6.js.map +1 -0
  280. package/dist/chunk-RRF5UOBJ.js +91 -0
  281. package/dist/chunk-RXDLTSWT.js +124 -0
  282. package/dist/chunk-RXDLTSWT.js.map +1 -0
  283. package/dist/chunk-RYED3SPJ.js +42 -0
  284. package/dist/chunk-RYED3SPJ.js.map +1 -0
  285. package/dist/chunk-S7KDBTWT.js +106 -0
  286. package/dist/chunk-S7KDBTWT.js.map +1 -0
  287. package/dist/chunk-SEDEKFYQ.js +1 -0
  288. package/dist/chunk-SOAU2OE2.js +125 -0
  289. package/dist/chunk-SOAU2OE2.js.map +1 -0
  290. package/dist/chunk-TECVW3JP.js +36 -0
  291. package/dist/chunk-TECVW3JP.js.map +1 -0
  292. package/dist/chunk-TFO23QT4.js +88 -0
  293. package/dist/chunk-TFO23QT4.js.map +1 -0
  294. package/dist/chunk-TK4UEOSK.js +76 -0
  295. package/dist/chunk-TK4UEOSK.js.map +1 -0
  296. package/dist/chunk-TKWGAOLV.js +122 -0
  297. package/dist/chunk-TKWGAOLV.js.map +1 -0
  298. package/dist/chunk-TMM4S4IJ.js +597 -0
  299. package/dist/chunk-TMM4S4IJ.js.map +1 -0
  300. package/dist/chunk-TMQLARTH.js +188 -0
  301. package/dist/chunk-TMQLARTH.js.map +1 -0
  302. package/dist/chunk-TPDBFYEG.js +130 -0
  303. package/dist/chunk-TPDBFYEG.js.map +1 -0
  304. package/dist/chunk-TPMQ3G6Z.js +145 -0
  305. package/dist/chunk-TPMQ3G6Z.js.map +1 -0
  306. package/dist/chunk-TZOLIGIG.js +61 -0
  307. package/dist/chunk-TZOLIGIG.js.map +1 -0
  308. package/dist/chunk-U3PN77QT.js +113 -0
  309. package/dist/chunk-U3WSW6PZ.js +277 -0
  310. package/dist/chunk-U4SCL7B7.js +640 -0
  311. package/dist/chunk-U4SCL7B7.js.map +1 -0
  312. package/dist/chunk-UWK5OXUJ.js +156 -0
  313. package/dist/chunk-UWK5OXUJ.js.map +1 -0
  314. package/dist/chunk-UWVJF25J.js +74 -0
  315. package/dist/chunk-UXHQAFNA.js +1317 -0
  316. package/dist/chunk-UXHQAFNA.js.map +1 -0
  317. package/dist/chunk-V5OCT34X.js +1 -0
  318. package/dist/chunk-V5OCT34X.js.map +1 -0
  319. package/dist/chunk-VLXA6PI2.js +304 -0
  320. package/dist/chunk-VLXA6PI2.js.map +1 -0
  321. package/dist/chunk-VNO6ZJ35.js +500 -0
  322. package/dist/chunk-VNO6ZJ35.js.map +1 -0
  323. package/dist/chunk-VW676BEI.js +827 -0
  324. package/dist/chunk-VW676BEI.js.map +1 -0
  325. package/dist/chunk-VWT3F4IV.js +2161 -0
  326. package/dist/chunk-VWT3F4IV.js.map +1 -0
  327. package/dist/chunk-W3LR522O.js +2296 -0
  328. package/dist/chunk-W3LR522O.js.map +1 -0
  329. package/dist/chunk-W4L6CZKA.js +96 -0
  330. package/dist/chunk-W4L6CZKA.js.map +1 -0
  331. package/dist/chunk-W4RVMTHR.js +372 -0
  332. package/dist/chunk-W4RVMTHR.js.map +1 -0
  333. package/dist/chunk-WEHSQBFR.js +188 -0
  334. package/dist/chunk-WEHSQBFR.js.map +1 -0
  335. package/dist/chunk-WELDCG6C.js +380 -0
  336. package/dist/chunk-WELDCG6C.js.map +1 -0
  337. package/dist/chunk-WZYKANL3.js +2800 -0
  338. package/dist/chunk-WZYKANL3.js.map +1 -0
  339. package/dist/chunk-XIG5PDM7.js +48 -0
  340. package/dist/chunk-XJNBEDFE.js +193 -0
  341. package/dist/chunk-XJNBEDFE.js.map +1 -0
  342. package/dist/chunk-XVVIG67A.js +291 -0
  343. package/dist/chunk-XVVIG67A.js.map +1 -0
  344. package/dist/chunk-XVZ7B3HG.js +135 -0
  345. package/dist/chunk-YBPYIAA5.js +73 -0
  346. package/dist/chunk-YBPYIAA5.js.map +1 -0
  347. package/dist/chunk-Z734BLO3.js +21 -0
  348. package/dist/chunk-Z734BLO3.js.map +1 -0
  349. package/dist/chunk-ZKSK55RC.js +269 -0
  350. package/dist/chunk-ZKSK55RC.js.map +1 -0
  351. package/dist/chunk-ZTFCYYEZ.js +69 -0
  352. package/dist/chunk-ZTFCYYEZ.js.map +1 -0
  353. package/dist/chunk-ZY2MNJR6.js +329 -0
  354. package/dist/chunk-ZY2MNJR6.js.map +1 -0
  355. package/dist/cli-D3VpkVwB.d.ts +1136 -0
  356. package/dist/cli.d.ts +42 -10
  357. package/dist/cli.js +121 -58
  358. package/dist/codex-cli-fallback.d.ts +1 -0
  359. package/dist/codex-cli-fallback.js +1 -1
  360. package/dist/commitment-ledger.js +1 -1
  361. package/dist/compat/checks.d.ts +5 -0
  362. package/dist/compat/checks.js +11 -0
  363. package/dist/compat/checks.js.map +1 -0
  364. package/dist/compat/types.d.ts +30 -0
  365. package/dist/compat/types.js +1 -0
  366. package/dist/compat/types.js.map +1 -0
  367. package/dist/compounding/engine.d.ts +221 -0
  368. package/dist/compounding/engine.js +32 -0
  369. package/dist/compounding/engine.js.map +1 -0
  370. package/dist/compounding/preference-consolidator.d.ts +92 -0
  371. package/dist/compounding/preference-consolidator.js +553 -0
  372. package/dist/compounding/preference-consolidator.js.map +1 -0
  373. package/dist/compression-optimizer.d.ts +1 -1
  374. package/dist/config.d.ts +5 -3
  375. package/dist/config.js +9 -4
  376. package/dist/conflict-policy-DyJ2wd-h.d.ts +4 -0
  377. package/dist/connectors/codex-materialize-runner.d.ts +64 -0
  378. package/dist/connectors/codex-materialize-runner.js +33 -0
  379. package/dist/connectors/codex-materialize-runner.js.map +1 -0
  380. package/dist/connectors/codex-materialize.d.ts +195 -0
  381. package/dist/connectors/codex-materialize.js +38 -0
  382. package/dist/connectors/codex-materialize.js.map +1 -0
  383. package/dist/connectors/index.d.ts +444 -0
  384. package/dist/connectors/index.js +115 -0
  385. package/dist/connectors/index.js.map +1 -0
  386. package/dist/connectors-cli-CwbyjGR7.d.ts +257 -0
  387. package/dist/connectors-cli.d.ts +1 -1
  388. package/dist/consolidation-provenance-check.d.ts +4 -2
  389. package/dist/consolidation-undo.d.ts +4 -2
  390. package/dist/contradiction/index.d.ts +258 -0
  391. package/dist/contradiction/index.js +43 -0
  392. package/dist/contradiction/index.js.map +1 -0
  393. package/dist/contradiction-review-ATP4S6IC.js +30 -0
  394. package/dist/contradiction-review-ATP4S6IC.js.map +1 -0
  395. package/dist/contradiction-scan-5A4IDZV5.js +13 -0
  396. package/dist/contradiction-scan-5A4IDZV5.js.map +1 -0
  397. package/dist/conversation-index/backend.d.ts +97 -0
  398. package/dist/conversation-index/backend.js +13 -0
  399. package/dist/conversation-index/backend.js.map +1 -0
  400. package/dist/conversation-index/chunker.d.ts +16 -0
  401. package/dist/conversation-index/chunker.js +8 -0
  402. package/dist/conversation-index/chunker.js.map +1 -0
  403. package/dist/conversation-index/cleanup.d.ts +11 -0
  404. package/dist/conversation-index/cleanup.js +9 -0
  405. package/dist/conversation-index/cleanup.js.map +1 -0
  406. package/dist/conversation-index/faiss-adapter.d.ts +6 -0
  407. package/dist/conversation-index/faiss-adapter.js +16 -0
  408. package/dist/conversation-index/faiss-adapter.js.map +1 -0
  409. package/dist/conversation-index/indexer.d.ts +23 -0
  410. package/dist/conversation-index/indexer.js +15 -0
  411. package/dist/conversation-index/indexer.js.map +1 -0
  412. package/dist/conversation-index/search.d.ts +6 -0
  413. package/dist/conversation-index/search.js +11 -0
  414. package/dist/conversation-index/search.js.map +1 -0
  415. package/dist/day-summary.d.ts +1 -1
  416. package/dist/delinearize.d.ts +1 -1
  417. package/dist/direct-answer-wiring.d.ts +1 -1
  418. package/dist/direct-answer-wiring.js +1 -1
  419. package/dist/direct-answer.d.ts +1 -1
  420. package/dist/embedding-fallback.d.ts +1 -1
  421. package/dist/embedding-fallback.js +2 -2
  422. package/dist/enrichment/index.d.ts +163 -0
  423. package/dist/enrichment/index.js +18 -0
  424. package/dist/enrichment/index.js.map +1 -0
  425. package/dist/entity-retrieval.d.ts +4 -2
  426. package/dist/entity-retrieval.js +9 -6
  427. package/dist/entity-schema.d.ts +1 -1
  428. package/dist/evals.js +1 -1
  429. package/dist/event-order-recall.d.ts +17 -0
  430. package/dist/event-order-recall.js +11 -0
  431. package/dist/event-order-recall.js.map +1 -0
  432. package/dist/evidence-pack.d.ts +3 -1
  433. package/dist/evidence-pack.js +5 -3
  434. package/dist/explicit-capture.d.ts +23 -6
  435. package/dist/explicit-capture.js +2 -2
  436. package/dist/explicit-cue-recall.d.ts +4 -1
  437. package/dist/explicit-cue-recall.js +4 -2
  438. package/dist/extraction-judge-telemetry.d.ts +1 -1
  439. package/dist/extraction-judge-training.d.ts +1 -1
  440. package/dist/extraction-judge-training.js +1 -1
  441. package/dist/extraction-judge.d.ts +1 -1
  442. package/dist/extraction.d.ts +1 -1
  443. package/dist/extraction.js +11 -10
  444. package/dist/faiss-adapter-CzPghc4C.d.ts +70 -0
  445. package/dist/fallback-llm.d.ts +4 -1
  446. package/dist/fallback-llm.js +6 -6
  447. package/dist/focused-list-recall.d.ts +17 -0
  448. package/dist/focused-list-recall.js +11 -0
  449. package/dist/focused-list-recall.js.map +1 -0
  450. package/dist/graph-edge-decay-5DI5GUNL.js +207 -0
  451. package/dist/identity-continuity.d.ts +1 -1
  452. package/dist/importance.d.ts +1 -1
  453. package/dist/index-DJ9QWMw-.d.ts +35 -0
  454. package/dist/index.d.ts +107 -715
  455. package/dist/index.js +657 -2611
  456. package/dist/index.js.map +1 -1
  457. package/dist/intent.d.ts +1 -1
  458. package/dist/intent.js +1 -1
  459. package/dist/lcm/archive.d.ts +89 -0
  460. package/dist/lcm/archive.js +12 -0
  461. package/dist/lcm/archive.js.map +1 -0
  462. package/dist/lcm/dag.d.ts +48 -0
  463. package/dist/lcm/dag.js +8 -0
  464. package/dist/lcm/dag.js.map +1 -0
  465. package/dist/lcm/engine.d.ts +116 -0
  466. package/dist/lcm/engine.js +20 -0
  467. package/dist/lcm/engine.js.map +1 -0
  468. package/dist/lcm/index.d.ts +12 -0
  469. package/dist/lcm/index.js +44 -0
  470. package/dist/lcm/index.js.map +1 -0
  471. package/dist/lcm/queue.d.ts +62 -0
  472. package/dist/lcm/queue.js +8 -0
  473. package/dist/lcm/queue.js.map +1 -0
  474. package/dist/lcm/recall.d.ts +20 -0
  475. package/dist/lcm/recall.js +8 -0
  476. package/dist/lcm/recall.js.map +1 -0
  477. package/dist/lcm/schema.d.ts +16 -0
  478. package/dist/lcm/schema.js +14 -0
  479. package/dist/lcm/schema.js.map +1 -0
  480. package/dist/lcm/summarizer.d.ts +38 -0
  481. package/dist/lcm/summarizer.js +12 -0
  482. package/dist/lcm/summarizer.js.map +1 -0
  483. package/dist/lcm/tools.d.ts +29 -0
  484. package/dist/lcm/tools.js +8 -0
  485. package/dist/lcm/tools.js.map +1 -0
  486. package/dist/lifecycle.d.ts +1 -1
  487. package/dist/live-connectors-runner.d.ts +1 -1
  488. package/dist/live-connectors-runner.js +5 -5
  489. package/dist/local-llm.d.ts +8 -4
  490. package/dist/local-llm.js +3 -3
  491. package/dist/maintenance/archive-observations.d.ts +18 -0
  492. package/dist/maintenance/archive-observations.js +8 -0
  493. package/dist/maintenance/archive-observations.js.map +1 -0
  494. package/dist/maintenance/backup-stamp.d.ts +3 -0
  495. package/dist/maintenance/backup-stamp.js +8 -0
  496. package/dist/maintenance/backup-stamp.js.map +1 -0
  497. package/dist/maintenance/memory-governance-cron.d.ts +85 -0
  498. package/dist/maintenance/memory-governance-cron.js +22 -0
  499. package/dist/maintenance/memory-governance-cron.js.map +1 -0
  500. package/dist/maintenance/memory-governance.d.ts +137 -0
  501. package/dist/maintenance/memory-governance.js +40 -0
  502. package/dist/maintenance/memory-governance.js.map +1 -0
  503. package/dist/maintenance/migrate-observations.d.ts +18 -0
  504. package/dist/maintenance/migrate-observations.js +9 -0
  505. package/dist/maintenance/migrate-observations.js.map +1 -0
  506. package/dist/maintenance/observation-ledger-utils.d.ts +10 -0
  507. package/dist/maintenance/observation-ledger-utils.js +10 -0
  508. package/dist/maintenance/observation-ledger-utils.js.map +1 -0
  509. package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +15 -0
  510. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +28 -0
  511. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js.map +1 -0
  512. package/dist/maintenance/rebuild-memory-projection.d.ts +77 -0
  513. package/dist/maintenance/rebuild-memory-projection.js +35 -0
  514. package/dist/maintenance/rebuild-memory-projection.js.map +1 -0
  515. package/dist/maintenance/rebuild-observations.d.ts +17 -0
  516. package/dist/maintenance/rebuild-observations.js +9 -0
  517. package/dist/maintenance/rebuild-observations.js.map +1 -0
  518. package/dist/mcp-memory-inspector-app.d.ts +124 -0
  519. package/dist/mcp-memory-inspector-app.js +20 -0
  520. package/dist/mcp-memory-inspector-app.js.map +1 -0
  521. package/dist/memory-action-policy.d.ts +1 -1
  522. package/dist/memory-cache.d.ts +1 -1
  523. package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
  524. package/dist/memory-projection-store.d.ts +108 -3
  525. package/dist/memory-projection-store.js +2 -1
  526. package/dist/memory-provenance.d.ts +57 -0
  527. package/dist/memory-provenance.js +13 -0
  528. package/dist/memory-provenance.js.map +1 -0
  529. package/dist/memory-worth-outcomes.d.ts +4 -2
  530. package/dist/migrate/from-engram.d.ts +24 -0
  531. package/dist/migrate/from-engram.js +12 -0
  532. package/dist/migrate/from-engram.js.map +1 -0
  533. package/dist/models-json.d.ts +1 -1
  534. package/dist/namespaces/migrate.d.ts +50 -0
  535. package/dist/namespaces/migrate.js +50 -0
  536. package/dist/namespaces/migrate.js.map +1 -0
  537. package/dist/namespaces/principal.d.ts +17 -0
  538. package/dist/namespaces/principal.js +16 -0
  539. package/dist/namespaces/principal.js.map +1 -0
  540. package/dist/namespaces/search.d.ts +46 -0
  541. package/dist/namespaces/search.js +28 -0
  542. package/dist/namespaces/search.js.map +1 -0
  543. package/dist/namespaces/storage.d.ts +32 -0
  544. package/dist/namespaces/storage.js +28 -0
  545. package/dist/namespaces/storage.js.map +1 -0
  546. package/dist/native-knowledge.d.ts +1 -1
  547. package/dist/network/tailscale.d.ts +41 -0
  548. package/dist/network/tailscale.js +9 -0
  549. package/dist/network/tailscale.js.map +1 -0
  550. package/dist/network/webdav.d.ts +39 -0
  551. package/dist/network/webdav.js +10 -0
  552. package/dist/network/webdav.js.map +1 -0
  553. package/dist/objective-state-writers.d.ts +1 -1
  554. package/dist/objective-state-writers.js +2 -2
  555. package/dist/operator-toolkit.d.ts +4 -2
  556. package/dist/operator-toolkit.js +35 -17
  557. package/dist/opik-exporter.js +2 -2
  558. package/dist/opik-exporter.js.map +1 -1
  559. package/dist/orchestrator-DuWl9Hwx.d.ts +1244 -0
  560. package/dist/orchestrator.d.ts +24 -7
  561. package/dist/orchestrator.js +107 -65
  562. package/dist/path-MR5JPYOP.js +9 -0
  563. package/dist/path-MR5JPYOP.js.map +1 -0
  564. package/dist/patterns-cli.d.ts +1 -1
  565. package/dist/policy-runtime.d.ts +1 -1
  566. package/dist/qmd-recall-cache.d.ts +2 -2
  567. package/dist/qmd.d.ts +103 -4
  568. package/dist/qmd.js +23 -5
  569. package/dist/recall-disclosure-escalation.d.ts +1 -1
  570. package/dist/recall-explain-renderer.d.ts +3 -1
  571. package/dist/recall-explain-renderer.js +5 -3
  572. package/dist/recall-state.d.ts +1 -1
  573. package/dist/recall-tag-filter.d.ts +3 -1
  574. package/dist/recall-xray-cli.d.ts +3 -1
  575. package/dist/recall-xray-cli.js +6 -4
  576. package/dist/recall-xray-renderer.d.ts +3 -1
  577. package/dist/recall-xray-renderer.js +5 -3
  578. package/dist/recall-xray.d.ts +8 -1
  579. package/dist/recall-xray.js +4 -2
  580. package/dist/replay/normalizers/chatgpt.d.ts +6 -0
  581. package/dist/replay/normalizers/chatgpt.js +11 -0
  582. package/dist/replay/normalizers/chatgpt.js.map +1 -0
  583. package/dist/replay/normalizers/claude.d.ts +6 -0
  584. package/dist/replay/normalizers/claude.js +11 -0
  585. package/dist/replay/normalizers/claude.js.map +1 -0
  586. package/dist/replay/normalizers/openclaw.d.ts +6 -0
  587. package/dist/replay/normalizers/openclaw.js +11 -0
  588. package/dist/replay/normalizers/openclaw.js.map +1 -0
  589. package/dist/replay/normalizers/shared.d.ts +16 -0
  590. package/dist/replay/normalizers/shared.js +14 -0
  591. package/dist/replay/normalizers/shared.js.map +1 -0
  592. package/dist/replay/runner.d.ts +35 -0
  593. package/dist/replay/runner.js +16 -0
  594. package/dist/replay/runner.js.map +1 -0
  595. package/dist/replay/types.d.ts +57 -0
  596. package/dist/replay/types.js +19 -0
  597. package/dist/replay/types.js.map +1 -0
  598. package/dist/resolution-B7FNQSSP.js +12 -0
  599. package/dist/resolution-B7FNQSSP.js.map +1 -0
  600. package/dist/resolve-auth-token.d.ts +1 -1
  601. package/dist/resolve-provider-secret.js +2 -2
  602. package/dist/response-guidance-recall.d.ts +18 -0
  603. package/dist/response-guidance-recall.js +11 -0
  604. package/dist/response-guidance-recall.js.map +1 -0
  605. package/dist/resume-bundles.js +7 -5
  606. package/dist/retrieval-agents.d.ts +2 -2
  607. package/dist/retrieval-tiers.d.ts +1 -1
  608. package/dist/routing/engine.d.ts +35 -0
  609. package/dist/routing/engine.js +16 -0
  610. package/dist/routing/engine.js.map +1 -0
  611. package/dist/routing/store.d.ts +27 -0
  612. package/dist/routing/store.js +10 -0
  613. package/dist/routing/store.js.map +1 -0
  614. package/dist/runtime/better-sqlite.d.ts +8 -0
  615. package/dist/runtime/better-sqlite.js +10 -0
  616. package/dist/runtime/better-sqlite.js.map +1 -0
  617. package/dist/runtime/child-process.d.ts +32 -0
  618. package/dist/runtime/child-process.js +10 -0
  619. package/dist/runtime/child-process.js.map +1 -0
  620. package/dist/runtime/env.d.ts +5 -0
  621. package/dist/runtime/env.js +12 -0
  622. package/dist/runtime/env.js.map +1 -0
  623. package/dist/sdk-compat.js +1 -1
  624. package/dist/search/document-scanner.d.ts +22 -0
  625. package/dist/search/document-scanner.js +8 -0
  626. package/dist/search/document-scanner.js.map +1 -0
  627. package/dist/search/embed-helper.d.ts +35 -0
  628. package/dist/search/embed-helper.js +9 -0
  629. package/dist/search/embed-helper.js.map +1 -0
  630. package/dist/search/factory.d.ts +32 -0
  631. package/dist/search/factory.js +29 -0
  632. package/dist/search/factory.js.map +1 -0
  633. package/dist/search/index.d.ts +15 -0
  634. package/dist/search/index.js +50 -0
  635. package/dist/search/index.js.map +1 -0
  636. package/dist/search/lancedb-backend.d.ts +51 -0
  637. package/dist/search/lancedb-backend.js +10 -0
  638. package/dist/search/lancedb-backend.js.map +1 -0
  639. package/dist/search/meilisearch-backend.d.ts +48 -0
  640. package/dist/search/meilisearch-backend.js +10 -0
  641. package/dist/search/meilisearch-backend.js.map +1 -0
  642. package/dist/search/noop-backend.d.ts +26 -0
  643. package/dist/search/noop-backend.js +8 -0
  644. package/dist/search/noop-backend.js.map +1 -0
  645. package/dist/search/orama-backend.d.ts +53 -0
  646. package/dist/search/orama-backend.js +10 -0
  647. package/dist/search/orama-backend.js.map +1 -0
  648. package/dist/search/port.d.ts +61 -0
  649. package/dist/search/port.js +1 -0
  650. package/dist/search/port.js.map +1 -0
  651. package/dist/search/remote-backend.d.ts +39 -0
  652. package/dist/search/remote-backend.js +9 -0
  653. package/dist/search/remote-backend.js.map +1 -0
  654. package/dist/secure-store/index.d.ts +890 -0
  655. package/dist/secure-store/index.js +156 -0
  656. package/dist/secure-store/index.js.map +1 -0
  657. package/dist/semantic-VwGI14Ok.d.ts +69 -0
  658. package/dist/semantic-consolidation-4HkHWgeI.d.ts +180 -0
  659. package/dist/semantic-consolidation.d.ts +3 -3
  660. package/dist/semantic-consolidation.js +15 -8
  661. package/dist/semantic-rule-promotion.js +9 -6
  662. package/dist/semantic-rule-verifier.d.ts +1 -1
  663. package/dist/semantic-rule-verifier.js +10 -7
  664. package/dist/session-observer-bands.d.ts +1 -1
  665. package/dist/session-observer-state.d.ts +1 -1
  666. package/dist/shared-context/manager.d.ts +131 -0
  667. package/dist/shared-context/manager.js +15 -0
  668. package/dist/shared-context/manager.js.map +1 -0
  669. package/dist/signal.d.ts +1 -1
  670. package/dist/skills-registry.js +13 -1
  671. package/dist/skills-registry.js.map +1 -1
  672. package/dist/state-store-VZU2IA53.js +16 -0
  673. package/dist/state-store-VZU2IA53.js.map +1 -0
  674. package/dist/storage-paths.d.ts +9 -0
  675. package/dist/storage-paths.js +20 -0
  676. package/dist/storage-paths.js.map +1 -0
  677. package/dist/storage.d.ts +6 -2
  678. package/dist/storage.js +8 -5
  679. package/dist/summarizer.d.ts +6 -1
  680. package/dist/summarizer.js +11 -10
  681. package/dist/summary-snapshot.d.ts +1 -1
  682. package/dist/summary-snapshot.js +2 -1
  683. package/dist/surfaces/dreams.d.ts +16 -0
  684. package/dist/surfaces/dreams.js +282 -0
  685. package/dist/surfaces/dreams.js.map +1 -0
  686. package/dist/surfaces/heartbeat.d.ts +17 -0
  687. package/dist/surfaces/heartbeat.js +265 -0
  688. package/dist/surfaces/heartbeat.js.map +1 -0
  689. package/dist/targeted-fact-recall.d.ts +17 -0
  690. package/dist/targeted-fact-recall.js +11 -0
  691. package/dist/targeted-fact-recall.js.map +1 -0
  692. package/dist/telemetry-transcript.d.ts +7 -0
  693. package/dist/telemetry-transcript.js +16 -0
  694. package/dist/telemetry-transcript.js.map +1 -0
  695. package/dist/temporal-supersession.d.ts +4 -2
  696. package/dist/temporal-supersession.js +2 -1
  697. package/dist/temporal-validity.d.ts +1 -1
  698. package/dist/threading.d.ts +6 -1
  699. package/dist/threading.js +2 -1
  700. package/dist/tier-migration.d.ts +5 -3
  701. package/dist/tier-routing.d.ts +1 -1
  702. package/dist/tokens.js +2 -2
  703. package/dist/topics.d.ts +1 -1
  704. package/dist/transcript.d.ts +16 -2
  705. package/dist/transcript.js +2 -1
  706. package/dist/transfer/autodetect.d.ts +4 -0
  707. package/dist/transfer/autodetect.js +15 -0
  708. package/dist/transfer/autodetect.js.map +1 -0
  709. package/dist/transfer/backup.d.ts +21 -0
  710. package/dist/transfer/backup.js +17 -0
  711. package/dist/transfer/backup.js.map +1 -0
  712. package/dist/transfer/capsule-export.d.ts +113 -0
  713. package/dist/transfer/capsule-export.js +19 -0
  714. package/dist/transfer/capsule-export.js.map +1 -0
  715. package/dist/transfer/capsule-import.d.ts +124 -0
  716. package/dist/transfer/capsule-import.js +16 -0
  717. package/dist/transfer/capsule-import.js.map +1 -0
  718. package/dist/transfer/constants.d.ts +13 -0
  719. package/dist/transfer/constants.js +12 -0
  720. package/dist/transfer/constants.js.map +1 -0
  721. package/dist/transfer/export-json.d.ts +11 -0
  722. package/dist/transfer/export-json.js +11 -0
  723. package/dist/transfer/export-json.js.map +1 -0
  724. package/dist/transfer/export-md.d.ts +10 -0
  725. package/dist/transfer/export-md.js +13 -0
  726. package/dist/transfer/export-md.js.map +1 -0
  727. package/dist/transfer/export-sqlite.d.ts +9 -0
  728. package/dist/transfer/export-sqlite.js +12 -0
  729. package/dist/transfer/export-sqlite.js.map +1 -0
  730. package/dist/transfer/fs-utils.d.ts +61 -0
  731. package/dist/transfer/fs-utils.js +40 -0
  732. package/dist/transfer/fs-utils.js.map +1 -0
  733. package/dist/transfer/import-json.d.ts +16 -0
  734. package/dist/transfer/import-json.js +13 -0
  735. package/dist/transfer/import-json.js.map +1 -0
  736. package/dist/transfer/import-md.d.ts +14 -0
  737. package/dist/transfer/import-md.js +11 -0
  738. package/dist/transfer/import-md.js.map +1 -0
  739. package/dist/transfer/import-sqlite.d.ts +14 -0
  740. package/dist/transfer/import-sqlite.js +12 -0
  741. package/dist/transfer/import-sqlite.js.map +1 -0
  742. package/dist/transfer/sqlite-schema.d.ts +4 -0
  743. package/dist/transfer/sqlite-schema.js +10 -0
  744. package/dist/transfer/sqlite-schema.js.map +1 -0
  745. package/dist/transfer/types.d.ts +916 -0
  746. package/dist/transfer/types.js +30 -0
  747. package/dist/transfer/types.js.map +1 -0
  748. package/dist/trust-zones.d.ts +3 -2
  749. package/dist/trust-zones.js +1 -1
  750. package/dist/types.d.ts +88 -3
  751. package/dist/types.js +1 -1
  752. package/dist/user-model.d.ts +37 -0
  753. package/dist/user-model.js +28 -0
  754. package/dist/user-model.js.map +1 -0
  755. package/dist/utility-runtime.d.ts +1 -1
  756. package/dist/verified-recall.js +11 -8
  757. package/dist/work/board.d.ts +43 -0
  758. package/dist/work/board.js +14 -0
  759. package/dist/work/board.js.map +1 -0
  760. package/dist/work/boundary.d.ts +8 -0
  761. package/dist/work/boundary.js +14 -0
  762. package/dist/work/boundary.js.map +1 -0
  763. package/dist/work/storage.d.ts +39 -0
  764. package/dist/work/storage.js +11 -0
  765. package/dist/work/storage.js.map +1 -0
  766. package/dist/work/types.d.ts +75 -0
  767. package/dist/work/types.js +1 -0
  768. package/dist/work/types.js.map +1 -0
  769. package/package.json +2767 -6
  770. package/scripts/faiss_index.py +816 -0
  771. package/scripts/faiss_requirements.txt +3 -0
  772. package/skills/remnic-entities/SKILL.md +51 -0
  773. package/skills/remnic-memory-workflow/SKILL.md +61 -0
  774. package/skills/remnic-recall/SKILL.md +51 -0
  775. package/skills/remnic-remember/SKILL.md +56 -0
  776. package/skills/remnic-search/SKILL.md +51 -0
  777. package/skills/remnic-status/SKILL.md +51 -0
  778. package/src/abort-error.test.ts +49 -0
  779. package/src/abort-error.ts +46 -0
  780. package/src/abstraction-nodes.ts +162 -0
  781. package/src/access-audit.test.ts +178 -0
  782. package/src/access-audit.ts +125 -0
  783. package/src/access-cli.test.ts +439 -0
  784. package/src/access-cli.ts +438 -0
  785. package/src/access-http.test.ts +225 -0
  786. package/src/access-http.ts +1899 -0
  787. package/src/access-idempotency.ts +232 -0
  788. package/src/access-mcp.test.ts +568 -0
  789. package/src/access-mcp.ts +3056 -0
  790. package/src/access-schema-pi.test.ts +60 -0
  791. package/src/access-schema.ts +522 -0
  792. package/src/access-service-namespace.test.ts +123 -0
  793. package/src/access-service.ts +5629 -0
  794. package/src/action-confidence.test.ts +206 -0
  795. package/src/action-confidence.ts +466 -0
  796. package/src/active-memory-bridge.test.ts +285 -0
  797. package/src/active-memory-bridge.ts +217 -0
  798. package/src/active-recall.test.ts +484 -0
  799. package/src/active-recall.ts +459 -0
  800. package/src/adapters/claude-code.ts +56 -0
  801. package/src/adapters/codex.ts +57 -0
  802. package/src/adapters/hermes.ts +64 -0
  803. package/src/adapters/index.ts +6 -0
  804. package/src/adapters/registry.ts +41 -0
  805. package/src/adapters/replit.ts +55 -0
  806. package/src/adapters/types.ts +51 -0
  807. package/src/behavior-learner.ts +144 -0
  808. package/src/behavior-signals.ts +73 -0
  809. package/src/binary-lifecycle/backend.ts +117 -0
  810. package/src/binary-lifecycle/index.ts +35 -0
  811. package/src/binary-lifecycle/manifest.ts +79 -0
  812. package/src/binary-lifecycle/pipeline.ts +352 -0
  813. package/src/binary-lifecycle/scanner.ts +89 -0
  814. package/src/binary-lifecycle/types.ts +89 -0
  815. package/src/bootstrap.ts +178 -0
  816. package/src/boxes.ts +521 -0
  817. package/src/briefing.test.ts +1535 -0
  818. package/src/briefing.ts +1382 -0
  819. package/src/buffer-session.test.ts +443 -0
  820. package/src/buffer-surprise-report.ts +176 -0
  821. package/src/buffer-surprise-telemetry.test.ts +606 -0
  822. package/src/buffer-surprise-trigger.test.ts +766 -0
  823. package/src/buffer-surprise.test.ts +339 -0
  824. package/src/buffer-surprise.ts +203 -0
  825. package/src/buffer.ts +900 -0
  826. package/src/bulk-import/cli-command.test.ts +204 -0
  827. package/src/bulk-import/index.ts +34 -0
  828. package/src/bulk-import/pipeline.test.ts +445 -0
  829. package/src/bulk-import/pipeline.ts +178 -0
  830. package/src/bulk-import/registry.test.ts +151 -0
  831. package/src/bulk-import/registry.ts +72 -0
  832. package/src/bulk-import/types.test.ts +272 -0
  833. package/src/bulk-import/types.ts +145 -0
  834. package/src/calibration.ts +394 -0
  835. package/src/capsule-cli.test.ts +398 -0
  836. package/src/capsule-cli.ts +565 -0
  837. package/src/causal-behavior.ts +308 -0
  838. package/src/causal-chain.ts +419 -0
  839. package/src/causal-consolidation.ts +370 -0
  840. package/src/causal-retrieval.ts +286 -0
  841. package/src/causal-trajectory-graph.ts +60 -0
  842. package/src/causal-trajectory.ts +303 -0
  843. package/src/chunking.ts +220 -0
  844. package/src/citations.ts +232 -0
  845. package/src/cli.ts +9403 -0
  846. package/src/codex-cli-fallback.ts +162 -0
  847. package/src/codex-thread-key.ts +1 -0
  848. package/src/coding/access-coding-context.test.ts +197 -0
  849. package/src/coding/coding-branch-scope.test.ts +281 -0
  850. package/src/coding/coding-namespace.test.ts +360 -0
  851. package/src/coding/coding-namespace.ts +412 -0
  852. package/src/coding/coding-orchestrator.test.ts +249 -0
  853. package/src/coding/git-context.test.ts +507 -0
  854. package/src/coding/git-context.ts +336 -0
  855. package/src/coding/mcp-set-coding-context.test.ts +174 -0
  856. package/src/coding/review-context.test.ts +316 -0
  857. package/src/coding/review-context.ts +349 -0
  858. package/src/coding/wire-coding-context.test.ts +468 -0
  859. package/src/commitment-ledger.test.ts +78 -0
  860. package/src/commitment-ledger.ts +337 -0
  861. package/src/compat/checks.test.ts +206 -0
  862. package/src/compat/checks.ts +716 -0
  863. package/src/compat/types.ts +33 -0
  864. package/src/compounding/engine.ts +1686 -0
  865. package/src/compounding/preference-consolidator.ts +778 -0
  866. package/src/compression-optimizer.ts +312 -0
  867. package/src/config.test.ts +930 -0
  868. package/src/config.ts +3807 -0
  869. package/src/connectors/codex/instructions.md +160 -0
  870. package/src/connectors/codex/resources/namespace-cheatsheet.md +48 -0
  871. package/src/connectors/codex-marketplace.ts +500 -0
  872. package/src/connectors/codex-materialize-runner.ts +212 -0
  873. package/src/connectors/codex-materialize.ts +983 -0
  874. package/src/connectors/coerce.ts +62 -0
  875. package/src/connectors/index.test.ts +1570 -0
  876. package/src/connectors/index.ts +3222 -0
  877. package/src/connectors/live/framework.ts +164 -0
  878. package/src/connectors/live/github.test.ts +1218 -0
  879. package/src/connectors/live/github.ts +1068 -0
  880. package/src/connectors/live/gmail.test.ts +1706 -0
  881. package/src/connectors/live/gmail.ts +1293 -0
  882. package/src/connectors/live/google-drive.test.ts +696 -0
  883. package/src/connectors/live/google-drive.ts +724 -0
  884. package/src/connectors/live/index.ts +101 -0
  885. package/src/connectors/live/live-connectors.test.ts +689 -0
  886. package/src/connectors/live/notion.test.ts +1109 -0
  887. package/src/connectors/live/notion.ts +978 -0
  888. package/src/connectors/live/registry.ts +103 -0
  889. package/src/connectors/live/state-store.ts +399 -0
  890. package/src/connectors/live/transient-errors.ts +150 -0
  891. package/src/connectors/weclone-installer.test.ts +850 -0
  892. package/src/connectors-cli.ts +513 -0
  893. package/src/console/state.test.ts +224 -0
  894. package/src/console/state.ts +514 -0
  895. package/src/console/trace.test.ts +813 -0
  896. package/src/console/trace.ts +603 -0
  897. package/src/console/tui.test.ts +582 -0
  898. package/src/console/tui.ts +508 -0
  899. package/src/consolidation-operator.ts +182 -0
  900. package/src/consolidation-provenance-check.ts +551 -0
  901. package/src/consolidation-undo.ts +718 -0
  902. package/src/contradiction/contradiction-judge.test.ts +189 -0
  903. package/src/contradiction/contradiction-judge.ts +333 -0
  904. package/src/contradiction/contradiction-review.ts +574 -0
  905. package/src/contradiction/contradiction-scan.ts +504 -0
  906. package/src/contradiction/contradiction.test.ts +2230 -0
  907. package/src/contradiction/index.ts +37 -0
  908. package/src/contradiction/resolution.ts +383 -0
  909. package/src/conversation-index/backend.ts +323 -0
  910. package/src/conversation-index/chunker.ts +47 -0
  911. package/src/conversation-index/cleanup.ts +53 -0
  912. package/src/conversation-index/faiss-adapter.ts +384 -0
  913. package/src/conversation-index/indexer.test.ts +164 -0
  914. package/src/conversation-index/indexer.ts +192 -0
  915. package/src/conversation-index/search.ts +37 -0
  916. package/src/cross-namespace-budget.test.ts +275 -0
  917. package/src/cross-namespace-budget.ts +365 -0
  918. package/src/cue-anchors.ts +163 -0
  919. package/src/curation/index.ts +544 -0
  920. package/src/dashboard-runtime.ts +337 -0
  921. package/src/day-summary.ts +122 -0
  922. package/src/dedup/index.ts +330 -0
  923. package/src/dedup/semantic.test.ts +1577 -0
  924. package/src/dedup/semantic.ts +148 -0
  925. package/src/delinearize.ts +193 -0
  926. package/src/direct-answer-wiring.test.ts +473 -0
  927. package/src/direct-answer-wiring.ts +180 -0
  928. package/src/direct-answer.test.ts +484 -0
  929. package/src/direct-answer.ts +273 -0
  930. package/src/embedding-fallback.ts +565 -0
  931. package/src/enrichment/audit.ts +89 -0
  932. package/src/enrichment/index.ts +27 -0
  933. package/src/enrichment/pipeline.ts +197 -0
  934. package/src/enrichment/provider-registry.ts +85 -0
  935. package/src/enrichment/types.ts +100 -0
  936. package/src/enrichment/web-search-provider.ts +63 -0
  937. package/src/entity-retrieval.ts +774 -0
  938. package/src/entity-schema.ts +239 -0
  939. package/src/evals.ts +1312 -0
  940. package/src/event-order-recall.test.ts +4164 -0
  941. package/src/event-order-recall.ts +2802 -0
  942. package/src/evidence-pack.test.ts +89 -0
  943. package/src/evidence-pack.ts +388 -0
  944. package/src/explicit-capture.ts +530 -0
  945. package/src/explicit-cue-recall.test.ts +3019 -0
  946. package/src/explicit-cue-recall.ts +5545 -0
  947. package/src/extraction-judge-telemetry.ts +234 -0
  948. package/src/extraction-judge-training.ts +221 -0
  949. package/src/extraction-judge.ts +846 -0
  950. package/src/extraction-timeout.test.ts +265 -0
  951. package/src/extraction.ts +2719 -0
  952. package/src/fallback-llm.test.ts +1060 -0
  953. package/src/fallback-llm.ts +918 -0
  954. package/src/focused-list-recall.test.ts +734 -0
  955. package/src/focused-list-recall.ts +1160 -0
  956. package/src/graph-dashboard-diff.ts +35 -0
  957. package/src/graph-dashboard-key.ts +5 -0
  958. package/src/graph-dashboard-parser.ts +104 -0
  959. package/src/graph-edge-reinforcement.ts +192 -0
  960. package/src/graph-events.ts +151 -0
  961. package/src/graph-recall.test.ts +164 -0
  962. package/src/graph-recall.ts +189 -0
  963. package/src/graph-retrieval.test.ts +809 -0
  964. package/src/graph-retrieval.ts +823 -0
  965. package/src/graph-snapshot.ts +329 -0
  966. package/src/graph.ts +813 -0
  967. package/src/harmonic-retrieval.ts +223 -0
  968. package/src/himem.ts +154 -0
  969. package/src/hygiene.ts +87 -0
  970. package/src/identity-continuity.ts +333 -0
  971. package/src/importance.ts +328 -0
  972. package/src/importers/base.test.ts +294 -0
  973. package/src/importers/base.ts +436 -0
  974. package/src/importers/index.ts +21 -0
  975. package/src/index.ts +1204 -0
  976. package/src/intent.ts +154 -0
  977. package/src/json-extract.ts +85 -0
  978. package/src/json-store.ts +42 -0
  979. package/src/lcm/archive.ts +617 -0
  980. package/src/lcm/dag.ts +199 -0
  981. package/src/lcm/engine.ts +645 -0
  982. package/src/lcm/index.ts +7 -0
  983. package/src/lcm/queue.test.ts +178 -0
  984. package/src/lcm/queue.ts +200 -0
  985. package/src/lcm/recall.ts +117 -0
  986. package/src/lcm/schema.ts +154 -0
  987. package/src/lcm/summarizer.ts +235 -0
  988. package/src/lcm/tools.ts +191 -0
  989. package/src/lcm-engine.test.ts +660 -0
  990. package/src/legacy-hook-compat.test.ts +20 -0
  991. package/src/legacy-hook-compat.ts +45 -0
  992. package/src/lifecycle.ts +289 -0
  993. package/src/live-connectors-runner.ts +385 -0
  994. package/src/local-llm-qos.test.ts +303 -0
  995. package/src/local-llm-thinking.test.ts +292 -0
  996. package/src/local-llm.ts +1464 -0
  997. package/src/logger.ts +49 -0
  998. package/src/maintenance/archive-observations.ts +147 -0
  999. package/src/maintenance/backup-stamp.ts +3 -0
  1000. package/src/maintenance/dreams-ledger.ts +516 -0
  1001. package/src/maintenance/first-start-migration.ts +362 -0
  1002. package/src/maintenance/forget.test.ts +206 -0
  1003. package/src/maintenance/forget.ts +126 -0
  1004. package/src/maintenance/graph-edge-decay.test.ts +409 -0
  1005. package/src/maintenance/graph-edge-decay.ts +394 -0
  1006. package/src/maintenance/memory-governance-cron.ts +447 -0
  1007. package/src/maintenance/memory-governance.ts +1039 -0
  1008. package/src/maintenance/migrate-observations.ts +216 -0
  1009. package/src/maintenance/observation-ledger-utils.ts +54 -0
  1010. package/src/maintenance/pattern-reinforcement.test.ts +875 -0
  1011. package/src/maintenance/pattern-reinforcement.ts +369 -0
  1012. package/src/maintenance/purge.ts +334 -0
  1013. package/src/maintenance/rebuild-memory-lifecycle-ledger.ts +78 -0
  1014. package/src/maintenance/rebuild-memory-projection.ts +1234 -0
  1015. package/src/maintenance/rebuild-observations.ts +178 -0
  1016. package/src/maintenance/tier-stats.test.ts +378 -0
  1017. package/src/maintenance/tier-stats.ts +222 -0
  1018. package/src/mcp-memory-inspector-app.ts +421 -0
  1019. package/src/memory-action-policy.ts +80 -0
  1020. package/src/memory-cache.ts +208 -0
  1021. package/src/memory-extension/claude-code-publisher.ts +51 -0
  1022. package/src/memory-extension/codex-publisher.ts +149 -0
  1023. package/src/memory-extension/hermes-publisher.ts +51 -0
  1024. package/src/memory-extension/index.ts +100 -0
  1025. package/src/memory-extension/shared-instructions.ts +133 -0
  1026. package/src/memory-extension/types.ts +86 -0
  1027. package/src/memory-extension-host/host-discovery.ts +276 -0
  1028. package/src/memory-extension-host/index.ts +14 -0
  1029. package/src/memory-extension-host/render-extensions-block.ts +73 -0
  1030. package/src/memory-extension-host/types.ts +21 -0
  1031. package/src/memory-lifecycle-ledger-utils.ts +116 -0
  1032. package/src/memory-projection-format.ts +11 -0
  1033. package/src/memory-projection-store.ts +951 -0
  1034. package/src/memory-provenance.test.ts +196 -0
  1035. package/src/memory-provenance.ts +484 -0
  1036. package/src/memory-worth-bench.test.ts +71 -0
  1037. package/src/memory-worth-bench.ts +265 -0
  1038. package/src/memory-worth-filter.test.ts +209 -0
  1039. package/src/memory-worth-filter.ts +204 -0
  1040. package/src/memory-worth-frontmatter.test.ts +311 -0
  1041. package/src/memory-worth-outcomes.test.ts +316 -0
  1042. package/src/memory-worth-outcomes.ts +286 -0
  1043. package/src/memory-worth.test.ts +317 -0
  1044. package/src/memory-worth.ts +215 -0
  1045. package/src/message-parts/index.ts +806 -0
  1046. package/src/message-parts/message-parts.test.ts +421 -0
  1047. package/src/migrate/from-engram.ts +789 -0
  1048. package/src/model-registry.ts +313 -0
  1049. package/src/models-json.ts +76 -0
  1050. package/src/namespaces/migrate.ts +187 -0
  1051. package/src/namespaces/path.ts +25 -0
  1052. package/src/namespaces/principal.test.ts +195 -0
  1053. package/src/namespaces/principal.ts +86 -0
  1054. package/src/namespaces/search.test.ts +105 -0
  1055. package/src/namespaces/search.ts +233 -0
  1056. package/src/namespaces/storage.ts +74 -0
  1057. package/src/native-knowledge.ts +1823 -0
  1058. package/src/negative.ts +72 -0
  1059. package/src/network/tailscale.ts +179 -0
  1060. package/src/network/webdav.ts +385 -0
  1061. package/src/objective-state-writers.ts +951 -0
  1062. package/src/objective-state.ts +320 -0
  1063. package/src/onboarding/index.ts +529 -0
  1064. package/src/openai-chat-compat.ts +56 -0
  1065. package/src/operator-toolkit.ts +2132 -0
  1066. package/src/opik-exporter.test.ts +72 -0
  1067. package/src/opik-exporter.ts +587 -0
  1068. package/src/orchestrator-extraction-queue.test.ts +197 -0
  1069. package/src/orchestrator-flush.test.ts +1171 -0
  1070. package/src/orchestrator-pattern-reinforcement.test.ts +128 -0
  1071. package/src/orchestrator-source-attribution.test.ts +701 -0
  1072. package/src/orchestrator.ts +16368 -0
  1073. package/src/page-versioning.ts +450 -0
  1074. package/src/patterns-cli.ts +574 -0
  1075. package/src/peers/index.ts +54 -0
  1076. package/src/peers/migrate-from-identity-anchor.test.ts +291 -0
  1077. package/src/peers/migrate-from-identity-anchor.ts +350 -0
  1078. package/src/peers/peers.test.ts +419 -0
  1079. package/src/peers/profile-reasoner.ts +694 -0
  1080. package/src/peers/storage.ts +1350 -0
  1081. package/src/peers/types.ts +138 -0
  1082. package/src/plugin-id.ts +84 -0
  1083. package/src/policy-runtime.ts +209 -0
  1084. package/src/procedural/procedure-miner.ts +150 -0
  1085. package/src/procedural/procedure-recall.ts +93 -0
  1086. package/src/procedural/procedure-stats.ts +213 -0
  1087. package/src/procedural/procedure-types.ts +132 -0
  1088. package/src/procedural/reinforcement-core.test.ts +132 -0
  1089. package/src/procedural/reinforcement-core.ts +73 -0
  1090. package/src/profiling.test.ts +263 -0
  1091. package/src/profiling.ts +435 -0
  1092. package/src/projection/index.ts +398 -0
  1093. package/src/qmd-recall-cache.test.ts +138 -0
  1094. package/src/qmd-recall-cache.ts +111 -0
  1095. package/src/qmd.test.ts +257 -0
  1096. package/src/qmd.ts +2614 -0
  1097. package/src/reasoning-trace-recall.ts +201 -0
  1098. package/src/reasoning-trace-types.ts +235 -0
  1099. package/src/recall-audit-anomaly.test.ts +246 -0
  1100. package/src/recall-audit-anomaly.ts +297 -0
  1101. package/src/recall-audit.test.ts +51 -0
  1102. package/src/recall-audit.ts +72 -0
  1103. package/src/recall-budget-config.test.ts +87 -0
  1104. package/src/recall-disclosure-escalation.test.ts +196 -0
  1105. package/src/recall-disclosure-escalation.ts +158 -0
  1106. package/src/recall-disclosure-shaping.test.ts +146 -0
  1107. package/src/recall-disclosure.test.ts +214 -0
  1108. package/src/recall-explain-renderer.test.ts +140 -0
  1109. package/src/recall-explain-renderer.ts +356 -0
  1110. package/src/recall-mmr.test.ts +808 -0
  1111. package/src/recall-mmr.ts +607 -0
  1112. package/src/recall-qos.test.ts +85 -0
  1113. package/src/recall-qos.ts +82 -0
  1114. package/src/recall-query-policy.ts +221 -0
  1115. package/src/recall-state.test.ts +233 -0
  1116. package/src/recall-state.ts +456 -0
  1117. package/src/recall-tag-filter.ts +143 -0
  1118. package/src/recall-tokenization.ts +35 -0
  1119. package/src/recall-xray-cli.test.ts +118 -0
  1120. package/src/recall-xray-cli.ts +100 -0
  1121. package/src/recall-xray-disclosure-telemetry.test.ts +183 -0
  1122. package/src/recall-xray-renderer.test.ts +539 -0
  1123. package/src/recall-xray-renderer.ts +487 -0
  1124. package/src/recall-xray.test.ts +503 -0
  1125. package/src/recall-xray.ts +621 -0
  1126. package/src/reconstruct.ts +41 -0
  1127. package/src/release-changelog.ts +35 -0
  1128. package/src/relevance.ts +67 -0
  1129. package/src/replay/normalizers/chatgpt.ts +133 -0
  1130. package/src/replay/normalizers/claude.ts +102 -0
  1131. package/src/replay/normalizers/openclaw.ts +119 -0
  1132. package/src/replay/normalizers/shared.ts +69 -0
  1133. package/src/replay/runner.ts +197 -0
  1134. package/src/replay/types.ts +143 -0
  1135. package/src/rerank.test.ts +48 -0
  1136. package/src/rerank.ts +176 -0
  1137. package/src/resolve-auth-token.test.ts +226 -0
  1138. package/src/resolve-auth-token.ts +151 -0
  1139. package/src/resolve-provider-secret.test.ts +187 -0
  1140. package/src/resolve-provider-secret.ts +410 -0
  1141. package/src/response-guidance-recall.test.ts +3952 -0
  1142. package/src/response-guidance-recall.ts +4431 -0
  1143. package/src/resume-bundles.ts +415 -0
  1144. package/src/retrieval-agents.ts +623 -0
  1145. package/src/retrieval-tiers.ts +25 -0
  1146. package/src/retrieval.ts +104 -0
  1147. package/src/review/index.test.ts +201 -0
  1148. package/src/review/index.ts +536 -0
  1149. package/src/routing/engine.ts +162 -0
  1150. package/src/routing/store.ts +321 -0
  1151. package/src/runtime/better-sqlite.test.ts +32 -0
  1152. package/src/runtime/better-sqlite.ts +76 -0
  1153. package/src/runtime/child-process.ts +67 -0
  1154. package/src/runtime/env.ts +48 -0
  1155. package/src/sanitize.ts +58 -0
  1156. package/src/schemas.ts +449 -0
  1157. package/src/sdk-compat.ts +87 -0
  1158. package/src/search/document-scanner.ts +96 -0
  1159. package/src/search/embed-helper.ts +142 -0
  1160. package/src/search/factory.ts +189 -0
  1161. package/src/search/index.ts +10 -0
  1162. package/src/search/lancedb-backend.ts +342 -0
  1163. package/src/search/meilisearch-backend.ts +232 -0
  1164. package/src/search/noop-backend.ts +57 -0
  1165. package/src/search/orama-backend.ts +358 -0
  1166. package/src/search/port.ts +86 -0
  1167. package/src/search/remote-backend.ts +124 -0
  1168. package/src/secure-store/cipher.ts +271 -0
  1169. package/src/secure-store/cli-handlers.ts +355 -0
  1170. package/src/secure-store/cli-renderer.ts +131 -0
  1171. package/src/secure-store/header.ts +373 -0
  1172. package/src/secure-store/index.ts +137 -0
  1173. package/src/secure-store/kdf.ts +263 -0
  1174. package/src/secure-store/keyring.ts +106 -0
  1175. package/src/secure-store/metadata.ts +394 -0
  1176. package/src/secure-store/passphrase-reader.ts +252 -0
  1177. package/src/secure-store/secure-fs.ts +571 -0
  1178. package/src/secure-store/secure-store.test.ts +755 -0
  1179. package/src/semantic-chunking.ts +545 -0
  1180. package/src/semantic-consolidation.test.ts +182 -0
  1181. package/src/semantic-consolidation.ts +432 -0
  1182. package/src/semantic-rule-promotion.ts +183 -0
  1183. package/src/semantic-rule-verifier.ts +160 -0
  1184. package/src/session-integrity.ts +569 -0
  1185. package/src/session-observer-bands.ts +11 -0
  1186. package/src/session-observer-state.ts +346 -0
  1187. package/src/session-toggles.test.ts +96 -0
  1188. package/src/session-toggles.ts +159 -0
  1189. package/src/shared-context/manager.ts +810 -0
  1190. package/src/signal.ts +84 -0
  1191. package/src/skills-registry.test.ts +277 -0
  1192. package/src/skills-registry.ts +120 -0
  1193. package/src/source-attribution-roundtrip.test.ts +215 -0
  1194. package/src/source-attribution.test.ts +1425 -0
  1195. package/src/source-attribution.ts +639 -0
  1196. package/src/spaces/index.ts +627 -0
  1197. package/src/storage-paths.ts +117 -0
  1198. package/src/storage.ts +6657 -0
  1199. package/src/store-contract.ts +55 -0
  1200. package/src/summarizer.ts +844 -0
  1201. package/src/summary-snapshot.test.ts +681 -0
  1202. package/src/summary-snapshot.ts +238 -0
  1203. package/src/surfaces/dreams.test.ts +394 -0
  1204. package/src/surfaces/dreams.ts +346 -0
  1205. package/src/surfaces/heartbeat.test.ts +415 -0
  1206. package/src/surfaces/heartbeat.ts +325 -0
  1207. package/src/sync/index.ts +308 -0
  1208. package/src/targeted-fact-recall.test.ts +1694 -0
  1209. package/src/targeted-fact-recall.ts +2905 -0
  1210. package/src/taxonomy/default-taxonomy.ts +87 -0
  1211. package/src/taxonomy/index.ts +26 -0
  1212. package/src/taxonomy/resolver-doc-generator.ts +57 -0
  1213. package/src/taxonomy/resolver.ts +184 -0
  1214. package/src/taxonomy/taxonomy-loader.ts +186 -0
  1215. package/src/taxonomy/types.ts +48 -0
  1216. package/src/telemetry-transcript.ts +70 -0
  1217. package/src/temporal-index.ts +890 -0
  1218. package/src/temporal-supersession.test.ts +2703 -0
  1219. package/src/temporal-supersession.ts +493 -0
  1220. package/src/temporal-validity.test.ts +448 -0
  1221. package/src/temporal-validity.ts +123 -0
  1222. package/src/threading.ts +395 -0
  1223. package/src/tier-migration.ts +124 -0
  1224. package/src/tier-routing.ts +102 -0
  1225. package/src/tmt.ts +462 -0
  1226. package/src/tokens.test.ts +178 -0
  1227. package/src/tokens.ts +279 -0
  1228. package/src/topics.ts +147 -0
  1229. package/src/training-export/cli-date-validation.test.ts +258 -0
  1230. package/src/training-export/converter.test.ts +452 -0
  1231. package/src/training-export/converter.ts +319 -0
  1232. package/src/training-export/date-parse.ts +117 -0
  1233. package/src/training-export/index.ts +26 -0
  1234. package/src/training-export/registry.test.ts +85 -0
  1235. package/src/training-export/registry.ts +57 -0
  1236. package/src/training-export/types.ts +31 -0
  1237. package/src/transcript.ts +1179 -0
  1238. package/src/transfer/autodetect.ts +30 -0
  1239. package/src/transfer/backup.ts +138 -0
  1240. package/src/transfer/capsule-crypto.ts +485 -0
  1241. package/src/transfer/capsule-encrypt.test.ts +690 -0
  1242. package/src/transfer/capsule-export.ts +543 -0
  1243. package/src/transfer/capsule-fork.ts +375 -0
  1244. package/src/transfer/capsule-import.ts +564 -0
  1245. package/src/transfer/capsule-merge.ts +433 -0
  1246. package/src/transfer/conflict-policy.ts +16 -0
  1247. package/src/transfer/constants.ts +13 -0
  1248. package/src/transfer/exclusions.ts +37 -0
  1249. package/src/transfer/export-json.ts +65 -0
  1250. package/src/transfer/export-md.ts +59 -0
  1251. package/src/transfer/export-sqlite.ts +52 -0
  1252. package/src/transfer/fs-utils.ts +269 -0
  1253. package/src/transfer/import-json.ts +108 -0
  1254. package/src/transfer/import-md.ts +84 -0
  1255. package/src/transfer/import-sqlite.ts +100 -0
  1256. package/src/transfer/integrity.ts +71 -0
  1257. package/src/transfer/sqlite-schema.ts +16 -0
  1258. package/src/transfer/types.ts +297 -0
  1259. package/src/trust-zones.ts +1186 -0
  1260. package/src/types.ts +3074 -0
  1261. package/src/user-model.test.ts +124 -0
  1262. package/src/user-model.ts +162 -0
  1263. package/src/utility-learner.ts +353 -0
  1264. package/src/utility-runtime.ts +88 -0
  1265. package/src/utility-telemetry.ts +215 -0
  1266. package/src/utils/category-dir.ts +44 -0
  1267. package/src/utils/errno.ts +6 -0
  1268. package/src/utils/iso-timestamp.test.ts +37 -0
  1269. package/src/utils/iso-timestamp.ts +164 -0
  1270. package/src/utils/path.ts +26 -0
  1271. package/src/verified-recall.ts +138 -0
  1272. package/src/version-utils.test.ts +10 -0
  1273. package/src/version-utils.ts +9 -0
  1274. package/src/whitespace.ts +10 -0
  1275. package/src/work/board.ts +359 -0
  1276. package/src/work/boundary.ts +107 -0
  1277. package/src/work/storage.ts +436 -0
  1278. package/src/work/types.ts +82 -0
  1279. package/src/work-product-ledger.ts +265 -0
  1280. package/dist/access-service-BkXt3di1.d.ts +0 -2039
  1281. package/dist/capsule-crypto-SJS5VVAP.js +0 -18
  1282. package/dist/capsule-export-LLEVB2RG.js +0 -17
  1283. package/dist/capsule-import-UW45R2MZ.js +0 -16
  1284. package/dist/capsule-merge-DI7PNQ2H.js +0 -189
  1285. package/dist/chunk-2LGMW3DJ.js +0 -111
  1286. package/dist/chunk-2YMTO4ZJ.js +0 -265
  1287. package/dist/chunk-2YMTO4ZJ.js.map +0 -1
  1288. package/dist/chunk-363MWCD3.js +0 -9683
  1289. package/dist/chunk-363MWCD3.js.map +0 -1
  1290. package/dist/chunk-36CTNQY7.js +0 -1554
  1291. package/dist/chunk-36CTNQY7.js.map +0 -1
  1292. package/dist/chunk-457A4P3L.js +0 -119
  1293. package/dist/chunk-457A4P3L.js.map +0 -1
  1294. package/dist/chunk-4DXC6HQQ.js +0 -1837
  1295. package/dist/chunk-4DXC6HQQ.js.map +0 -1
  1296. package/dist/chunk-4IS4SXIQ.js +0 -2040
  1297. package/dist/chunk-57QNCUEZ.js +0 -1914
  1298. package/dist/chunk-57QNCUEZ.js.map +0 -1
  1299. package/dist/chunk-6AUUAZEX.js +0 -150
  1300. package/dist/chunk-6AUUAZEX.js.map +0 -1
  1301. package/dist/chunk-6TBWYBJ3.js +0 -236
  1302. package/dist/chunk-6XA7UN4Z.js +0 -135
  1303. package/dist/chunk-6Z6UH6TK.js +0 -2129
  1304. package/dist/chunk-6Z6UH6TK.js.map +0 -1
  1305. package/dist/chunk-74EMIVE4.js +0 -329
  1306. package/dist/chunk-74EMIVE4.js.map +0 -1
  1307. package/dist/chunk-74WWN7ZW.js +0 -82
  1308. package/dist/chunk-74WWN7ZW.js.map +0 -1
  1309. package/dist/chunk-767ODGE6.js +0 -183
  1310. package/dist/chunk-A4ACKWIW.js +0 -289
  1311. package/dist/chunk-A4ACKWIW.js.map +0 -1
  1312. package/dist/chunk-ASAITVLA.js +0 -64
  1313. package/dist/chunk-ASAITVLA.js.map +0 -1
  1314. package/dist/chunk-C5HUWVH2.js +0 -891
  1315. package/dist/chunk-C5HUWVH2.js.map +0 -1
  1316. package/dist/chunk-D54LZC5L.js +0 -147
  1317. package/dist/chunk-DF3RVK3X.js +0 -119
  1318. package/dist/chunk-DF3RVK3X.js.map +0 -1
  1319. package/dist/chunk-E6K4NIEU.js +0 -747
  1320. package/dist/chunk-E6K4NIEU.js.map +0 -1
  1321. package/dist/chunk-EEQLFRUM.js +0 -89
  1322. package/dist/chunk-EQINRHYR.js +0 -672
  1323. package/dist/chunk-EQINRHYR.js.map +0 -1
  1324. package/dist/chunk-ETOW6ACV.js +0 -158
  1325. package/dist/chunk-ETOW6ACV.js.map +0 -1
  1326. package/dist/chunk-EYNQTST2.js +0 -721
  1327. package/dist/chunk-FYIYMQ5N.js +0 -221
  1328. package/dist/chunk-FYIYMQ5N.js.map +0 -1
  1329. package/dist/chunk-G2WADRQ3.js +0 -219
  1330. package/dist/chunk-G4SK7DSQ.js +0 -121
  1331. package/dist/chunk-GGD5W7TB.js +0 -105
  1332. package/dist/chunk-GGD5W7TB.js.map +0 -1
  1333. package/dist/chunk-GVPWB7EY.js +0 -390
  1334. package/dist/chunk-GVPWB7EY.js.map +0 -1
  1335. package/dist/chunk-HJYHRE4S.js +0 -647
  1336. package/dist/chunk-I6BQZSML.js +0 -1451
  1337. package/dist/chunk-I6BQZSML.js.map +0 -1
  1338. package/dist/chunk-IBX3VFOM.js +0 -446
  1339. package/dist/chunk-IBX3VFOM.js.map +0 -1
  1340. package/dist/chunk-IXEJRKCZ.js +0 -18
  1341. package/dist/chunk-JBMSGZEQ.js +0 -441
  1342. package/dist/chunk-JBMSGZEQ.js.map +0 -1
  1343. package/dist/chunk-JRNQ3RNA.js +0 -284
  1344. package/dist/chunk-JRNQ3RNA.js.map +0 -1
  1345. package/dist/chunk-K6WK37A6.js +0 -865
  1346. package/dist/chunk-K6WK37A6.js.map +0 -1
  1347. package/dist/chunk-KBYWQWSB.js +0 -271
  1348. package/dist/chunk-KUHRUM6B.js +0 -14397
  1349. package/dist/chunk-KUHRUM6B.js.map +0 -1
  1350. package/dist/chunk-KWBPHZUU.js +0 -83
  1351. package/dist/chunk-KWBPHZUU.js.map +0 -1
  1352. package/dist/chunk-LIO5X3CM.js +0 -596
  1353. package/dist/chunk-MARWOCVP.js +0 -48
  1354. package/dist/chunk-MCC6KDQF.js +0 -5095
  1355. package/dist/chunk-MCC6KDQF.js.map +0 -1
  1356. package/dist/chunk-N5AKDXAI.js +0 -74
  1357. package/dist/chunk-NN3LPQ5D.js +0 -936
  1358. package/dist/chunk-NN3LPQ5D.js.map +0 -1
  1359. package/dist/chunk-O4XJUPSF.js +0 -533
  1360. package/dist/chunk-O4XJUPSF.js.map +0 -1
  1361. package/dist/chunk-OA3L7BFR.js +0 -183
  1362. package/dist/chunk-OA3L7BFR.js.map +0 -1
  1363. package/dist/chunk-OR64ZGRZ.js +0 -23
  1364. package/dist/chunk-P73JTV34.js +0 -275
  1365. package/dist/chunk-P73JTV34.js.map +0 -1
  1366. package/dist/chunk-P77UEOU2.js +0 -1521
  1367. package/dist/chunk-P77UEOU2.js.map +0 -1
  1368. package/dist/chunk-PB5KW5PL.js +0 -118
  1369. package/dist/chunk-PHNGXFQ6.js +0 -623
  1370. package/dist/chunk-PHNGXFQ6.js.map +0 -1
  1371. package/dist/chunk-QIGOEM65.js +0 -228
  1372. package/dist/chunk-RXTFCYQF.js +0 -108
  1373. package/dist/chunk-S2JJBLJG.js +0 -2101
  1374. package/dist/chunk-S2JJBLJG.js.map +0 -1
  1375. package/dist/chunk-S3IP6R6K.js +0 -219
  1376. package/dist/chunk-S3IP6R6K.js.map +0 -1
  1377. package/dist/chunk-SRBJUAMP.js +0 -403
  1378. package/dist/chunk-SRBJUAMP.js.map +0 -1
  1379. package/dist/chunk-URB2WSKZ.js +0 -350
  1380. package/dist/chunk-URB2WSKZ.js.map +0 -1
  1381. package/dist/chunk-VQXK37XA.js +0 -26
  1382. package/dist/chunk-VQXK37XA.js.map +0 -1
  1383. package/dist/chunk-VTU2B4VF.js +0 -146
  1384. package/dist/chunk-VTU2B4VF.js.map +0 -1
  1385. package/dist/chunk-VX2IUQFE.js +0 -613
  1386. package/dist/chunk-VX2IUQFE.js.map +0 -1
  1387. package/dist/chunk-WGK4VHGP.js +0 -4292
  1388. package/dist/chunk-WGK4VHGP.js.map +0 -1
  1389. package/dist/chunk-WTFWLUSX.js +0 -827
  1390. package/dist/chunk-WTFWLUSX.js.map +0 -1
  1391. package/dist/chunk-XJKFSSDW.js +0 -726
  1392. package/dist/chunk-XJKFSSDW.js.map +0 -1
  1393. package/dist/chunk-XMHBH5H6.js +0 -283
  1394. package/dist/chunk-XMHBH5H6.js.map +0 -1
  1395. package/dist/chunk-XMVFHBHT.js +0 -277
  1396. package/dist/chunk-Y5KDIOKF.js +0 -2403
  1397. package/dist/chunk-Y5KDIOKF.js.map +0 -1
  1398. package/dist/chunk-YNB73F22.js +0 -137
  1399. package/dist/chunk-YNB73F22.js.map +0 -1
  1400. package/dist/chunk-Z2E7VW55.js +0 -335
  1401. package/dist/chunk-Z2E7VW55.js.map +0 -1
  1402. package/dist/chunk-Z5S5HNGY.js +0 -2280
  1403. package/dist/chunk-Z5S5HNGY.js.map +0 -1
  1404. package/dist/chunk-ZL4S7ARC.js +0 -53
  1405. package/dist/chunk-ZTSE2ZJ6.js +0 -190
  1406. package/dist/chunk-ZTSE2ZJ6.js.map +0 -1
  1407. package/dist/cli-Cvy2SNhF.d.ts +0 -1259
  1408. package/dist/codex-materialize-CQlLTzke.d.ts +0 -139
  1409. package/dist/connectors-cli-DFGtY2DB.d.ts +0 -257
  1410. package/dist/contradiction-review-5LTTVDQV.js +0 -22
  1411. package/dist/contradiction-scan-3Z6YW7YA.js +0 -413
  1412. package/dist/contradiction-scan-3Z6YW7YA.js.map +0 -1
  1413. package/dist/engine-FOC3IJLA.js +0 -28
  1414. package/dist/fs-utils-IRVUFB6G.js +0 -30
  1415. package/dist/graph-edge-decay-PWB63GRE.js +0 -207
  1416. package/dist/index-1qIcnbG1.d.ts +0 -34
  1417. package/dist/memory-governance-F3QOJGEY.js +0 -37
  1418. package/dist/memory-projection-store-CY8TU40w.d.ts +0 -222
  1419. package/dist/orchestrator-AOQMo7QI.d.ts +0 -1784
  1420. package/dist/path-RMTY5Y5A.js +0 -9
  1421. package/dist/port-B6VEDIkC.d.ts +0 -53
  1422. package/dist/resolution-YGIBORXI.js +0 -101
  1423. package/dist/resolution-YGIBORXI.js.map +0 -1
  1424. package/dist/secure-store-4R2GSO7S.js +0 -156
  1425. package/dist/semantic-consolidation-ByBXb-sf.d.ts +0 -180
  1426. package/dist/state-store-3EH7HYIN.js +0 -16
  1427. package/dist/types-V3FJ26TF.js +0 -30
  1428. /package/dist/{capsule-crypto-SJS5VVAP.js.map → action-confidence.js.map} +0 -0
  1429. /package/dist/{capsule-export-LLEVB2RG.js.map → adapters/claude-code.js.map} +0 -0
  1430. /package/dist/{capsule-import-UW45R2MZ.js.map → adapters/codex.js.map} +0 -0
  1431. /package/dist/{contradiction-review-5LTTVDQV.js.map → adapters/hermes.js.map} +0 -0
  1432. /package/dist/{engine-FOC3IJLA.js.map → adapters/index.js.map} +0 -0
  1433. /package/dist/{fs-utils-IRVUFB6G.js.map → adapters/registry.js.map} +0 -0
  1434. /package/dist/{memory-governance-F3QOJGEY.js.map → adapters/replit.js.map} +0 -0
  1435. /package/dist/{path-RMTY5Y5A.js.map → adapters/types.js.map} +0 -0
  1436. /package/dist/{secure-store-4R2GSO7S.js.map → capsule-crypto-5CYAGVC5.js.map} +0 -0
  1437. /package/dist/{capsule-merge-DI7PNQ2H.js.map → capsule-merge-4MGKE7C5.js.map} +0 -0
  1438. /package/dist/{chunk-G4SK7DSQ.js.map → chunk-2WWLHTZY.js.map} +0 -0
  1439. /package/dist/{chunk-KBYWQWSB.js.map → chunk-4CRG46BG.js.map} +0 -0
  1440. /package/dist/{chunk-LIO5X3CM.js.map → chunk-7IASACLB.js.map} +0 -0
  1441. /package/dist/{chunk-EYNQTST2.js.map → chunk-EFJ3MQ4V.js.map} +0 -0
  1442. /package/dist/{chunk-D54LZC5L.js.map → chunk-FDU6HUUL.js.map} +0 -0
  1443. /package/dist/{chunk-QIGOEM65.js.map → chunk-GGKRUQOO.js.map} +0 -0
  1444. /package/dist/{chunk-HJYHRE4S.js.map → chunk-GL6I6MEQ.js.map} +0 -0
  1445. /package/dist/{state-store-3EH7HYIN.js.map → chunk-HHLLAQGZ.js.map} +0 -0
  1446. /package/dist/{chunk-4IS4SXIQ.js.map → chunk-HXXBL2KD.js.map} +0 -0
  1447. /package/dist/{chunk-767ODGE6.js.map → chunk-KNKUID7G.js.map} +0 -0
  1448. /package/dist/{chunk-6TBWYBJ3.js.map → chunk-LPMVBPA3.js.map} +0 -0
  1449. /package/dist/{chunk-PB5KW5PL.js.map → chunk-MC26UJIM.js.map} +0 -0
  1450. /package/dist/{chunk-ZL4S7ARC.js.map → chunk-MT4HVDUZ.js.map} +0 -0
  1451. /package/dist/{chunk-G2WADRQ3.js.map → chunk-MY6TPVXW.js.map} +0 -0
  1452. /package/dist/{chunk-OR64ZGRZ.js.map → chunk-NNVTUXEB.js.map} +0 -0
  1453. /package/dist/{chunk-RXTFCYQF.js.map → chunk-P4NEIHUT.js.map} +0 -0
  1454. /package/dist/{chunk-IXEJRKCZ.js.map → chunk-QRNI5JBH.js.map} +0 -0
  1455. /package/dist/{chunk-EEQLFRUM.js.map → chunk-RRF5UOBJ.js.map} +0 -0
  1456. /package/dist/{types-V3FJ26TF.js.map → chunk-SEDEKFYQ.js.map} +0 -0
  1457. /package/dist/{chunk-2LGMW3DJ.js.map → chunk-U3PN77QT.js.map} +0 -0
  1458. /package/dist/{chunk-XMVFHBHT.js.map → chunk-U3WSW6PZ.js.map} +0 -0
  1459. /package/dist/{chunk-N5AKDXAI.js.map → chunk-UWVJF25J.js.map} +0 -0
  1460. /package/dist/{chunk-MARWOCVP.js.map → chunk-XIG5PDM7.js.map} +0 -0
  1461. /package/dist/{chunk-6XA7UN4Z.js.map → chunk-XVZ7B3HG.js.map} +0 -0
  1462. /package/dist/{graph-edge-decay-PWB63GRE.js.map → graph-edge-decay-5DI5GUNL.js.map} +0 -0
@@ -1,4292 +0,0 @@
1
- import {
2
- importCapsule
3
- } from "./chunk-QIGOEM65.js";
4
- import {
5
- applyTagFilter,
6
- normalizeTags,
7
- parseTagMatch
8
- } from "./chunk-BT7NVCML.js";
9
- import {
10
- toRecallExplainJson
11
- } from "./chunk-O4XJUPSF.js";
12
- import {
13
- decideDisclosureEscalation
14
- } from "./chunk-H7XKCNR6.js";
15
- import {
16
- buildProposedActions,
17
- buildQualityScore,
18
- groupActionsByStatus,
19
- listMemoryGovernanceRuns,
20
- readMemoryGovernanceRunArtifact,
21
- runMemoryGovernance
22
- } from "./chunk-EYNQTST2.js";
23
- import {
24
- clusterByKey,
25
- resolveGitContext
26
- } from "./chunk-D54LZC5L.js";
27
- import {
28
- getTrustZoneStoreStatus,
29
- isTrustZoneName,
30
- listTrustZoneRecords,
31
- promoteTrustZoneRecord,
32
- scoreTrustZoneProvenance,
33
- seedTrustZoneDemoDataset,
34
- summarizeTrustZonePromotionReadiness
35
- } from "./chunk-EQINRHYR.js";
36
- import {
37
- estimateRecallTokens
38
- } from "./chunk-2YMTO4ZJ.js";
39
- import {
40
- recordMemoryOutcome
41
- } from "./chunk-EIR5VLIH.js";
42
- import {
43
- recordObjectiveStateSnapshotsFromObservedMessages
44
- } from "./chunk-HJYHRE4S.js";
45
- import {
46
- objectiveStateStoreOverrideForNamespace
47
- } from "./chunk-5UM2VJ6D.js";
48
- import {
49
- buildGraphSnapshot
50
- } from "./chunk-PCUKNJAZ.js";
51
- import {
52
- wrapWorkLayerContext
53
- } from "./chunk-EEQLFRUM.js";
54
- import {
55
- formatProfileTraceAscii
56
- } from "./chunk-NBNN5GOB.js";
57
- import {
58
- persistExplicitCapture,
59
- queueExplicitCaptureForReview,
60
- validateExplicitCaptureInput
61
- } from "./chunk-GVPWB7EY.js";
62
- import {
63
- buildProcedurePersistBody,
64
- normalizeProcedureSteps
65
- } from "./chunk-QDW3E4RD.js";
66
- import {
67
- CrossNamespaceBudget
68
- } from "./chunk-GDFS42HT.js";
69
- import {
70
- filterTrajectoriesByLookbackDays,
71
- readCausalTrajectoryRecords
72
- } from "./chunk-G2WADRQ3.js";
73
- import {
74
- defaultCapsulesDir
75
- } from "./chunk-74EMIVE4.js";
76
- import {
77
- canReadNamespace,
78
- canWriteNamespace,
79
- defaultNamespaceForPrincipal,
80
- recallNamespacesForPrincipal,
81
- resolvePrincipal
82
- } from "./chunk-N5AKDXAI.js";
83
- import {
84
- FileCalendarSource,
85
- buildBriefing,
86
- parseBriefingFocus,
87
- parseBriefingWindow
88
- } from "./chunk-WTFWLUSX.js";
89
- import {
90
- parseEntityFile
91
- } from "./chunk-MCC6KDQF.js";
92
- import {
93
- DEFAULT_RECALL_DISCLOSURE,
94
- isRecallDisclosure
95
- } from "./chunk-VQXK37XA.js";
96
- import {
97
- inferMemoryStatus,
98
- toMemoryPathRel
99
- } from "./chunk-RULE4VG5.js";
100
- import {
101
- normalizeProjectionPreview,
102
- normalizeProjectionTags
103
- } from "./chunk-SCU65EZI.js";
104
- import {
105
- getMemoryProjectionPath
106
- } from "./chunk-XJKFSSDW.js";
107
- import {
108
- log
109
- } from "./chunk-2ODBA7MQ.js";
110
- import {
111
- AccessAuditAdapter
112
- } from "./chunk-TVVEYCNW.js";
113
- import {
114
- AccessIdempotencyStore,
115
- hashAccessIdempotencyPayload
116
- } from "./chunk-XKECPATV.js";
117
- import {
118
- exportCapsule
119
- } from "./chunk-P73JTV34.js";
120
-
121
- // src/access-service.ts
122
- import { stat } from "fs/promises";
123
- import * as nodeFs from "fs/promises";
124
- import { constants as fsConstants } from "fs";
125
- import { createHash } from "crypto";
126
- import { ZodError } from "zod";
127
-
128
- // src/work/storage.ts
129
- import path from "path";
130
- import { randomUUID } from "crypto";
131
- import { mkdir, readdir, readFile, rm, writeFile } from "fs/promises";
132
- var TASK_TRANSITIONS = {
133
- todo: /* @__PURE__ */ new Set(["in_progress", "blocked", "cancelled"]),
134
- in_progress: /* @__PURE__ */ new Set(["todo", "blocked", "done", "cancelled"]),
135
- blocked: /* @__PURE__ */ new Set(["todo", "in_progress", "cancelled"]),
136
- done: /* @__PURE__ */ new Set(),
137
- cancelled: /* @__PURE__ */ new Set()
138
- };
139
- function serializeFrontmatter(values) {
140
- const lines = Object.entries(values).map(([k, v]) => `${k}: ${JSON.stringify(v)}`);
141
- return `---
142
- ${lines.join("\n")}
143
- ---`;
144
- }
145
- function parseFrontmatter(raw) {
146
- const match = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
147
- if (!match) return null;
148
- const fm = match[1] ?? "";
149
- const body = match[2] ?? "";
150
- const data = {};
151
- for (const line of fm.split("\n")) {
152
- if (!line.trim()) continue;
153
- const idx = line.indexOf(":");
154
- if (idx <= 0) continue;
155
- const key = line.slice(0, idx).trim();
156
- const rawValue = line.slice(idx + 1).trim();
157
- try {
158
- data[key] = JSON.parse(rawValue);
159
- } catch {
160
- data[key] = rawValue;
161
- }
162
- }
163
- return { data, body };
164
- }
165
- function toSafeSlug(value) {
166
- let slug = value.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-");
167
- let start = 0;
168
- while (start < slug.length && slug[start] === "-") start++;
169
- let end = slug.length;
170
- while (end > start && slug[end - 1] === "-") end--;
171
- return slug.slice(start, end).slice(0, 80);
172
- }
173
- var WORK_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9-]{0,127}$/;
174
- function makeId(prefix, titleOrName, now) {
175
- const slug = toSafeSlug(titleOrName) || "item";
176
- const nonce = randomUUID().slice(0, 8);
177
- return `${prefix}-${now.getTime()}-${slug}-${nonce}`;
178
- }
179
- function assertValidWorkId(id, kind) {
180
- if (!WORK_ID_PATTERN.test(id)) {
181
- throw new Error(`invalid ${kind} id: ${id}`);
182
- }
183
- }
184
- function ensureString(value, fallback = "") {
185
- return typeof value === "string" ? value : fallback;
186
- }
187
- function ensureStringArray(value) {
188
- if (!Array.isArray(value)) return [];
189
- return value.filter((entry) => typeof entry === "string");
190
- }
191
- function ensureNullableString(value) {
192
- return typeof value === "string" ? value : null;
193
- }
194
- function ensureTaskStatus(value) {
195
- if (value === "todo" || value === "in_progress" || value === "blocked" || value === "done" || value === "cancelled") {
196
- return value;
197
- }
198
- return "todo";
199
- }
200
- function ensureTaskPriority(value) {
201
- if (value === "low" || value === "medium" || value === "high") return value;
202
- return "medium";
203
- }
204
- function ensureProjectStatus(value) {
205
- if (value === "active" || value === "on_hold" || value === "completed" || value === "archived") return value;
206
- return "active";
207
- }
208
- var WorkStorage = class {
209
- constructor(memoryDir) {
210
- this.memoryDir = memoryDir;
211
- this.tasksDir = path.join(memoryDir, "work", "tasks");
212
- this.projectsDir = path.join(memoryDir, "work", "projects");
213
- }
214
- memoryDir;
215
- tasksDir;
216
- projectsDir;
217
- async ensureDirectories() {
218
- await mkdir(this.tasksDir, { recursive: true });
219
- await mkdir(this.projectsDir, { recursive: true });
220
- }
221
- taskPath(id) {
222
- assertValidWorkId(id, "task");
223
- return path.join(this.tasksDir, `${id}.md`);
224
- }
225
- projectPath(id) {
226
- assertValidWorkId(id, "project");
227
- return path.join(this.projectsDir, `${id}.md`);
228
- }
229
- serializeTask(task) {
230
- return `${serializeFrontmatter(task)}
231
-
232
- ${task.description}
233
- `;
234
- }
235
- serializeProject(project) {
236
- return `${serializeFrontmatter(project)}
237
-
238
- ${project.description}
239
- `;
240
- }
241
- parseTask(raw) {
242
- const parsed = parseFrontmatter(raw);
243
- if (!parsed) return null;
244
- const d = parsed.data;
245
- return {
246
- id: ensureString(d.id),
247
- title: ensureString(d.title),
248
- description: ensureString(d.description, parsed.body.trim()),
249
- status: ensureTaskStatus(d.status),
250
- priority: ensureTaskPriority(d.priority),
251
- owner: ensureNullableString(d.owner),
252
- assignee: ensureNullableString(d.assignee),
253
- projectId: ensureNullableString(d.projectId),
254
- tags: ensureStringArray(d.tags),
255
- dueAt: ensureNullableString(d.dueAt),
256
- createdAt: ensureString(d.createdAt),
257
- updatedAt: ensureString(d.updatedAt)
258
- };
259
- }
260
- parseProject(raw) {
261
- const parsed = parseFrontmatter(raw);
262
- if (!parsed) return null;
263
- const d = parsed.data;
264
- return {
265
- id: ensureString(d.id),
266
- name: ensureString(d.name),
267
- description: ensureString(d.description, parsed.body.trim()),
268
- status: ensureProjectStatus(d.status),
269
- owner: ensureNullableString(d.owner),
270
- tags: ensureStringArray(d.tags),
271
- taskIds: ensureStringArray(d.taskIds),
272
- createdAt: ensureString(d.createdAt),
273
- updatedAt: ensureString(d.updatedAt)
274
- };
275
- }
276
- async createTask(input, now = /* @__PURE__ */ new Date()) {
277
- await this.ensureDirectories();
278
- const timestamp = now.toISOString();
279
- const task = {
280
- id: input.id ?? makeId("task", input.title, now),
281
- title: input.title,
282
- description: input.description ?? "",
283
- status: input.status ?? "todo",
284
- priority: input.priority ?? "medium",
285
- owner: input.owner ?? null,
286
- assignee: input.assignee ?? null,
287
- projectId: input.projectId ?? null,
288
- tags: input.tags ?? [],
289
- dueAt: input.dueAt ?? null,
290
- createdAt: timestamp,
291
- updatedAt: timestamp
292
- };
293
- if (task.projectId) {
294
- const project = await this.getProject(task.projectId);
295
- if (!project) {
296
- throw new Error(`project not found: ${task.projectId}`);
297
- }
298
- }
299
- await writeFile(this.taskPath(task.id), this.serializeTask(task), "utf-8");
300
- if (task.projectId) {
301
- await this.addTaskIdToProject(task.projectId, task.id, now);
302
- }
303
- return task;
304
- }
305
- async getTask(id) {
306
- try {
307
- const raw = await readFile(this.taskPath(id), "utf-8");
308
- return this.parseTask(raw);
309
- } catch {
310
- return null;
311
- }
312
- }
313
- async listTasks(filter) {
314
- await this.ensureDirectories();
315
- const entries = await readdir(this.tasksDir, { withFileTypes: true });
316
- const out = [];
317
- for (const entry of entries) {
318
- if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
319
- const raw = await readFile(path.join(this.tasksDir, entry.name), "utf-8");
320
- const task = this.parseTask(raw);
321
- if (!task) continue;
322
- if (filter?.status && task.status !== filter.status) continue;
323
- if (filter?.owner && task.owner !== filter.owner) continue;
324
- if (filter?.assignee && task.assignee !== filter.assignee) continue;
325
- if (filter?.projectId && task.projectId !== filter.projectId) continue;
326
- out.push(task);
327
- }
328
- out.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
329
- return out;
330
- }
331
- async updateTask(id, patch, now = /* @__PURE__ */ new Date(), options) {
332
- const existing = await this.getTask(id);
333
- if (!existing) return null;
334
- const projectIdPatched = Object.prototype.hasOwnProperty.call(patch, "projectId");
335
- const statusPatched = Object.prototype.hasOwnProperty.call(patch, "status");
336
- const nextProjectId = projectIdPatched ? patch.projectId ?? null : existing.projectId;
337
- if (statusPatched && patch.status && existing.status !== patch.status && options?.skipStatusTransitionValidation !== true && !TASK_TRANSITIONS[existing.status].has(patch.status)) {
338
- throw new Error(`invalid task status transition: ${existing.status} -> ${patch.status}`);
339
- }
340
- if (projectIdPatched && nextProjectId) {
341
- const nextProject = await this.getProject(nextProjectId);
342
- if (!nextProject) {
343
- throw new Error(`project not found: ${nextProjectId}`);
344
- }
345
- }
346
- if (projectIdPatched && existing.projectId !== nextProjectId) {
347
- if (existing.projectId) {
348
- await this.removeTaskIdFromProject(existing.projectId, id, now);
349
- }
350
- if (nextProjectId) {
351
- await this.addTaskIdToProject(nextProjectId, id, now);
352
- }
353
- }
354
- const next = {
355
- ...existing,
356
- ...patch,
357
- projectId: nextProjectId,
358
- tags: patch.tags ?? existing.tags,
359
- updatedAt: now.toISOString()
360
- };
361
- await writeFile(this.taskPath(id), this.serializeTask(next), "utf-8");
362
- return next;
363
- }
364
- async transitionTask(id, nextStatus, now = /* @__PURE__ */ new Date()) {
365
- const existing = await this.getTask(id);
366
- if (!existing) throw new Error(`task not found: ${id}`);
367
- if (existing.status === nextStatus) return existing;
368
- if (!TASK_TRANSITIONS[existing.status].has(nextStatus)) {
369
- throw new Error(`invalid task status transition: ${existing.status} -> ${nextStatus}`);
370
- }
371
- const updated = await this.updateTask(id, { status: nextStatus }, now);
372
- if (!updated) throw new Error(`task not found after update: ${id}`);
373
- return updated;
374
- }
375
- async deleteTask(id) {
376
- try {
377
- const existing = await this.getTask(id);
378
- await rm(this.taskPath(id));
379
- if (existing?.projectId) {
380
- await this.removeTaskIdFromProject(existing.projectId, id);
381
- }
382
- return true;
383
- } catch {
384
- return false;
385
- }
386
- }
387
- async createProject(input, now = /* @__PURE__ */ new Date()) {
388
- await this.ensureDirectories();
389
- const timestamp = now.toISOString();
390
- const project = {
391
- id: input.id ?? makeId("project", input.name, now),
392
- name: input.name,
393
- description: input.description ?? "",
394
- status: input.status ?? "active",
395
- owner: input.owner ?? null,
396
- tags: input.tags ?? [],
397
- taskIds: [],
398
- createdAt: timestamp,
399
- updatedAt: timestamp
400
- };
401
- await writeFile(this.projectPath(project.id), this.serializeProject(project), "utf-8");
402
- return project;
403
- }
404
- async getProject(id) {
405
- try {
406
- const raw = await readFile(this.projectPath(id), "utf-8");
407
- return this.parseProject(raw);
408
- } catch {
409
- return null;
410
- }
411
- }
412
- async listProjects() {
413
- await this.ensureDirectories();
414
- const entries = await readdir(this.projectsDir, { withFileTypes: true });
415
- const out = [];
416
- for (const entry of entries) {
417
- if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
418
- const raw = await readFile(path.join(this.projectsDir, entry.name), "utf-8");
419
- const project = this.parseProject(raw);
420
- if (project) out.push(project);
421
- }
422
- out.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
423
- return out;
424
- }
425
- async updateProject(id, patch, now = /* @__PURE__ */ new Date()) {
426
- const existing = await this.getProject(id);
427
- if (!existing) return null;
428
- const next = {
429
- ...existing,
430
- ...patch,
431
- tags: patch.tags ?? existing.tags,
432
- taskIds: patch.taskIds ? [...patch.taskIds].sort() : existing.taskIds,
433
- updatedAt: now.toISOString()
434
- };
435
- await writeFile(this.projectPath(id), this.serializeProject(next), "utf-8");
436
- return next;
437
- }
438
- async deleteProject(id) {
439
- try {
440
- const existing = await this.getProject(id);
441
- if (existing) {
442
- for (const taskId of existing.taskIds) {
443
- await this.updateTask(taskId, { projectId: null });
444
- }
445
- }
446
- await rm(this.projectPath(id));
447
- return true;
448
- } catch {
449
- return false;
450
- }
451
- }
452
- async linkTaskToProject(taskId, projectId, now = /* @__PURE__ */ new Date()) {
453
- const task = await this.getTask(taskId);
454
- if (!task) throw new Error(`task not found: ${taskId}`);
455
- const project = await this.getProject(projectId);
456
- if (!project) throw new Error(`project not found: ${projectId}`);
457
- const updatedTask = await this.updateTask(taskId, { projectId }, now);
458
- if (!updatedTask) throw new Error(`task not found after update: ${taskId}`);
459
- const updatedProject = await this.getProject(projectId);
460
- if (!updatedProject) throw new Error(`project not found after update: ${projectId}`);
461
- return { task: updatedTask, project: updatedProject };
462
- }
463
- async removeTaskIdFromProject(projectId, taskId, now = /* @__PURE__ */ new Date()) {
464
- const project = await this.getProject(projectId);
465
- if (!project) return;
466
- const filtered = project.taskIds.filter((id) => id !== taskId);
467
- if (filtered.length === project.taskIds.length) return;
468
- await this.updateProject(projectId, { taskIds: filtered }, now);
469
- }
470
- async addTaskIdToProject(projectId, taskId, now = /* @__PURE__ */ new Date()) {
471
- const project = await this.getProject(projectId);
472
- if (!project) return;
473
- const taskIds = new Set(project.taskIds);
474
- taskIds.add(taskId);
475
- await this.updateProject(projectId, { taskIds: Array.from(taskIds) }, now);
476
- }
477
- };
478
-
479
- // src/work/board.ts
480
- var BOARD_STATUS_ORDER = [
481
- "todo",
482
- "in_progress",
483
- "blocked",
484
- "done",
485
- "cancelled"
486
- ];
487
- var BOARD_STATUS_LABEL = {
488
- todo: "Todo",
489
- in_progress: "In Progress",
490
- blocked: "Blocked",
491
- done: "Done",
492
- cancelled: "Cancelled"
493
- };
494
- var PRIORITY_WEIGHT = {
495
- high: 0,
496
- medium: 1,
497
- low: 2
498
- };
499
- function stableSortTasks(tasks) {
500
- return [...tasks].sort((a, b) => {
501
- const priorityCmp = PRIORITY_WEIGHT[a.priority] - PRIORITY_WEIGHT[b.priority];
502
- if (priorityCmp !== 0) return priorityCmp;
503
- const createdCmp = a.createdAt.localeCompare(b.createdAt);
504
- if (createdCmp !== 0) return createdCmp;
505
- return a.id.localeCompare(b.id);
506
- });
507
- }
508
- function projectMatches(task, projectId) {
509
- if (!projectId) return true;
510
- return task.projectId === projectId;
511
- }
512
- function assertValidImportEnums(item) {
513
- if (!["todo", "in_progress", "blocked", "done", "cancelled"].includes(item.status)) {
514
- throw new Error(`invalid task status in snapshot for ${item.id}: ${item.status}`);
515
- }
516
- if (!["low", "medium", "high"].includes(item.priority)) {
517
- throw new Error(`invalid task priority in snapshot for ${item.id}: ${item.priority}`);
518
- }
519
- }
520
- function normalizeImportedProjectId(rawValue, taskId, fallbackForUndefined) {
521
- if (rawValue === void 0) return fallbackForUndefined;
522
- if (rawValue === null) return null;
523
- if (typeof rawValue === "string") {
524
- const trimmed = rawValue.trim();
525
- return trimmed.length > 0 ? trimmed : null;
526
- }
527
- throw new Error(`invalid task projectId in snapshot for ${taskId}`);
528
- }
529
- function normalizeImportedTags(rawValue, taskId) {
530
- if (rawValue === void 0 || rawValue === null) return [];
531
- if (!Array.isArray(rawValue)) {
532
- throw new Error(`invalid task tags in snapshot for ${taskId}`);
533
- }
534
- if (!rawValue.every((entry) => typeof entry === "string")) {
535
- throw new Error(`invalid task tags in snapshot for ${taskId}`);
536
- }
537
- return [...rawValue];
538
- }
539
- function assertValidImportedTaskId(rawValue) {
540
- if (typeof rawValue !== "string") {
541
- throw new Error("invalid task id in snapshot");
542
- }
543
- const trimmed = rawValue.trim();
544
- if (!WORK_ID_PATTERN.test(trimmed)) {
545
- throw new Error(`invalid task id in snapshot: ${trimmed}`);
546
- }
547
- return trimmed;
548
- }
549
- function normalizeImportedNullableField(rawValue, taskId, fieldName, fallbackForUndefined) {
550
- if (rawValue === void 0) return fallbackForUndefined;
551
- if (rawValue === null) return null;
552
- if (typeof rawValue === "string") return rawValue;
553
- throw new Error(`invalid task ${fieldName} in snapshot for ${taskId}`);
554
- }
555
- function normalizeImportedTitle(rawValue, taskId) {
556
- if (typeof rawValue !== "string") {
557
- throw new Error(`invalid task title in snapshot for ${taskId}`);
558
- }
559
- const trimmed = rawValue.trim();
560
- if (trimmed.length === 0) {
561
- throw new Error(`invalid task title in snapshot for ${taskId}`);
562
- }
563
- return trimmed;
564
- }
565
- function normalizeImportedDescription(rawValue, taskId) {
566
- if (typeof rawValue !== "string") {
567
- throw new Error(`invalid task description in snapshot for ${taskId}`);
568
- }
569
- return rawValue;
570
- }
571
- function asBoardItem(task) {
572
- return {
573
- id: task.id,
574
- title: task.title,
575
- description: task.description,
576
- status: task.status,
577
- priority: task.priority,
578
- owner: task.owner,
579
- assignee: task.assignee,
580
- projectId: task.projectId,
581
- tags: [...task.tags],
582
- dueAt: task.dueAt
583
- };
584
- }
585
- function formatTaskLine(task) {
586
- const bits = [`id:${task.id}`, `priority:${task.priority}`];
587
- if (task.assignee) bits.push(`assignee:${task.assignee}`);
588
- if (task.owner) bits.push(`owner:${task.owner}`);
589
- if (task.dueAt) bits.push(`due:${task.dueAt}`);
590
- if (task.tags.length > 0) bits.push(`tags:${task.tags.join(",")}`);
591
- const checked = task.status === "done";
592
- return `- [${checked ? "x" : " "}] ${task.title} \`[${bits.join(" ")}]\``;
593
- }
594
- async function exportWorkBoardSnapshot(options) {
595
- const storage = new WorkStorage(options.memoryDir);
596
- await storage.ensureDirectories();
597
- const projectId = options.projectId?.trim() || void 0;
598
- let project = null;
599
- if (projectId) {
600
- project = await storage.getProject(projectId);
601
- if (!project) throw new Error(`project not found: ${projectId}`);
602
- }
603
- const allTasks = await storage.listTasks();
604
- const filtered = stableSortTasks(allTasks.filter((task) => projectMatches(task, projectId)));
605
- return {
606
- version: 1,
607
- generatedAt: (options.now ?? /* @__PURE__ */ new Date()).toISOString(),
608
- projectId: projectId ?? null,
609
- projectName: project?.name ?? null,
610
- items: filtered.map(asBoardItem)
611
- };
612
- }
613
- function renderWorkBoardMarkdown(snapshot) {
614
- const lines = [];
615
- lines.push("# Work Board");
616
- lines.push("");
617
- lines.push(`Generated: ${snapshot.generatedAt}`);
618
- lines.push(`Project: ${snapshot.projectName ?? "all"} (${snapshot.projectId ?? "all"})`);
619
- lines.push("");
620
- for (const status of BOARD_STATUS_ORDER) {
621
- const bucket = snapshot.items.filter((item) => item.status === status);
622
- lines.push(`## ${BOARD_STATUS_LABEL[status]} (${bucket.length})`);
623
- if (bucket.length === 0) {
624
- lines.push("_none_");
625
- } else {
626
- for (const item of bucket) {
627
- lines.push(formatTaskLine(item));
628
- }
629
- }
630
- lines.push("");
631
- }
632
- return `${lines.join("\n").trim()}
633
- `;
634
- }
635
- async function exportWorkBoardMarkdown(options) {
636
- const snapshot = await exportWorkBoardSnapshot(options);
637
- return renderWorkBoardMarkdown(snapshot);
638
- }
639
- async function importWorkBoardSnapshot(options) {
640
- if (options.snapshot.version !== 1) {
641
- throw new Error(`unsupported work board snapshot version: ${options.snapshot.version}`);
642
- }
643
- const storage = new WorkStorage(options.memoryDir);
644
- await storage.ensureDirectories();
645
- const forcedProjectId = options.projectId === void 0 ? void 0 : options.projectId?.trim() || null;
646
- const snapshotProjectId = normalizeImportedProjectId(
647
- options.snapshot.projectId,
648
- "snapshot",
649
- null
650
- );
651
- const preparedRows = [];
652
- const seenItemIds = /* @__PURE__ */ new Set();
653
- for (const item of options.snapshot.items) {
654
- const id = assertValidImportedTaskId(item.id);
655
- if (seenItemIds.has(id)) {
656
- throw new Error(`duplicate task id in snapshot: ${id}`);
657
- }
658
- seenItemIds.add(id);
659
- assertValidImportEnums(item);
660
- const existing = await storage.getTask(id);
661
- const title = normalizeImportedTitle(item.title, id);
662
- const description = normalizeImportedDescription(item.description, id);
663
- const fallbackProjectId = existing ? existing.projectId : snapshotProjectId;
664
- const projectId = forcedProjectId === void 0 ? normalizeImportedProjectId(
665
- item.projectId,
666
- item.id,
667
- fallbackProjectId
668
- ) : forcedProjectId;
669
- const hasTagsField = Object.prototype.hasOwnProperty.call(
670
- item,
671
- "tags"
672
- );
673
- const tags = hasTagsField ? normalizeImportedTags(item.tags, item.id) : existing ? [...existing.tags] : [];
674
- const owner = normalizeImportedNullableField(
675
- item.owner,
676
- id,
677
- "owner",
678
- existing?.owner ?? null
679
- );
680
- const assignee = normalizeImportedNullableField(
681
- item.assignee,
682
- id,
683
- "assignee",
684
- existing?.assignee ?? null
685
- );
686
- const dueAt = normalizeImportedNullableField(
687
- item.dueAt,
688
- id,
689
- "dueAt",
690
- existing?.dueAt ?? null
691
- );
692
- preparedRows.push({ item, existing, id, title, description, projectId, tags, owner, assignee, dueAt });
693
- }
694
- const projectIdsToValidate = new Set(
695
- preparedRows.map((row) => row.projectId).filter((projectId) => typeof projectId === "string")
696
- );
697
- for (const projectId of projectIdsToValidate) {
698
- const project = await storage.getProject(projectId);
699
- if (!project) throw new Error(`project not found: ${projectId}`);
700
- }
701
- let created = 0;
702
- let updated = 0;
703
- for (const row of preparedRows) {
704
- const { item, existing, id, title, description, projectId, tags, owner, assignee, dueAt } = row;
705
- if (existing) {
706
- await storage.updateTask(id, {
707
- title,
708
- description,
709
- status: item.status,
710
- priority: item.priority,
711
- owner,
712
- assignee,
713
- projectId,
714
- tags,
715
- dueAt
716
- }, options.now, { skipStatusTransitionValidation: true });
717
- updated += 1;
718
- continue;
719
- }
720
- await storage.createTask({
721
- id,
722
- title,
723
- description,
724
- status: item.status,
725
- priority: item.priority,
726
- owner,
727
- assignee,
728
- projectId,
729
- tags,
730
- dueAt
731
- }, options.now);
732
- created += 1;
733
- }
734
- return { created, updated };
735
- }
736
-
737
- // src/procedural/procedure-miner.ts
738
- var PROCEDURE_CLUSTER_ATTR_MAX = 500;
739
- function clusterKey(record) {
740
- const goal = record.goal.trim().toLowerCase().replace(/\s+/g, " ").slice(0, 120);
741
- const refs = [...record.entityRefs ?? []].map((r) => r.trim().toLowerCase()).sort();
742
- return `${goal}|${refs.join(",")}`;
743
- }
744
- function successRate(group) {
745
- if (group.length === 0) return 0;
746
- const ok = group.filter((g) => g.outcomeKind === "success" || g.outcomeKind === "partial").length;
747
- return ok / group.length;
748
- }
749
- function pseudoStepsFromCluster(group) {
750
- const sentences = [];
751
- const pushUnique = (raw) => {
752
- const t = raw.trim();
753
- if (t.length < 8) return;
754
- if (!sentences.includes(t)) sentences.push(t);
755
- };
756
- for (const g of group) {
757
- const parts = [g.actionSummary, g.observationSummary, g.outcomeSummary].join(" ").split(/[.!?]\s+|;|\n+/).map((s) => s.trim()).filter((s) => s.length > 12);
758
- for (const p of parts) pushUnique(p);
759
- if (sentences.length >= 5) break;
760
- }
761
- if (sentences.length < 2 && group[0]) {
762
- pushUnique(`${group[0].goal.trim()} \u2014 confirm prerequisites and context.`);
763
- pushUnique("Execute the planned actions, then record the outcome.");
764
- }
765
- return sentences.slice(0, 6).map((intent, i) => ({
766
- order: i + 1,
767
- intent
768
- }));
769
- }
770
- async function hasExistingClusterWrite(storage, cluster) {
771
- const clusterKey2 = cluster.slice(0, PROCEDURE_CLUSTER_ATTR_MAX);
772
- const memories = await storage.readAllMemories();
773
- for (const m of memories) {
774
- if (m.frontmatter.category !== "procedure") continue;
775
- const c = m.frontmatter.structuredAttributes?.procedure_cluster;
776
- if (c === clusterKey2) return true;
777
- }
778
- return false;
779
- }
780
- async function runProcedureMining(options) {
781
- const cfg = options.config.procedural;
782
- if (!cfg?.enabled) {
783
- return { clustersProcessed: 0, proceduresWritten: 0, skippedReason: "procedural_disabled" };
784
- }
785
- if (cfg.minOccurrences <= 0) {
786
- return { clustersProcessed: 0, proceduresWritten: 0, skippedReason: "minOccurrences_zero" };
787
- }
788
- const trajectoryDir = typeof options.config.causalTrajectoryStoreDir === "string" && options.config.causalTrajectoryStoreDir.trim().length > 0 ? options.config.causalTrajectoryStoreDir.trim() : void 0;
789
- const { trajectories } = await readCausalTrajectoryRecords({
790
- memoryDir: options.memoryDir,
791
- causalTrajectoryStoreDir: trajectoryDir
792
- });
793
- const recent = filterTrajectoriesByLookbackDays(trajectories, cfg.lookbackDays);
794
- const clusters = clusterByKey(recent, clusterKey);
795
- let clustersProcessed = 0;
796
- let proceduresWritten = 0;
797
- for (const [key, group] of clusters) {
798
- if (group.length < cfg.minOccurrences) continue;
799
- const rate = successRate(group);
800
- if (rate < cfg.successFloor) continue;
801
- clustersProcessed += 1;
802
- if (await hasExistingClusterWrite(options.storage, key)) {
803
- log.debug(`procedure-miner: skip duplicate cluster key=${key.slice(0, 40)}\u2026`);
804
- continue;
805
- }
806
- const steps = normalizeProcedureSteps(pseudoStepsFromCluster(group));
807
- if (steps.length < 2) continue;
808
- const title = `When you work on goals like: ${group[0].goal.trim().slice(0, 140)}`;
809
- const body = buildProcedurePersistBody(title, steps);
810
- const promote = cfg.autoPromoteEnabled === true && group.length >= cfg.autoPromoteOccurrences && rate >= cfg.successFloor;
811
- await options.storage.writeMemory("procedure", body, {
812
- source: "procedure-miner",
813
- status: promote ? "active" : "pending_review",
814
- tags: ["procedure-miner", "causal-trajectory"],
815
- structuredAttributes: {
816
- procedure_cluster: key.slice(0, PROCEDURE_CLUSTER_ATTR_MAX),
817
- trajectory_ids: group.map((g) => g.trajectoryId).join(",").slice(0, 1900),
818
- trajectory_count: String(group.length),
819
- success_rate: rate.toFixed(4)
820
- }
821
- });
822
- proceduresWritten += 1;
823
- }
824
- return { clustersProcessed, proceduresWritten };
825
- }
826
-
827
- // src/procedural/procedure-stats.ts
828
- function snapshotConfig(config) {
829
- const p = config.procedural;
830
- return {
831
- enabled: p?.enabled === true,
832
- minOccurrences: typeof p?.minOccurrences === "number" ? p.minOccurrences : 0,
833
- successFloor: typeof p?.successFloor === "number" ? p.successFloor : 0,
834
- autoPromoteOccurrences: typeof p?.autoPromoteOccurrences === "number" ? p.autoPromoteOccurrences : 0,
835
- autoPromoteEnabled: p?.autoPromoteEnabled === true,
836
- lookbackDays: typeof p?.lookbackDays === "number" ? p.lookbackDays : 0,
837
- recallMaxProcedures: typeof p?.recallMaxProcedures === "number" ? p.recallMaxProcedures : 0
838
- };
839
- }
840
- function tsMs(value) {
841
- if (typeof value !== "string") return null;
842
- const ms = Date.parse(value);
843
- return Number.isFinite(ms) ? ms : null;
844
- }
845
- async function computeProcedureStats(options) {
846
- const { storage, config } = options;
847
- const nowMs = options.nowMs ?? Date.now();
848
- const sevenDaysMs = 7 * 24 * 60 * 60 * 1e3;
849
- const counts = {
850
- total: 0,
851
- active: 0,
852
- pending_review: 0,
853
- rejected: 0,
854
- quarantined: 0,
855
- superseded: 0,
856
- archived: 0,
857
- other: 0
858
- };
859
- let lastWriteMs = null;
860
- let writesLast7Days = 0;
861
- let minerSourced = 0;
862
- const known = [
863
- "active",
864
- "pending_review",
865
- "rejected",
866
- "quarantined",
867
- "superseded",
868
- "archived"
869
- ];
870
- const seen = /* @__PURE__ */ new Set();
871
- const live = await storage.readAllMemories();
872
- const archived = await storage.readArchivedMemories();
873
- const pool = [...live, ...archived];
874
- for (const m of pool) {
875
- if (m.frontmatter.category !== "procedure") continue;
876
- if (seen.has(m.frontmatter.id)) continue;
877
- seen.add(m.frontmatter.id);
878
- counts.total += 1;
879
- const status = m.frontmatter.status ?? "active";
880
- if (known.includes(status)) {
881
- counts[status] += 1;
882
- } else {
883
- counts.other += 1;
884
- }
885
- const createdMs = tsMs(m.frontmatter.created);
886
- const updatedMs = tsMs(m.frontmatter.updated);
887
- const latestMs = createdMs !== null && updatedMs !== null ? Math.max(createdMs, updatedMs) : updatedMs ?? createdMs;
888
- if (latestMs !== null) {
889
- if (lastWriteMs === null || latestMs > lastWriteMs) {
890
- lastWriteMs = latestMs;
891
- }
892
- if (latestMs >= nowMs - sevenDaysMs && latestMs < nowMs) {
893
- writesLast7Days += 1;
894
- }
895
- }
896
- if (m.frontmatter.source === "procedure-miner") {
897
- minerSourced += 1;
898
- }
899
- }
900
- return {
901
- schemaVersion: 1,
902
- generatedAt: new Date(nowMs).toISOString(),
903
- counts,
904
- recent: {
905
- lastWriteAt: lastWriteMs !== null ? new Date(lastWriteMs).toISOString() : null,
906
- writesLast7Days,
907
- minerSourced
908
- },
909
- config: snapshotConfig(config)
910
- };
911
- }
912
- function formatProcedureStatsText(report) {
913
- const { counts, recent, config } = report;
914
- const lines = [];
915
- lines.push(`Procedural memory stats (schema v${report.schemaVersion})`);
916
- lines.push(` generated: ${report.generatedAt}`);
917
- lines.push("");
918
- lines.push(` config:`);
919
- lines.push(` enabled: ${config.enabled}`);
920
- lines.push(` minOccurrences: ${config.minOccurrences}`);
921
- lines.push(` successFloor: ${config.successFloor}`);
922
- lines.push(` autoPromoteOccurrences: ${config.autoPromoteOccurrences}`);
923
- lines.push(` autoPromoteEnabled: ${config.autoPromoteEnabled}`);
924
- lines.push(` lookbackDays: ${config.lookbackDays}`);
925
- lines.push(` recallMaxProcedures: ${config.recallMaxProcedures}`);
926
- lines.push("");
927
- lines.push(` counts:`);
928
- lines.push(` total: ${counts.total}`);
929
- lines.push(` active: ${counts.active}`);
930
- lines.push(` pending_review: ${counts.pending_review}`);
931
- lines.push(` rejected: ${counts.rejected}`);
932
- lines.push(` quarantined: ${counts.quarantined}`);
933
- lines.push(` superseded: ${counts.superseded}`);
934
- lines.push(` archived: ${counts.archived}`);
935
- if (counts.other > 0) {
936
- lines.push(` other: ${counts.other}`);
937
- }
938
- lines.push("");
939
- lines.push(` recent:`);
940
- lines.push(` lastWriteAt: ${recent.lastWriteAt ?? "(none)"}`);
941
- lines.push(` writesLast7Days: ${recent.writesLast7Days}`);
942
- lines.push(` minerSourced: ${recent.minerSourced}`);
943
- return lines.join("\n") + "\n";
944
- }
945
-
946
- // src/access-service.ts
947
- import * as nodePath from "path";
948
- var EngramAccessInputError = class extends Error {
949
- };
950
- var cachedPackageVersion = null;
951
- async function getPackageVersion() {
952
- if (cachedPackageVersion !== null) return cachedPackageVersion;
953
- try {
954
- const raw = await nodeFs.readFile(new URL("../package.json", import.meta.url), "utf-8");
955
- const parsed = JSON.parse(raw);
956
- cachedPackageVersion = typeof parsed.version === "string" && parsed.version.length > 0 ? parsed.version : "unknown";
957
- } catch {
958
- cachedPackageVersion = "unknown";
959
- }
960
- return cachedPackageVersion;
961
- }
962
- function normalizeTrustZoneInputError(error) {
963
- const message = error instanceof Error ? error.message : null;
964
- if (!message) {
965
- return null;
966
- }
967
- if (/^sourceRecordId must /.test(message) || /^promotionReason must /.test(message) || /^recordedAt must /.test(message) || /^trust zone promotion requires /.test(message) || /^source trust-zone record not found: /.test(message) || /^trust-zone promotion denied: /.test(message) || /^trust zone demo seed requires /.test(message) || /^unsupported trust-zone demo scenario: /.test(message)) {
968
- return new EngramAccessInputError(message);
969
- }
970
- return null;
971
- }
972
- var ENGRAM_ACCESS_WRITE_SCHEMA_VERSION = 1;
973
- async function buildProjectedGovernanceProposedActions(storage, projected) {
974
- const reviewQueue = projected.reviewQueueRows.map((row) => ({
975
- entryId: row.entryId,
976
- memoryId: row.memoryId,
977
- path: row.path,
978
- reasonCode: row.reasonCode,
979
- severity: row.severity,
980
- suggestedAction: row.suggestedAction,
981
- suggestedStatus: row.suggestedStatus,
982
- relatedMemoryIds: row.relatedMemoryIds
983
- }));
984
- const memories = (await Promise.all(projected.reviewQueueRows.map((row) => storage.getMemoryById(row.memoryId)))).filter((memory) => Boolean(memory));
985
- return buildProposedActions(reviewQueue, memories);
986
- }
987
- function hasGroupedGovernanceActions(grouped) {
988
- if (!grouped) return false;
989
- return Object.values(grouped).some((actions) => Array.isArray(actions) && actions.length > 0);
990
- }
991
- function normalizePagination(limit, offset) {
992
- const normalizedLimit = Number.isFinite(limit) ? Math.max(1, Math.min(200, Math.floor(limit ?? 50))) : 50;
993
- const normalizedOffset = Number.isFinite(offset) ? Math.max(0, Math.floor(offset ?? 0)) : 0;
994
- return { limit: normalizedLimit, offset: normalizedOffset };
995
- }
996
- function normalizeBrowseSort(sort) {
997
- switch (sort) {
998
- case "updated_asc":
999
- case "created_desc":
1000
- case "created_asc":
1001
- return sort;
1002
- case "updated_desc":
1003
- default:
1004
- return "updated_desc";
1005
- }
1006
- }
1007
- function bucketMemoryAge(referenceIso, nowMs) {
1008
- const referenceMs = referenceIso ? Date.parse(referenceIso) : Number.NaN;
1009
- if (!Number.isFinite(referenceMs)) return "unknown";
1010
- const ageDays = Math.floor((nowMs - referenceMs) / 864e5);
1011
- if (ageDays <= 7) return "0_7_days";
1012
- if (ageDays <= 30) return "8_30_days";
1013
- if (ageDays <= 90) return "31_90_days";
1014
- return "91_plus_days";
1015
- }
1016
- function incrementCount(counts, key) {
1017
- counts[key] = (counts[key] ?? 0) + 1;
1018
- }
1019
- function summarizeTrustZoneRecord(record, filePath, allRecords, poisoningDefenseEnabled, trustZonesEnabled, promotionEnabled) {
1020
- const trustScore = poisoningDefenseEnabled ? scoreTrustZoneProvenance(record) : void 0;
1021
- const readiness = summarizeTrustZonePromotionReadiness({
1022
- record,
1023
- allRecords,
1024
- poisoningDefenseEnabled
1025
- });
1026
- const promotionReasons = [...readiness.reasons];
1027
- const promotionAllowed = readiness.allowed && trustZonesEnabled === true && promotionEnabled === true;
1028
- if (trustZonesEnabled !== true) {
1029
- promotionReasons.push("trust zone promotion requires trustZonesEnabled=true");
1030
- }
1031
- if (promotionEnabled !== true) {
1032
- promotionReasons.push("trust zone promotion requires quarantinePromotionEnabled=true");
1033
- }
1034
- return {
1035
- recordId: record.recordId,
1036
- filePath,
1037
- zone: record.zone,
1038
- recordedAt: record.recordedAt,
1039
- kind: record.kind,
1040
- summary: record.summary,
1041
- sourceClass: record.provenance.sourceClass,
1042
- sessionKey: record.provenance.sessionKey,
1043
- sourceId: record.provenance.sourceId,
1044
- evidenceHashPresent: typeof record.provenance.evidenceHash === "string",
1045
- anchored: Boolean(record.provenance.sourceId && record.provenance.evidenceHash),
1046
- entityRefs: [...record.entityRefs ?? []],
1047
- tags: [...record.tags ?? []],
1048
- metadata: record.metadata,
1049
- trustScore,
1050
- nextPromotionTarget: readiness.nextTargetZone,
1051
- nextPromotionAllowed: promotionAllowed,
1052
- nextPromotionReasons: promotionReasons,
1053
- corroborationCount: readiness.requiresCorroboration ? readiness.corroborationCount : void 0,
1054
- corroborationSourceClasses: readiness.requiresCorroboration ? readiness.corroborationSourceClasses : void 0
1055
- };
1056
- }
1057
- function compareBrowseMemory(sort, left, right) {
1058
- const leftUpdated = left.frontmatter.updated ?? left.frontmatter.created ?? "";
1059
- const rightUpdated = right.frontmatter.updated ?? right.frontmatter.created ?? "";
1060
- const leftCreated = left.frontmatter.created ?? "";
1061
- const rightCreated = right.frontmatter.created ?? "";
1062
- switch (sort) {
1063
- case "updated_asc":
1064
- return leftUpdated.localeCompare(rightUpdated) || leftCreated.localeCompare(rightCreated) || left.frontmatter.id.localeCompare(right.frontmatter.id);
1065
- case "created_desc":
1066
- return rightCreated.localeCompare(leftCreated) || rightUpdated.localeCompare(leftUpdated) || left.frontmatter.id.localeCompare(right.frontmatter.id);
1067
- case "created_asc":
1068
- return leftCreated.localeCompare(rightCreated) || leftUpdated.localeCompare(rightUpdated) || left.frontmatter.id.localeCompare(right.frontmatter.id);
1069
- case "updated_desc":
1070
- default:
1071
- return rightUpdated.localeCompare(leftUpdated) || rightCreated.localeCompare(leftCreated) || left.frontmatter.id.localeCompare(right.frontmatter.id);
1072
- }
1073
- }
1074
- function shapeMemorySummary(memory, baseDir, disclosure, rawExcerpts) {
1075
- const includeFullContent = disclosure === "section" || disclosure === "raw";
1076
- return {
1077
- id: memory.frontmatter.id,
1078
- path: memory.path,
1079
- category: memory.frontmatter.category,
1080
- status: inferMemoryStatus(memory.frontmatter, toMemoryPathRel(baseDir, memory.path)),
1081
- created: memory.frontmatter.created,
1082
- updated: memory.frontmatter.updated,
1083
- tags: normalizeProjectionTags(memory.frontmatter.tags),
1084
- entityRef: memory.frontmatter.entityRef,
1085
- preview: normalizeProjectionPreview(memory.content),
1086
- ...disclosure !== void 0 ? { disclosure } : {},
1087
- ...includeFullContent ? { content: memory.content } : {},
1088
- ...disclosure === "raw" && rawExcerpts !== void 0 ? { rawExcerpts } : {}
1089
- };
1090
- }
1091
- var EngramAccessService = class {
1092
- constructor(orchestrator) {
1093
- this.orchestrator = orchestrator;
1094
- this.idempotency = new AccessIdempotencyStore(orchestrator.config.memoryDir);
1095
- this.budget = new CrossNamespaceBudget({
1096
- enabled: orchestrator.config.recallCrossNamespaceBudgetEnabled,
1097
- windowMs: orchestrator.config.recallCrossNamespaceBudgetWindowMs,
1098
- softLimit: orchestrator.config.recallCrossNamespaceBudgetSoftLimit,
1099
- hardLimit: orchestrator.config.recallCrossNamespaceBudgetHardLimit
1100
- });
1101
- const auditEnabled = orchestrator.config.recallAuditAnomalyDetectionEnabled === true;
1102
- const auditLogEnabled = false;
1103
- if (auditEnabled || auditLogEnabled) {
1104
- const auditConfig = {
1105
- audit: {
1106
- enabled: auditLogEnabled,
1107
- rootDir: orchestrator.config.memoryDir
1108
- },
1109
- detection: {
1110
- enabled: auditEnabled,
1111
- windowMs: orchestrator.config.recallAuditAnomalyWindowMs,
1112
- repeatQueryLimit: orchestrator.config.recallAuditAnomalyRepeatQueryLimit,
1113
- namespaceWalkLimit: orchestrator.config.recallAuditAnomalyNamespaceWalkLimit,
1114
- highCardinalityReturnLimit: orchestrator.config.recallAuditAnomalyHighCardinalityLimit,
1115
- rapidFireLimit: orchestrator.config.recallAuditAnomalyRapidFireLimit
1116
- }
1117
- };
1118
- this.auditAdapter = new AccessAuditAdapter(auditConfig);
1119
- } else {
1120
- this.auditAdapter = null;
1121
- }
1122
- }
1123
- orchestrator;
1124
- idempotency;
1125
- idempotencyLocks = /* @__PURE__ */ new Map();
1126
- budget;
1127
- auditAdapter;
1128
- get briefingEnabled() {
1129
- return this.orchestrator.config.briefing?.enabled === true;
1130
- }
1131
- resolveNamespace(namespace) {
1132
- const requested = namespace?.trim();
1133
- if (!requested) return this.orchestrator.config.defaultNamespace;
1134
- if (!this.orchestrator.config.namespacesEnabled && requested !== this.orchestrator.config.defaultNamespace) {
1135
- throw new EngramAccessInputError(`unsupported namespace: ${requested}`);
1136
- }
1137
- return requested;
1138
- }
1139
- normalizeRecallMode(mode) {
1140
- if (!mode || mode === "auto") return void 0;
1141
- if (mode === "no_recall" || mode === "minimal" || mode === "full" || mode === "graph_mode") {
1142
- return mode;
1143
- }
1144
- throw new EngramAccessInputError(`unsupported recall mode: ${mode}`);
1145
- }
1146
- resolveRecallNamespace(namespace, sessionKey) {
1147
- const requested = namespace?.trim();
1148
- if (!requested) return void 0;
1149
- const resolved = this.resolveNamespace(requested);
1150
- const principal = resolvePrincipal(sessionKey, this.orchestrator.config);
1151
- if (!canReadNamespace(principal, resolved, this.orchestrator.config)) {
1152
- throw new EngramAccessInputError(`namespace override is not readable: ${resolved}`);
1153
- }
1154
- return resolved;
1155
- }
1156
- resolveWritePrincipal(sessionKey, authenticatedPrincipal) {
1157
- const trusted = authenticatedPrincipal?.trim();
1158
- if (trusted) return trusted;
1159
- return resolvePrincipal(sessionKey, this.orchestrator.config);
1160
- }
1161
- resolveWritableNamespace(namespace, sessionKey, authenticatedPrincipal) {
1162
- const resolved = this.resolveNamespace(namespace);
1163
- const principal = this.resolveWritePrincipal(sessionKey, authenticatedPrincipal);
1164
- if (!canWriteNamespace(principal, resolved, this.orchestrator.config)) {
1165
- throw new EngramAccessInputError(`namespace is not writable: ${resolved}`);
1166
- }
1167
- return resolved;
1168
- }
1169
- async objectiveStateStoreLocationForNamespace(namespace) {
1170
- if (!this.orchestrator.config.namespacesEnabled) {
1171
- return {
1172
- memoryDir: this.orchestrator.config.memoryDir,
1173
- objectiveStateStoreDir: this.orchestrator.config.objectiveStateStoreDir
1174
- };
1175
- }
1176
- const storage = await this.orchestrator.getStorage(namespace);
1177
- return {
1178
- memoryDir: storage.dir,
1179
- objectiveStateStoreDir: objectiveStateStoreOverrideForNamespace({
1180
- memoryDir: this.orchestrator.config.memoryDir,
1181
- configuredStoreDir: this.orchestrator.config.objectiveStateStoreDir,
1182
- namespacesEnabled: this.orchestrator.config.namespacesEnabled,
1183
- namespace
1184
- })
1185
- };
1186
- }
1187
- resolveReadableNamespace(namespace, principal) {
1188
- const resolved = this.resolveNamespace(namespace);
1189
- const namespacesEnabled = this.orchestrator.config.namespacesEnabled;
1190
- if (!namespacesEnabled) {
1191
- return resolved;
1192
- }
1193
- if (!principal) {
1194
- throw new EngramAccessInputError(
1195
- "authentication required: namespaces are enabled and no principal was supplied"
1196
- );
1197
- }
1198
- if (!canReadNamespace(principal, resolved, this.orchestrator.config)) {
1199
- throw new EngramAccessInputError(`namespace is not readable: ${resolved}`);
1200
- }
1201
- return resolved;
1202
- }
1203
- async buildRecallDebug(snapshot, namespace, includeDebug, sessionKey) {
1204
- if (!includeDebug) return void 0;
1205
- if (!sessionKey?.trim()) return void 0;
1206
- const [intent, graph] = await Promise.all([
1207
- this.orchestrator.getLastIntentSnapshot(namespace),
1208
- this.orchestrator.getLastGraphRecallSnapshot(namespace)
1209
- ]);
1210
- return snapshot || intent || graph ? {
1211
- snapshot: snapshot ?? void 0,
1212
- intent,
1213
- graph
1214
- } : void 0;
1215
- }
1216
- async serializeRecallResults(snapshot, disclosure, rawContext = null) {
1217
- if (!snapshot) return [];
1218
- const namespace = snapshot.namespace ? this.resolveNamespace(snapshot.namespace) : this.orchestrator.config.defaultNamespace;
1219
- const storage = await this.orchestrator.getStorage(namespace);
1220
- const storageDir = storage.dir;
1221
- const results = [];
1222
- const seen = /* @__PURE__ */ new Set();
1223
- const rawExcerptsResult = await this.fetchRawExcerpts(
1224
- disclosure,
1225
- rawContext ? { ...rawContext, namespace } : null
1226
- );
1227
- const rawExcerpts = rawExcerptsResult ?? void 0;
1228
- for (const memoryPath of snapshot.resultPaths ?? []) {
1229
- if (!memoryPath || seen.has(memoryPath)) continue;
1230
- const memory = await storage.readMemoryByPath(memoryPath);
1231
- if (!memory) continue;
1232
- seen.add(memoryPath);
1233
- results.push(
1234
- this.serializeMemorySummary(
1235
- memory,
1236
- storageDir,
1237
- disclosure,
1238
- // Attach the (possibly empty) raw excerpts to the first raw
1239
- // result; subsequent results do not duplicate the array.
1240
- results.length === 0 ? rawExcerpts : void 0
1241
- )
1242
- );
1243
- }
1244
- if (results.length > 0) return results;
1245
- for (const memoryId of snapshot.memoryIds) {
1246
- const memory = await storage.getMemoryById(memoryId);
1247
- if (!memory || seen.has(memory.path)) continue;
1248
- seen.add(memory.path);
1249
- results.push(
1250
- this.serializeMemorySummary(
1251
- memory,
1252
- storageDir,
1253
- disclosure,
1254
- results.length === 0 ? rawExcerpts : void 0
1255
- )
1256
- );
1257
- }
1258
- return results;
1259
- }
1260
- /**
1261
- * Fetch raw transcript excerpts from the LCM archive for `disclosure ===
1262
- * "raw"` recalls (issue #677 PR 2/4). Returns `null` for non-raw recall
1263
- * depths, an empty array when LCM is disabled / not initialized / has no
1264
- * matches, and an array of LCM-side excerpts otherwise. Errors are
1265
- * swallowed and treated as "no excerpts" so a failing LCM never breaks
1266
- * the recall response.
1267
- *
1268
- * Namespace handling: LCM archival prefixes non-default-namespace
1269
- * sessions with `${namespace}:${sessionKey}` (see `observe()` around
1270
- * line 2498), so the lookup must mirror that prefix or raw recalls in
1271
- * non-default namespaces miss their own excerpts.
1272
- */
1273
- async fetchRawExcerpts(disclosure, context) {
1274
- if (disclosure !== "raw") return null;
1275
- if (!context || !context.query) return [];
1276
- if (!context.sessionKey) return [];
1277
- const lcm = this.orchestrator.lcmEngine;
1278
- if (!lcm || !lcm.enabled) return [];
1279
- try {
1280
- const lcmSessionKey = context.namespace && context.namespace !== this.orchestrator.config.defaultNamespace ? `${context.namespace}:${context.sessionKey}` : context.sessionKey;
1281
- const rows = await lcm.searchContextFull(
1282
- context.query,
1283
- // Cap the excerpt fanout so recall responses stay bounded. Five
1284
- // matches is enough to anchor the model in the raw transcript
1285
- // without ballooning token spend; raw is meant as the escape
1286
- // hatch, not the default.
1287
- 5,
1288
- lcmSessionKey
1289
- );
1290
- return rows.map((r) => ({
1291
- turnIndex: r.turn_index,
1292
- role: r.role,
1293
- content: r.content,
1294
- sessionId: r.session_id
1295
- }));
1296
- } catch {
1297
- return [];
1298
- }
1299
- }
1300
- async handleIdempotentWrite(options) {
1301
- if (options.skip === true) {
1302
- return options.execute();
1303
- }
1304
- const key = options.idempotencyKey?.trim();
1305
- if (!key) {
1306
- return options.execute();
1307
- }
1308
- return this.withIdempotencyLock(key, async () => {
1309
- return this.idempotency.withKeyLock(key, async () => {
1310
- const requestHash = hashAccessIdempotencyPayload({
1311
- operation: options.operation,
1312
- request: options.requestFingerprint
1313
- });
1314
- const existing = await this.idempotency.get(key, requestHash);
1315
- if (existing.conflict) {
1316
- throw new EngramAccessInputError(`idempotencyKey reuse conflict: ${key}`);
1317
- }
1318
- if (existing.response) {
1319
- return {
1320
- ...existing.response,
1321
- idempotencyReplay: true
1322
- };
1323
- }
1324
- const response = await options.execute();
1325
- await this.idempotency.put(key, requestHash, response);
1326
- return response;
1327
- });
1328
- });
1329
- }
1330
- async peekIdempotentWrite(options) {
1331
- if (options.skip === true) {
1332
- return "miss";
1333
- }
1334
- const key = options.idempotencyKey?.trim();
1335
- if (!key) {
1336
- return "miss";
1337
- }
1338
- return this.withIdempotencyLock(key, async () => {
1339
- return this.idempotency.withKeyLock(key, async () => {
1340
- const requestHash = hashAccessIdempotencyPayload({
1341
- operation: options.operation,
1342
- request: options.requestFingerprint
1343
- });
1344
- const existing = await this.idempotency.get(key, requestHash);
1345
- if (existing.conflict) {
1346
- return "conflict";
1347
- }
1348
- return existing.response ? "replay" : "miss";
1349
- });
1350
- });
1351
- }
1352
- async withIdempotencyLock(key, fn) {
1353
- const previous = this.idempotencyLocks.get(key) ?? Promise.resolve();
1354
- let release;
1355
- const current = new Promise((resolve2) => {
1356
- release = resolve2;
1357
- });
1358
- const queued = previous.then(() => current, () => current);
1359
- this.idempotencyLocks.set(key, queued);
1360
- await previous.catch(() => {
1361
- });
1362
- try {
1363
- return await fn();
1364
- } finally {
1365
- release();
1366
- if (this.idempotencyLocks.get(key) === queued) {
1367
- this.idempotencyLocks.delete(key);
1368
- }
1369
- }
1370
- }
1371
- async health(namespace) {
1372
- const resolvedNamespace = this.resolveNamespace(namespace);
1373
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
1374
- let projectionAvailable = false;
1375
- try {
1376
- await stat(getMemoryProjectionPath(storage.dir));
1377
- projectionAvailable = true;
1378
- } catch {
1379
- projectionAvailable = false;
1380
- }
1381
- return {
1382
- ok: true,
1383
- memoryDir: storage.dir,
1384
- namespacesEnabled: this.orchestrator.config.namespacesEnabled === true,
1385
- defaultNamespace: this.orchestrator.config.defaultNamespace,
1386
- searchBackend: this.orchestrator.config.searchBackend ?? "qmd",
1387
- qmdEnabled: this.orchestrator.config.qmdEnabled === true,
1388
- nativeKnowledgeEnabled: this.orchestrator.config.nativeKnowledge?.enabled === true,
1389
- projectionAvailable
1390
- };
1391
- }
1392
- async daySummary(request) {
1393
- if (!this.orchestrator.config.daySummaryEnabled) {
1394
- throw new EngramAccessInputError("day summary is disabled");
1395
- }
1396
- const memories = (request.memories ?? "").trim();
1397
- const namespace = this.resolveRecallNamespace(request.namespace, request.sessionKey);
1398
- if (memories.length === 0) {
1399
- return this.orchestrator.generateDaySummaryAuto(namespace);
1400
- }
1401
- return this.orchestrator.generateDaySummary(memories);
1402
- }
1403
- /**
1404
- * Build a daily context briefing. Gracefully degrades when the OpenAI key
1405
- * or Responses API is unavailable — never throws for LLM-related problems.
1406
- */
1407
- async briefing(request) {
1408
- const config = this.orchestrator.config;
1409
- if (!config.briefing.enabled) {
1410
- throw new EngramAccessInputError("briefing is disabled");
1411
- }
1412
- const namespace = this.resolveReadableNamespace(request.namespace, request.principal);
1413
- const storage = await this.orchestrator.getStorage(namespace);
1414
- const token = typeof request.since === "string" && request.since.trim().length > 0 ? request.since.trim() : config.briefing.defaultWindow;
1415
- const window = parseBriefingWindow(token);
1416
- if (!window) {
1417
- throw new EngramAccessInputError(`invalid briefing window: ${token}`);
1418
- }
1419
- const rawFocus = typeof request.focus === "string" ? request.focus.trim() : "";
1420
- let focus = null;
1421
- if (rawFocus.length > 0) {
1422
- focus = parseBriefingFocus(rawFocus);
1423
- if (!focus) {
1424
- throw new EngramAccessInputError(
1425
- `invalid briefing focus filter: ${request.focus}`
1426
- );
1427
- }
1428
- }
1429
- const SUPPORTED_FORMATS = ["markdown", "json"];
1430
- if (typeof request.format === "string" && !SUPPORTED_FORMATS.includes(request.format)) {
1431
- throw new EngramAccessInputError(
1432
- `unsupported briefing format: "${request.format}". Accepted: ${SUPPORTED_FORMATS.join(", ")}.`
1433
- );
1434
- }
1435
- const format = request.format === "json" ? "json" : request.format === "markdown" ? "markdown" : config.briefing.defaultFormat;
1436
- const maxFollowups = typeof request.maxFollowups === "number" && Number.isFinite(request.maxFollowups) ? Math.max(0, Math.min(10, Math.floor(request.maxFollowups))) : config.briefing.maxFollowups;
1437
- const calendarSource = config.briefing.calendarSource ? new FileCalendarSource(config.briefing.calendarSource) : void 0;
1438
- const result = await buildBriefing({
1439
- storage,
1440
- namespace,
1441
- window,
1442
- focus,
1443
- calendarSource,
1444
- maxFollowups,
1445
- allowLlm: config.briefing.llmFollowups,
1446
- openaiApiKey: config.openaiApiKey,
1447
- openaiBaseUrl: config.openaiBaseUrl,
1448
- model: config.model
1449
- });
1450
- return {
1451
- format,
1452
- window: result.window,
1453
- namespace,
1454
- markdown: result.markdown,
1455
- json: result.json,
1456
- followupsUnavailableReason: result.followupsUnavailableReason
1457
- };
1458
- }
1459
- /**
1460
- * Attach a coding context to a session (issue #569). Used by the Claude
1461
- * Code / Codex / generic-MCP connectors at session start so that recall +
1462
- * write paths can route to a project- / branch-scoped namespace.
1463
- *
1464
- * Validates the input shape and rejects malformed payloads rather than
1465
- * silently accepting them (CLAUDE.md #51). Pass `codingContext: null` to
1466
- * clear.
1467
- */
1468
- setCodingContext(request) {
1469
- const sessionKey = typeof request.sessionKey === "string" ? request.sessionKey.trim() : "";
1470
- if (!sessionKey) {
1471
- throw new EngramAccessInputError("sessionKey is required for setCodingContext");
1472
- }
1473
- if (request.codingContext === null) {
1474
- this.orchestrator.setCodingContextForSession(sessionKey, null);
1475
- return;
1476
- }
1477
- const ctx = request.codingContext;
1478
- if (!ctx || typeof ctx !== "object") {
1479
- throw new EngramAccessInputError("codingContext must be an object or null");
1480
- }
1481
- if (typeof ctx.projectId !== "string" || ctx.projectId.trim().length === 0) {
1482
- throw new EngramAccessInputError("codingContext.projectId must be a non-empty string");
1483
- }
1484
- if (typeof ctx.rootPath !== "string" || ctx.rootPath.trim().length === 0) {
1485
- throw new EngramAccessInputError("codingContext.rootPath must be a non-empty string");
1486
- }
1487
- if (ctx.branch !== null && typeof ctx.branch !== "string") {
1488
- throw new EngramAccessInputError("codingContext.branch must be a string or null");
1489
- }
1490
- if (ctx.defaultBranch !== null && typeof ctx.defaultBranch !== "string") {
1491
- throw new EngramAccessInputError("codingContext.defaultBranch must be a string or null");
1492
- }
1493
- this.orchestrator.setCodingContextForSession(sessionKey, {
1494
- projectId: ctx.projectId,
1495
- branch: ctx.branch,
1496
- rootPath: ctx.rootPath,
1497
- defaultBranch: ctx.defaultBranch
1498
- });
1499
- }
1500
- /**
1501
- * Auto-resolve and attach a coding context for a session when one is not
1502
- * already present. Resolves from `projectTag` (highest priority after
1503
- * explicit `codingContext`), then from `cwd` via git detection.
1504
- *
1505
- * This is a no-op when:
1506
- * - `sessionKey` is missing
1507
- * - the session already has a coding context attached
1508
- * - codingMode.projectScope is disabled (CLAUDE.md #30)
1509
- * - neither `cwd` nor `projectTag` is provided
1510
- *
1511
- * Never throws — git resolution failures are silently ignored because not
1512
- * being in a repo is a normal runtime state.
1513
- */
1514
- async maybeAttachCodingContext(sessionKey, options) {
1515
- if (!sessionKey) return;
1516
- if (!this.orchestrator.config.codingMode?.projectScope) return;
1517
- if (this.orchestrator.getCodingContextForSession(sessionKey)) return;
1518
- if (typeof options.projectTag === "string" && options.projectTag.trim().length > 0) {
1519
- const tag = options.projectTag.trim();
1520
- this.orchestrator.setCodingContextForSession(sessionKey, {
1521
- projectId: `tag:${tag}`,
1522
- branch: null,
1523
- rootPath: `tag:${tag}`,
1524
- defaultBranch: null
1525
- });
1526
- return;
1527
- }
1528
- if (typeof options.cwd === "string" && options.cwd.trim().length > 0) {
1529
- try {
1530
- const gitCtx = await resolveGitContext(options.cwd);
1531
- if (gitCtx) {
1532
- this.setCodingContext({
1533
- sessionKey,
1534
- codingContext: {
1535
- projectId: gitCtx.projectId,
1536
- branch: gitCtx.branch,
1537
- rootPath: gitCtx.rootPath,
1538
- defaultBranch: gitCtx.defaultBranch
1539
- }
1540
- });
1541
- }
1542
- } catch {
1543
- }
1544
- }
1545
- }
1546
- async recall(request) {
1547
- const query = request.query.trim();
1548
- if (query.length === 0) {
1549
- throw new EngramAccessInputError("query is required");
1550
- }
1551
- const callerProvidedDisclosure = request.disclosure !== void 0 && request.disclosure !== null;
1552
- const requestedDisclosure = (() => {
1553
- if (!callerProvidedDisclosure) {
1554
- return DEFAULT_RECALL_DISCLOSURE;
1555
- }
1556
- if (!isRecallDisclosure(request.disclosure)) {
1557
- throw new EngramAccessInputError(
1558
- `disclosure must be one of: chunk, section, raw (got: ${String(request.disclosure)})`
1559
- );
1560
- }
1561
- return request.disclosure;
1562
- })();
1563
- if (request.codingContext !== void 0 && request.sessionKey) {
1564
- this.setCodingContext({
1565
- sessionKey: request.sessionKey,
1566
- codingContext: request.codingContext
1567
- });
1568
- }
1569
- if (request.codingContext === void 0 && request.sessionKey) {
1570
- await this.maybeAttachCodingContext(request.sessionKey, {
1571
- cwd: request.cwd,
1572
- projectTag: request.projectTag
1573
- });
1574
- }
1575
- const namespaceOverride = this.resolveRecallNamespace(request.namespace, request.sessionKey);
1576
- const namespace = namespaceOverride ?? this.orchestrator.config.defaultNamespace;
1577
- const mode = this.normalizeRecallMode(request.mode);
1578
- const principal = resolvePrincipal(request.sessionKey, this.orchestrator.config);
1579
- const principalNamespace = defaultNamespaceForPrincipal(principal, this.orchestrator.config);
1580
- const modeSkipsBudget = mode === "no_recall";
1581
- const effectiveNamespaces = namespaceOverride ? [namespaceOverride] : recallNamespacesForPrincipal(principal, this.orchestrator.config);
1582
- let budgetDecision;
1583
- if (modeSkipsBudget) {
1584
- budgetDecision = {
1585
- allowed: true,
1586
- reason: "allowed-same-namespace",
1587
- count: 0,
1588
- limit: {
1589
- softLimit: this.orchestrator.config.recallCrossNamespaceBudgetSoftLimit ?? 10,
1590
- hardLimit: this.orchestrator.config.recallCrossNamespaceBudgetHardLimit ?? 30,
1591
- windowMs: this.orchestrator.config.recallCrossNamespaceBudgetWindowMs ?? 6e4
1592
- }
1593
- };
1594
- } else {
1595
- let anyCrossNamespace = false;
1596
- let denied = null;
1597
- for (const ns of effectiveNamespaces) {
1598
- const peek = this.budget.peek({
1599
- principal,
1600
- principalNamespace,
1601
- queryNamespace: ns
1602
- });
1603
- if (peek.reason !== "allowed-same-namespace") {
1604
- anyCrossNamespace = true;
1605
- }
1606
- if (!peek.allowed) {
1607
- denied = peek;
1608
- break;
1609
- }
1610
- }
1611
- if (denied) {
1612
- budgetDecision = denied;
1613
- } else if (anyCrossNamespace) {
1614
- budgetDecision = this.budget.record(principal);
1615
- } else {
1616
- budgetDecision = {
1617
- allowed: true,
1618
- reason: "allowed-same-namespace",
1619
- count: 0,
1620
- limit: {
1621
- softLimit: this.orchestrator.config.recallCrossNamespaceBudgetSoftLimit ?? 10,
1622
- hardLimit: this.orchestrator.config.recallCrossNamespaceBudgetHardLimit ?? 30,
1623
- windowMs: this.orchestrator.config.recallCrossNamespaceBudgetWindowMs ?? 6e4
1624
- }
1625
- };
1626
- }
1627
- if (!budgetDecision.allowed) {
1628
- throw new EngramAccessInputError(
1629
- `recall denied: cross-namespace budget exceeded (${budgetDecision.count}/${budgetDecision.limit.hardLimit} in ${budgetDecision.limit.windowMs}ms window)`
1630
- );
1631
- }
1632
- this.budget.gc();
1633
- }
1634
- const topK = Number.isFinite(request.topK) ? Math.max(0, Math.floor(request.topK ?? 0)) : void 0;
1635
- let asOf;
1636
- if (request.asOf !== void 0 && request.asOf !== null) {
1637
- if (typeof request.asOf !== "string" || request.asOf.trim().length === 0) {
1638
- throw new EngramAccessInputError(
1639
- "asOf must be a non-empty ISO 8601 timestamp string"
1640
- );
1641
- }
1642
- const parsed = Date.parse(request.asOf);
1643
- if (!Number.isFinite(parsed)) {
1644
- throw new EngramAccessInputError(
1645
- `asOf must be a parseable ISO 8601 timestamp (got: "${request.asOf}")`
1646
- );
1647
- }
1648
- asOf = request.asOf;
1649
- }
1650
- const recallOptions = {
1651
- namespace: namespaceOverride,
1652
- topK,
1653
- mode,
1654
- ...asOf !== void 0 ? { asOf } : {},
1655
- ...request.includeLowConfidence === true ? { includeLowConfidence: true } : {}
1656
- };
1657
- const startedAt = Date.now();
1658
- const context = await this.orchestrator.recall(query, request.sessionKey, recallOptions);
1659
- const snapshot = request.sessionKey ? this.orchestrator.lastRecall.get(request.sessionKey) : null;
1660
- const effectiveNamespace = snapshot?.namespace ? this.resolveNamespace(snapshot.namespace) : namespace;
1661
- const resultsReturned = snapshot?.memoryIds?.length ?? 0;
1662
- const appliedTopK = snapshot?.budgetsApplied?.appliedTopK;
1663
- const configMaxResults = typeof this.orchestrator.config.qmdMaxResults === "number" && Number.isFinite(this.orchestrator.config.qmdMaxResults) && this.orchestrator.config.qmdMaxResults > 0 ? this.orchestrator.config.qmdMaxResults : 0;
1664
- const topKDenominator = typeof appliedTopK === "number" && Number.isFinite(appliedTopK) && appliedTopK > 0 ? Math.max(appliedTopK, resultsReturned) : typeof topK === "number" && topK > 0 ? Math.max(topK, resultsReturned) : Math.max(configMaxResults, resultsReturned, 1);
1665
- const topKConfidence = snapshot && topKDenominator > 0 ? Math.min(1, resultsReturned / topKDenominator) : void 0;
1666
- const escalationDecision = decideDisclosureEscalation({
1667
- mode: this.orchestrator.config.recallDisclosureEscalation,
1668
- threshold: this.orchestrator.config.recallDisclosureEscalationThreshold,
1669
- originalDisclosure: requestedDisclosure,
1670
- callerProvidedDisclosure,
1671
- topKConfidence
1672
- });
1673
- const disclosure = escalationDecision.effective;
1674
- let results = await this.serializeRecallResults(snapshot, disclosure, {
1675
- query,
1676
- sessionKey: request.sessionKey
1677
- });
1678
- const filterTags = normalizeTags(request.tags);
1679
- let tagMatchMode;
1680
- try {
1681
- tagMatchMode = parseTagMatch(request.tagMatch);
1682
- } catch (err) {
1683
- throw new EngramAccessInputError(
1684
- err instanceof Error ? err.message : String(err)
1685
- );
1686
- }
1687
- let effectiveContext = context;
1688
- if (filterTags && filterTags.length > 0) {
1689
- const beforeIds = results.map((r) => r.id);
1690
- const { results: admitted } = applyTagFilter(results, {
1691
- tags: filterTags,
1692
- tagMatch: tagMatchMode
1693
- });
1694
- results = admitted;
1695
- const admittedIds = new Set(results.map((r) => r.id));
1696
- const droppedAny = beforeIds.some((id) => !admittedIds.has(id));
1697
- if (droppedAny) {
1698
- effectiveContext = results.map((r) => {
1699
- const content = typeof r.content === "string" ? r.content ?? "" : "";
1700
- const preview = typeof r.preview === "string" ? r.preview ?? "" : "";
1701
- return content || preview;
1702
- }).filter((s) => s.length > 0).join("\n\n");
1703
- }
1704
- }
1705
- const filteredMemoryIds = filterTags && filterTags.length > 0 ? results.map((r) => r.id) : snapshot?.memoryIds ?? [];
1706
- const debug = await this.buildRecallDebug(
1707
- snapshot,
1708
- effectiveNamespace,
1709
- request.includeDebug === true,
1710
- request.sessionKey
1711
- );
1712
- let auditAnomalies;
1713
- if (this.auditAdapter) {
1714
- try {
1715
- const resolvedAgentId = resolvePrincipal(
1716
- request.sessionKey,
1717
- this.orchestrator.config
1718
- );
1719
- const auditEntry = {
1720
- ts: (/* @__PURE__ */ new Date()).toISOString(),
1721
- sessionKey: request.sessionKey ?? "",
1722
- agentId: resolvedAgentId,
1723
- trigger: "access-surface",
1724
- queryText: query,
1725
- candidateMemoryIds: snapshot?.memoryIds ?? [],
1726
- // Audit must reflect what was actually injected, not what
1727
- // recall produced before the tag filter. Using `context`
1728
- // (pre-filter) overstates injectedChars and can leak content
1729
- // from excluded memories into the audit summary (cursor
1730
- // Medium on PR #712).
1731
- summary: effectiveContext.slice(0, 200) || null,
1732
- injectedChars: effectiveContext.length,
1733
- toggleState: "enabled",
1734
- latencyMs: Date.now() - startedAt,
1735
- plannerMode: snapshot?.plannerMode ?? mode,
1736
- requestedMode: mode,
1737
- fallbackUsed: snapshot?.fallbackUsed ?? false
1738
- };
1739
- const auditResult = await this.auditAdapter.record(
1740
- resolvedAgentId || "__anonymous__",
1741
- auditEntry
1742
- );
1743
- auditAnomalies = auditResult.anomalies;
1744
- } catch {
1745
- }
1746
- }
1747
- return {
1748
- query,
1749
- sessionKey: request.sessionKey,
1750
- namespace: effectiveNamespace,
1751
- context: effectiveContext,
1752
- count: filterTags && filterTags.length > 0 ? results.length : snapshot?.memoryIds.length ?? results.length,
1753
- memoryIds: filteredMemoryIds,
1754
- results,
1755
- recordedAt: snapshot?.recordedAt,
1756
- traceId: snapshot?.traceId,
1757
- plannerMode: snapshot?.plannerMode ?? mode,
1758
- fallbackUsed: snapshot?.fallbackUsed ?? false,
1759
- sourcesUsed: snapshot?.sourcesUsed ?? [],
1760
- disclosure,
1761
- budgetsApplied: snapshot?.budgetsApplied,
1762
- auditAnomalies,
1763
- budgetWarning: budgetDecision.reason === "warn-over-soft" ? budgetDecision : void 0,
1764
- latencyMs: snapshot?.latencyMs ?? Date.now() - startedAt,
1765
- debug
1766
- };
1767
- }
1768
- async recallExplain(request = {}) {
1769
- const requestedNamespace = request.namespace?.trim() ? this.resolveNamespace(request.namespace) : void 0;
1770
- if (requestedNamespace) {
1771
- const principal = resolvePrincipal(request.sessionKey, this.orchestrator.config);
1772
- if (!canReadNamespace(principal, requestedNamespace, this.orchestrator.config)) {
1773
- return { found: false };
1774
- }
1775
- }
1776
- const snapshot = request.sessionKey ? (() => {
1777
- const candidate = this.orchestrator.lastRecall.get(request.sessionKey);
1778
- if (!candidate) return null;
1779
- if (!requestedNamespace) return candidate;
1780
- return candidate.namespace === requestedNamespace ? candidate : null;
1781
- })() : (() => {
1782
- const candidate = this.orchestrator.lastRecall.getMostRecent();
1783
- if (!candidate) return null;
1784
- if (!requestedNamespace) return candidate;
1785
- return candidate.namespace === requestedNamespace ? candidate : null;
1786
- })();
1787
- const namespace = requestedNamespace ?? snapshot?.namespace ?? this.orchestrator.config.defaultNamespace;
1788
- const [intent, graph] = await Promise.all([
1789
- this.orchestrator.getLastIntentSnapshot(namespace),
1790
- this.orchestrator.getLastGraphRecallSnapshot(namespace)
1791
- ]);
1792
- if (!snapshot && !intent && !graph) return { found: false };
1793
- return { found: true, snapshot: snapshot ?? void 0, intent, graph };
1794
- }
1795
- async recallTierExplain(sessionKey, namespace, authenticatedPrincipal) {
1796
- const namespacesEnabled = this.orchestrator.config.namespacesEnabled;
1797
- const requestedNamespace = namespace?.trim() ? this.resolveNamespace(namespace) : void 0;
1798
- const principal = authenticatedPrincipal?.trim() || resolvePrincipal(sessionKey, this.orchestrator.config);
1799
- if (requestedNamespace) {
1800
- if (!canReadNamespace(principal, requestedNamespace, this.orchestrator.config)) {
1801
- return toRecallExplainJson(null);
1802
- }
1803
- } else if (namespacesEnabled && !authenticatedPrincipal?.trim() && !sessionKey?.trim()) {
1804
- return toRecallExplainJson(null);
1805
- }
1806
- const candidate = sessionKey ? this.orchestrator.lastRecall.get(sessionKey) : this.orchestrator.lastRecall.getMostRecent();
1807
- const snapshot = (() => {
1808
- if (!candidate) return null;
1809
- if (requestedNamespace) {
1810
- return candidate.namespace === requestedNamespace ? candidate : null;
1811
- }
1812
- if (!namespacesEnabled) return candidate;
1813
- const snapshotNs = candidate.namespace ?? this.orchestrator.config.defaultNamespace;
1814
- return canReadNamespace(principal, snapshotNs, this.orchestrator.config) ? candidate : null;
1815
- })();
1816
- return toRecallExplainJson(snapshot);
1817
- }
1818
- /**
1819
- * Recall X-ray (issue #570). Runs a recall with `xrayCapture: true`
1820
- * and returns the resulting snapshot as structured JSON so every
1821
- * surface (CLI / HTTP / MCP) gets the same payload. Namespace scope
1822
- * is enforced before the recall fires (CLAUDE.md rule 42 — read and
1823
- * write paths must resolve through the same namespace layer) so an
1824
- * unauthorized principal cannot capture an x-ray for a namespace it
1825
- * cannot read.
1826
- */
1827
- async recallXray(request) {
1828
- const query = typeof request.query === "string" ? request.query : "";
1829
- if (query.trim().length === 0) {
1830
- throw new Error("recallXray: query is required and must be non-empty");
1831
- }
1832
- if (request.disclosure !== void 0 && !isRecallDisclosure(request.disclosure)) {
1833
- throw new EngramAccessInputError(
1834
- `recallXray: disclosure must be one of: chunk, section, raw (got: ${String(request.disclosure)})`
1835
- );
1836
- }
1837
- const namespacesEnabled = this.orchestrator.config.namespacesEnabled;
1838
- const requestedNamespace = request.namespace?.trim() ? this.resolveNamespace(request.namespace) : void 0;
1839
- const authenticatedPrincipal = request.authenticatedPrincipal?.trim();
1840
- const principal = authenticatedPrincipal || resolvePrincipal(request.sessionKey, this.orchestrator.config);
1841
- if (requestedNamespace) {
1842
- if (!canReadNamespace(
1843
- principal,
1844
- requestedNamespace,
1845
- this.orchestrator.config
1846
- )) {
1847
- return { snapshotFound: false };
1848
- }
1849
- } else if (namespacesEnabled && !authenticatedPrincipal && !request.sessionKey?.trim()) {
1850
- return { snapshotFound: false };
1851
- }
1852
- let budgetOverride;
1853
- if (request.budget !== void 0 && request.budget !== null) {
1854
- const parsed = typeof request.budget === "number" ? request.budget : Number(request.budget);
1855
- if (!Number.isFinite(parsed) || parsed <= 0 || !Number.isInteger(parsed)) {
1856
- throw new Error(
1857
- `recallXray: budget expects a positive integer; got ${JSON.stringify(request.budget)}`
1858
- );
1859
- }
1860
- budgetOverride = parsed;
1861
- }
1862
- const previousQueue = this.xrayQueue;
1863
- let release = () => {
1864
- };
1865
- this.xrayQueue = new Promise((resolve2) => {
1866
- release = resolve2;
1867
- });
1868
- await previousQueue;
1869
- try {
1870
- this.orchestrator.clearLastXraySnapshot();
1871
- await this.orchestrator.recall(query, request.sessionKey?.trim() || void 0, {
1872
- xrayCapture: true,
1873
- ...requestedNamespace ? { namespace: requestedNamespace } : {},
1874
- ...budgetOverride !== void 0 ? { budgetCharsOverride: budgetOverride } : {},
1875
- // When the caller supplies an authenticated principal, forward
1876
- // it via the dedicated override channel so orchestrator-side
1877
- // ACL decisions use the SAME principal the access-surface
1878
- // pre-check above authorized. Threading an
1879
- // `authenticatedPrincipal` through `sessionKey` would be wrong:
1880
- // `resolvePrincipal(sessionKey)` only maps configured raw
1881
- // session keys and otherwise collapses to `"default"`, which
1882
- // in namespace-enabled deployments produces false denials /
1883
- // wrong-scope serving despite the pre-check passing
1884
- // (CLAUDE.md rule 42).
1885
- ...authenticatedPrincipal ? { principalOverride: authenticatedPrincipal } : {}
1886
- });
1887
- const rawSnapshot = this.orchestrator.getLastXraySnapshot();
1888
- if (!rawSnapshot) return { snapshotFound: false };
1889
- if (requestedNamespace && rawSnapshot.namespace !== requestedNamespace) {
1890
- return { snapshotFound: false };
1891
- }
1892
- let snapshot = rawSnapshot;
1893
- const xrayFilterTags = normalizeTags(request.tags);
1894
- let xrayTagMatch;
1895
- try {
1896
- xrayTagMatch = parseTagMatch(request.tagMatch);
1897
- } catch (err) {
1898
- throw new EngramAccessInputError(
1899
- err instanceof Error ? err.message : String(err)
1900
- );
1901
- }
1902
- if (xrayFilterTags && xrayFilterTags.length > 0) {
1903
- const namespace = snapshot.namespace ? this.resolveNamespace(snapshot.namespace) : this.orchestrator.config.defaultNamespace;
1904
- const tagsByIndex = await Promise.all(
1905
- snapshot.results.map(async (result) => {
1906
- try {
1907
- const storage = await this.orchestrator.getStorage(namespace);
1908
- const memory = await storage.readMemoryByPath(result.path);
1909
- const t = memory?.frontmatter?.tags;
1910
- return Array.isArray(t) ? normalizeProjectionTags(t) : [];
1911
- } catch {
1912
- return [];
1913
- }
1914
- })
1915
- );
1916
- const tagged = snapshot.results.map((result, index) => ({
1917
- result,
1918
- tags: tagsByIndex[index] ?? []
1919
- }));
1920
- const { results: admittedTagged, trace } = applyTagFilter(tagged, {
1921
- tags: xrayFilterTags,
1922
- tagMatch: xrayTagMatch
1923
- });
1924
- const admittedResults = admittedTagged.map((entry) => entry.result);
1925
- const filters = trace ? [...snapshot.filters, trace] : snapshot.filters;
1926
- snapshot = { ...snapshot, results: admittedResults, filters };
1927
- }
1928
- if (request.disclosure !== void 0) {
1929
- const disclosure = request.disclosure;
1930
- const namespace = snapshot.namespace ? this.resolveNamespace(snapshot.namespace) : this.orchestrator.config.defaultNamespace;
1931
- const trimmedSessionKey = request.sessionKey?.trim() || void 0;
1932
- const rawExcerpts = disclosure === "raw" ? await this.fetchRawExcerpts(disclosure, {
1933
- query,
1934
- ...trimmedSessionKey ? { sessionKey: trimmedSessionKey } : {},
1935
- namespace
1936
- }) : null;
1937
- const rawExcerptText = rawExcerpts && rawExcerpts.length > 0 ? rawExcerpts.map((e) => e.content).join("\n") : "";
1938
- const memoryByIndex = await Promise.all(
1939
- snapshot.results.map(async (result) => {
1940
- try {
1941
- const storage = await this.orchestrator.getStorage(namespace);
1942
- return await storage.readMemoryByPath(result.path);
1943
- } catch {
1944
- return null;
1945
- }
1946
- })
1947
- );
1948
- const firstReadableIndex = memoryByIndex.findIndex((m) => m !== null);
1949
- const baseDir = (await this.orchestrator.getStorage(namespace)).dir;
1950
- const decorated = snapshot.results.map((result, index) => {
1951
- const memory = memoryByIndex[index];
1952
- if (!memory) {
1953
- return { ...result, disclosure };
1954
- }
1955
- const shaped = shapeMemorySummary(
1956
- memory,
1957
- baseDir,
1958
- disclosure,
1959
- disclosure === "raw" && index === firstReadableIndex && rawExcerpts && rawExcerpts.length > 0 ? rawExcerpts : void 0
1960
- );
1961
- return {
1962
- ...result,
1963
- disclosure,
1964
- estimatedTokens: estimateRecallTokens(JSON.stringify(shaped))
1965
- };
1966
- });
1967
- if (disclosure === "raw" && firstReadableIndex === -1 && rawExcerptText.length > 0 && decorated.length > 0) {
1968
- decorated[0] = {
1969
- ...decorated[0],
1970
- disclosure,
1971
- estimatedTokens: estimateRecallTokens(rawExcerptText)
1972
- };
1973
- }
1974
- return {
1975
- snapshotFound: true,
1976
- snapshot: { ...snapshot, results: decorated }
1977
- };
1978
- }
1979
- return { snapshotFound: true, snapshot };
1980
- } finally {
1981
- release();
1982
- }
1983
- }
1984
- // Sequence lock for `recallXray` — see comment inside the method.
1985
- // Lives on the instance so every x-ray call on the same service
1986
- // shares it, and so separate services in the same process (e.g.
1987
- // per-tenant) do not block each other.
1988
- xrayQueue = Promise.resolve();
1989
- async memoryStore(request) {
1990
- const namespace = this.resolveWritableNamespace(
1991
- request.namespace,
1992
- request.sessionKey,
1993
- request.authenticatedPrincipal
1994
- );
1995
- const schemaVersion = request.schemaVersion ?? ENGRAM_ACCESS_WRITE_SCHEMA_VERSION;
1996
- if (schemaVersion !== ENGRAM_ACCESS_WRITE_SCHEMA_VERSION) {
1997
- throw new EngramAccessInputError(`unsupported schemaVersion: ${schemaVersion}`);
1998
- }
1999
- const execute = async () => {
2000
- const candidate = this.validateWriteCandidate(request, namespace);
2001
- if (request.dryRun === true) {
2002
- return {
2003
- schemaVersion: ENGRAM_ACCESS_WRITE_SCHEMA_VERSION,
2004
- operation: "memory_store",
2005
- namespace,
2006
- dryRun: true,
2007
- accepted: true,
2008
- queued: false,
2009
- status: "validated",
2010
- idempotencyKey: request.idempotencyKey?.trim() || void 0
2011
- };
2012
- }
2013
- const result = await persistExplicitCapture(this.orchestrator, candidate, "memory_store");
2014
- const response = {
2015
- schemaVersion: ENGRAM_ACCESS_WRITE_SCHEMA_VERSION,
2016
- operation: "memory_store",
2017
- namespace,
2018
- dryRun: false,
2019
- accepted: true,
2020
- queued: false,
2021
- status: result.duplicateOf ? "duplicate" : "stored",
2022
- memoryId: result.id,
2023
- duplicateOf: result.duplicateOf,
2024
- idempotencyKey: request.idempotencyKey?.trim() || void 0
2025
- };
2026
- log.info(
2027
- `access-write op=memory_store namespace=${namespace} dryRun=false status=${response.status} memoryId=${response.memoryId ?? "-"} idempotency=${response.idempotencyKey ? "yes" : "no"}`
2028
- );
2029
- return response;
2030
- };
2031
- return this.handleIdempotentWrite({
2032
- operation: "memory_store",
2033
- idempotencyKey: request.idempotencyKey,
2034
- requestFingerprint: {
2035
- schemaVersion,
2036
- content: request.content,
2037
- category: request.category,
2038
- confidence: request.confidence,
2039
- namespace,
2040
- tags: request.tags,
2041
- entityRef: request.entityRef,
2042
- ttl: request.ttl,
2043
- sourceReason: request.sourceReason
2044
- },
2045
- skip: request.dryRun === true,
2046
- execute
2047
- });
2048
- }
2049
- async peekMemoryStoreIdempotency(request) {
2050
- const namespace = this.resolveWritableNamespace(
2051
- request.namespace,
2052
- request.sessionKey,
2053
- request.authenticatedPrincipal
2054
- );
2055
- const schemaVersion = request.schemaVersion ?? ENGRAM_ACCESS_WRITE_SCHEMA_VERSION;
2056
- if (schemaVersion !== ENGRAM_ACCESS_WRITE_SCHEMA_VERSION) {
2057
- throw new EngramAccessInputError(`unsupported schemaVersion: ${schemaVersion}`);
2058
- }
2059
- return this.peekIdempotentWrite({
2060
- operation: "memory_store",
2061
- idempotencyKey: request.idempotencyKey,
2062
- requestFingerprint: {
2063
- schemaVersion,
2064
- content: request.content,
2065
- category: request.category,
2066
- confidence: request.confidence,
2067
- namespace,
2068
- tags: request.tags,
2069
- entityRef: request.entityRef,
2070
- ttl: request.ttl,
2071
- sourceReason: request.sourceReason
2072
- },
2073
- skip: request.dryRun === true
2074
- });
2075
- }
2076
- async suggestionSubmit(request) {
2077
- const namespace = this.resolveWritableNamespace(
2078
- request.namespace,
2079
- request.sessionKey,
2080
- request.authenticatedPrincipal
2081
- );
2082
- const schemaVersion = request.schemaVersion ?? ENGRAM_ACCESS_WRITE_SCHEMA_VERSION;
2083
- if (schemaVersion !== ENGRAM_ACCESS_WRITE_SCHEMA_VERSION) {
2084
- throw new EngramAccessInputError(`unsupported schemaVersion: ${schemaVersion}`);
2085
- }
2086
- const execute = async () => {
2087
- const candidate = this.validateWriteCandidate(request, namespace);
2088
- if (request.dryRun === true) {
2089
- return {
2090
- schemaVersion: ENGRAM_ACCESS_WRITE_SCHEMA_VERSION,
2091
- operation: "suggestion_submit",
2092
- namespace,
2093
- dryRun: true,
2094
- accepted: true,
2095
- queued: true,
2096
- status: "validated",
2097
- idempotencyKey: request.idempotencyKey?.trim() || void 0
2098
- };
2099
- }
2100
- const result = await queueExplicitCaptureForReview(
2101
- this.orchestrator,
2102
- candidate,
2103
- "suggestion_submit",
2104
- new Error(request.sourceReason?.trim() || "submitted via engram suggestion_submit")
2105
- );
2106
- const response = {
2107
- schemaVersion: ENGRAM_ACCESS_WRITE_SCHEMA_VERSION,
2108
- operation: "suggestion_submit",
2109
- namespace,
2110
- dryRun: false,
2111
- accepted: true,
2112
- queued: true,
2113
- status: "queued_for_review",
2114
- memoryId: result.id,
2115
- duplicateOf: result.duplicateOf,
2116
- idempotencyKey: request.idempotencyKey?.trim() || void 0
2117
- };
2118
- log.info(
2119
- `access-write op=suggestion_submit namespace=${namespace} dryRun=false status=${response.status} memoryId=${response.memoryId ?? "-"} idempotency=${response.idempotencyKey ? "yes" : "no"}`
2120
- );
2121
- return response;
2122
- };
2123
- return this.handleIdempotentWrite({
2124
- operation: "suggestion_submit",
2125
- idempotencyKey: request.idempotencyKey,
2126
- requestFingerprint: {
2127
- schemaVersion,
2128
- content: request.content,
2129
- category: request.category,
2130
- confidence: request.confidence,
2131
- namespace,
2132
- tags: request.tags,
2133
- entityRef: request.entityRef,
2134
- ttl: request.ttl,
2135
- sourceReason: request.sourceReason
2136
- },
2137
- skip: request.dryRun === true,
2138
- execute
2139
- });
2140
- }
2141
- async peekSuggestionSubmitIdempotency(request) {
2142
- const namespace = this.resolveWritableNamespace(
2143
- request.namespace,
2144
- request.sessionKey,
2145
- request.authenticatedPrincipal
2146
- );
2147
- const schemaVersion = request.schemaVersion ?? ENGRAM_ACCESS_WRITE_SCHEMA_VERSION;
2148
- if (schemaVersion !== ENGRAM_ACCESS_WRITE_SCHEMA_VERSION) {
2149
- throw new EngramAccessInputError(`unsupported schemaVersion: ${schemaVersion}`);
2150
- }
2151
- return this.peekIdempotentWrite({
2152
- operation: "suggestion_submit",
2153
- idempotencyKey: request.idempotencyKey,
2154
- requestFingerprint: {
2155
- schemaVersion,
2156
- content: request.content,
2157
- category: request.category,
2158
- confidence: request.confidence,
2159
- namespace,
2160
- tags: request.tags,
2161
- entityRef: request.entityRef,
2162
- ttl: request.ttl,
2163
- sourceReason: request.sourceReason
2164
- },
2165
- skip: request.dryRun === true
2166
- });
2167
- }
2168
- validateWriteCandidate(request, namespace) {
2169
- try {
2170
- return validateExplicitCaptureInput(
2171
- {
2172
- ...request,
2173
- namespace
2174
- },
2175
- "legacy_tool"
2176
- );
2177
- } catch (error) {
2178
- const message = error instanceof Error ? error.message : String(error);
2179
- throw new EngramAccessInputError(message);
2180
- }
2181
- }
2182
- async memoryGet(memoryId, namespace, principal) {
2183
- const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);
2184
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
2185
- const memory = await storage.getMemoryById(memoryId);
2186
- if (!memory) {
2187
- return { found: false, namespace: resolvedNamespace };
2188
- }
2189
- return {
2190
- found: true,
2191
- namespace: resolvedNamespace,
2192
- memory: this.serializeMemory(memory)
2193
- };
2194
- }
2195
- async memoryBrowse(request = {}) {
2196
- const storage = await this.orchestrator.getStorage(request.namespace);
2197
- const resolvedNamespace = request.namespace?.trim() || this.orchestrator.config.defaultNamespace;
2198
- const { limit, offset } = normalizePagination(request.limit, request.offset);
2199
- const sort = normalizeBrowseSort(request.sort);
2200
- const query = request.query?.trim().toLowerCase() ?? "";
2201
- const statusFilter = request.status?.trim().toLowerCase();
2202
- const categoryFilter = request.category?.trim().toLowerCase();
2203
- const projected = await storage.browseProjectedMemories({
2204
- query,
2205
- status: statusFilter,
2206
- category: categoryFilter,
2207
- sort,
2208
- limit,
2209
- offset
2210
- });
2211
- if (projected) {
2212
- return {
2213
- namespace: resolvedNamespace,
2214
- sort,
2215
- total: projected.total,
2216
- count: projected.memories.length,
2217
- limit,
2218
- offset,
2219
- memories: projected.memories.map((row) => ({ ...row }))
2220
- };
2221
- }
2222
- let memories = [...await storage.readAllMemories(), ...await storage.readArchivedMemories()];
2223
- memories = memories.filter((memory) => {
2224
- const status = inferMemoryStatus(memory.frontmatter, toMemoryPathRel(storage.dir, memory.path)).toLowerCase();
2225
- if (statusFilter && status !== statusFilter) return false;
2226
- if (categoryFilter && memory.frontmatter.category.toLowerCase() !== categoryFilter) return false;
2227
- if (!query) return true;
2228
- const haystack = [
2229
- memory.frontmatter.id,
2230
- memory.path,
2231
- memory.content,
2232
- memory.frontmatter.entityRef ?? "",
2233
- ...memory.frontmatter.tags
2234
- ].join("\n").toLowerCase();
2235
- return haystack.includes(query);
2236
- });
2237
- memories.sort((left, right) => compareBrowseMemory(sort, left, right));
2238
- const page = memories.slice(offset, offset + limit).map((memory) => this.serializeMemorySummary(memory, storage.dir));
2239
- return {
2240
- namespace: resolvedNamespace,
2241
- sort,
2242
- total: memories.length,
2243
- count: page.length,
2244
- limit,
2245
- offset,
2246
- memories: page
2247
- };
2248
- }
2249
- async memoryTimeline(memoryId, namespace, limit = 200, principal) {
2250
- const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);
2251
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
2252
- const timeline = await storage.getMemoryTimeline(memoryId, limit);
2253
- return {
2254
- found: timeline.length > 0,
2255
- namespace: resolvedNamespace,
2256
- count: timeline.length,
2257
- timeline
2258
- };
2259
- }
2260
- async entityList(options = {}) {
2261
- const storage = await this.orchestrator.getStorage(options.namespace);
2262
- const resolvedNamespace = options.namespace?.trim() || this.orchestrator.config.defaultNamespace;
2263
- const { limit, offset } = normalizePagination(options.limit, options.offset);
2264
- const query = options.query?.trim().toLowerCase() ?? "";
2265
- const names = await storage.listEntityNames();
2266
- const entities = [];
2267
- for (const name of names) {
2268
- const raw = await storage.readEntity(name);
2269
- if (!raw) continue;
2270
- const entity = parseEntityFile(raw, this.orchestrator.config.entitySchemas);
2271
- if (query) {
2272
- const haystack = [
2273
- entity.name,
2274
- entity.type,
2275
- entity.synthesis || entity.summary || "",
2276
- ...entity.aliases,
2277
- ...entity.facts,
2278
- ...(entity.structuredSections ?? []).flatMap((section) => [section.title, ...section.facts])
2279
- ].join("\n").toLowerCase();
2280
- if (!haystack.includes(query)) continue;
2281
- }
2282
- entities.push({
2283
- name: entity.name,
2284
- type: entity.type,
2285
- updated: entity.updated,
2286
- summary: entity.synthesis || entity.summary,
2287
- aliases: entity.aliases
2288
- });
2289
- }
2290
- entities.sort((left, right) => left.name.localeCompare(right.name));
2291
- const page = entities.slice(offset, offset + limit);
2292
- return {
2293
- namespace: resolvedNamespace,
2294
- total: entities.length,
2295
- count: page.length,
2296
- limit,
2297
- offset,
2298
- entities: page
2299
- };
2300
- }
2301
- async entityGet(name, namespace) {
2302
- const storage = await this.orchestrator.getStorage(namespace);
2303
- const resolvedNamespace = namespace?.trim() || this.orchestrator.config.defaultNamespace;
2304
- const raw = await storage.readEntity(name);
2305
- if (!raw) return { found: false, namespace: resolvedNamespace };
2306
- return {
2307
- found: true,
2308
- namespace: resolvedNamespace,
2309
- entity: parseEntityFile(raw, this.orchestrator.config.entitySchemas)
2310
- };
2311
- }
2312
- async reviewQueue(runId, namespace, principal) {
2313
- const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);
2314
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
2315
- const projected = await storage.getProjectedGovernanceRecord();
2316
- if (projected && (!runId || projected.runId === runId.trim())) {
2317
- const projectedAppliedActions = projected.appliedActionRows.map((row) => ({
2318
- action: row.action,
2319
- memoryId: row.memoryId,
2320
- reasonCode: row.reasonCode,
2321
- beforeStatus: row.beforeStatus,
2322
- afterStatus: row.afterStatus,
2323
- originalPath: row.originalPath,
2324
- currentPath: row.currentPath
2325
- }));
2326
- const projectedProposedActions = await buildProjectedGovernanceProposedActions(storage, projected);
2327
- const projectedArtifact = await (async () => {
2328
- try {
2329
- return await readMemoryGovernanceRunArtifact(storage.dir, projected.runId);
2330
- } catch {
2331
- return null;
2332
- }
2333
- })();
2334
- const metrics = projected.metrics;
2335
- const fallbackTransitionReport = {
2336
- proposed: groupActionsByStatus(projectedProposedActions),
2337
- applied: groupActionsByStatus(projectedAppliedActions)
2338
- };
2339
- const transitionReport = projectedArtifact?.transitionReport ? {
2340
- proposed: hasGroupedGovernanceActions(projectedArtifact.transitionReport.proposed) || projectedProposedActions.length === 0 ? projectedArtifact.transitionReport.proposed : fallbackTransitionReport.proposed,
2341
- applied: hasGroupedGovernanceActions(projectedArtifact.transitionReport.applied) || projectedAppliedActions.length === 0 ? projectedArtifact.transitionReport.applied : fallbackTransitionReport.applied
2342
- } : fallbackTransitionReport;
2343
- const qualityScore = projectedArtifact?.qualityScore ?? metrics?.qualityScore ?? buildQualityScore(metrics?.reviewReasons ?? {
2344
- exact_duplicate: 0,
2345
- semantic_duplicate_candidate: 0,
2346
- disputed_memory: 0,
2347
- speculative_low_confidence: 0,
2348
- archive_candidate: 0,
2349
- explicit_capture_review: 0,
2350
- malformed_import: 0
2351
- });
2352
- const effectiveMetrics = metrics ? { ...metrics, qualityScore: metrics.qualityScore ?? qualityScore } : metrics;
2353
- return {
2354
- found: true,
2355
- namespace: resolvedNamespace,
2356
- runId: projected.runId,
2357
- summary: projected.summary,
2358
- metrics: effectiveMetrics,
2359
- qualityScore,
2360
- reviewQueue: projected.reviewQueueRows.map((row) => ({
2361
- entryId: row.entryId,
2362
- memoryId: row.memoryId,
2363
- path: row.path,
2364
- reasonCode: row.reasonCode,
2365
- severity: row.severity,
2366
- suggestedAction: row.suggestedAction,
2367
- suggestedStatus: row.suggestedStatus,
2368
- relatedMemoryIds: row.relatedMemoryIds
2369
- })),
2370
- appliedActions: projectedAppliedActions,
2371
- transitionReport,
2372
- report: projected.report
2373
- };
2374
- }
2375
- const resolvedRunId = runId?.trim() || (await listMemoryGovernanceRuns(storage.dir))[0];
2376
- if (!resolvedRunId) return { found: false, namespace: resolvedNamespace };
2377
- const artifact = await readMemoryGovernanceRunArtifact(storage.dir, resolvedRunId);
2378
- return {
2379
- found: true,
2380
- namespace: resolvedNamespace,
2381
- runId: resolvedRunId,
2382
- summary: artifact.summary,
2383
- metrics: artifact.metrics,
2384
- qualityScore: artifact.qualityScore,
2385
- reviewQueue: artifact.reviewQueue,
2386
- appliedActions: artifact.appliedActions,
2387
- transitionReport: artifact.transitionReport,
2388
- report: artifact.report
2389
- };
2390
- }
2391
- async maintenance(namespace, principal) {
2392
- const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);
2393
- return {
2394
- namespace: resolvedNamespace,
2395
- health: await this.health(resolvedNamespace),
2396
- latestGovernanceRun: await this.reviewQueue(void 0, resolvedNamespace, principal)
2397
- };
2398
- }
2399
- async quality(namespace, principal) {
2400
- const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);
2401
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
2402
- const governance = await this.reviewQueue(void 0, resolvedNamespace, principal);
2403
- const nowMs = Date.now();
2404
- const statusCounts = {};
2405
- const categoryCounts = {};
2406
- const confidenceTierCounts = {};
2407
- const ageBucketCounts = {};
2408
- let staleActive = 0;
2409
- let lowConfidenceActive = 0;
2410
- const memories = [...await storage.readAllMemories(), ...await storage.readArchivedMemories()];
2411
- for (const memory of memories) {
2412
- const status = inferMemoryStatus(memory.frontmatter, toMemoryPathRel(storage.dir, memory.path)).toLowerCase();
2413
- const confidenceTier = memory.frontmatter.confidenceTier ?? "unknown";
2414
- const ageBucket = bucketMemoryAge(memory.frontmatter.updated ?? memory.frontmatter.created, nowMs);
2415
- incrementCount(statusCounts, status);
2416
- incrementCount(categoryCounts, memory.frontmatter.category);
2417
- incrementCount(confidenceTierCounts, confidenceTier);
2418
- incrementCount(ageBucketCounts, ageBucket);
2419
- if (status === "active") {
2420
- if (ageBucket === "91_plus_days") staleActive += 1;
2421
- if ((memory.frontmatter.confidence ?? 0) < 0.6) lowConfidenceActive += 1;
2422
- }
2423
- }
2424
- return {
2425
- namespace: resolvedNamespace,
2426
- totalMemories: memories.length,
2427
- statusCounts,
2428
- categoryCounts,
2429
- confidenceTierCounts,
2430
- ageBucketCounts,
2431
- archivePressure: {
2432
- pendingReview: statusCounts.pending_review ?? 0,
2433
- quarantined: statusCounts.quarantined ?? 0,
2434
- archived: statusCounts.archived ?? 0,
2435
- staleActive,
2436
- lowConfidenceActive
2437
- },
2438
- latestGovernanceRun: {
2439
- found: governance.found,
2440
- runId: governance.runId,
2441
- qualityScore: governance.qualityScore ?? governance.metrics?.qualityScore,
2442
- reviewQueueCount: governance.reviewQueue?.length ?? 0
2443
- }
2444
- };
2445
- }
2446
- async governanceRun(request, principal) {
2447
- const deepSleep = this.orchestrator.config.dreamsPhases.deepSleep;
2448
- if (deepSleep.enabled === false && deepSleep.enabledExplicitlySet === true) {
2449
- throw new Error("memory governance is disabled by dreams.phases.deepSleep.enabled=false");
2450
- }
2451
- const resolvedNamespace = this.resolveWritableNamespace(
2452
- request.namespace,
2453
- void 0,
2454
- request.authenticatedPrincipal ?? principal
2455
- );
2456
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
2457
- const mode = request.mode === "apply" ? "apply" : "shadow";
2458
- const boundedBatchSize = typeof request.batchSize === "number" && Number.isFinite(request.batchSize) ? Math.max(1, Math.floor(request.batchSize)) : void 0;
2459
- const result = await runMemoryGovernance({
2460
- memoryDir: storage.dir,
2461
- mode,
2462
- recentDays: typeof request.recentDays === "number" && Number.isFinite(request.recentDays) ? Math.max(1, Math.floor(request.recentDays)) : void 0,
2463
- maxMemories: typeof request.maxMemories === "number" && Number.isFinite(request.maxMemories) ? Math.max(1, Math.floor(request.maxMemories)) : void 0,
2464
- batchSize: boundedBatchSize
2465
- });
2466
- if (mode === "apply") {
2467
- try {
2468
- await this.orchestrator.processEntitySynthesisQueue(
2469
- resolvedNamespace,
2470
- Math.min(boundedBatchSize ?? 5, 5)
2471
- );
2472
- } catch (error) {
2473
- log.debug(`governanceRun: entity synthesis refresh failed after governance apply: ${error}`);
2474
- }
2475
- }
2476
- return {
2477
- namespace: resolvedNamespace,
2478
- runId: result.runId,
2479
- traceId: result.traceId,
2480
- mode: result.mode,
2481
- reviewQueueCount: result.reviewQueue.length,
2482
- proposedActionCount: result.proposedActions.length,
2483
- appliedActionCount: result.appliedActions.length,
2484
- summaryPath: result.summaryPath,
2485
- reportPath: result.reportPath
2486
- };
2487
- }
2488
- async procedureMiningRun(request, principal) {
2489
- const resolvedNamespace = this.resolveWritableNamespace(
2490
- request.namespace,
2491
- void 0,
2492
- request.authenticatedPrincipal ?? principal
2493
- );
2494
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
2495
- const result = await runProcedureMining({
2496
- memoryDir: storage.dir,
2497
- storage,
2498
- config: this.orchestrator.config
2499
- });
2500
- return {
2501
- namespace: resolvedNamespace,
2502
- clustersProcessed: result.clustersProcessed,
2503
- proceduresWritten: result.proceduresWritten,
2504
- skippedReason: result.skippedReason
2505
- };
2506
- }
2507
- async liveConnectorsRun(request = {}, principal) {
2508
- this.resolveWritableNamespace(
2509
- void 0,
2510
- void 0,
2511
- request.authenticatedPrincipal ?? principal
2512
- );
2513
- return this.orchestrator.runLiveConnectors({
2514
- force: request.force === true
2515
- });
2516
- }
2517
- /**
2518
- * Run the pattern-reinforcement maintenance job (issue #687 PR 2/4).
2519
- *
2520
- * Cluster duplicate non-procedural memories and reinforce the
2521
- * canonical (most-recent) member. Gated on
2522
- * `patternReinforcementEnabled` — when disabled, returns
2523
- * `{ ran: false, skippedReason: "disabled" }` so the cron payload
2524
- * surface in CI logs cleanly.
2525
- *
2526
- * Resolves the namespace via the same writable path used by
2527
- * `procedureMiningRun` so cross-tenant writes are impossible
2528
- * (CLAUDE.md rule 42).
2529
- *
2530
- * Delegates the run to `orchestrator.runPatternReinforcement` so
2531
- * the cadence floor (`patternReinforcementCadenceMs`) is enforced
2532
- * uniformly across cron + MCP paths (PR #730 review feedback,
2533
- * Codex P2). Accepts `force: true` for ad-hoc operator runs that
2534
- * must bypass the cadence floor — mirrors the pattern used by
2535
- * other maintenance MCP tools.
2536
- */
2537
- async patternReinforcementRun(request = {}, principal) {
2538
- const resolvedNamespace = this.resolveWritableNamespace(
2539
- request.namespace,
2540
- void 0,
2541
- request.authenticatedPrincipal ?? principal
2542
- );
2543
- const outcome = await this.orchestrator.runPatternReinforcement({
2544
- namespace: resolvedNamespace,
2545
- force: request.force === true
2546
- });
2547
- if (!outcome.ran) {
2548
- return {
2549
- namespace: resolvedNamespace,
2550
- ran: false,
2551
- skippedReason: outcome.skippedReason,
2552
- clustersFound: 0,
2553
- canonicalsUpdated: 0,
2554
- duplicatesSuperseded: 0
2555
- };
2556
- }
2557
- const result = outcome.result;
2558
- return {
2559
- namespace: resolvedNamespace,
2560
- ran: true,
2561
- clustersFound: result.clustersFound,
2562
- canonicalsUpdated: result.canonicalsUpdated,
2563
- duplicatesSuperseded: result.duplicatesSuperseded,
2564
- result
2565
- };
2566
- }
2567
- /**
2568
- * Procedural memory stats (issue #567 PR 5/5). Read-only — resolves the
2569
- * namespace via the same path used by `recallExplain` / `trustZoneStatus`
2570
- * so cross-tenant reads are impossible (CLAUDE.md rule 42).
2571
- */
2572
- async procedureStats(request = {}, principal) {
2573
- const resolvedNamespace = this.resolveReadableNamespace(
2574
- request.namespace,
2575
- principal
2576
- );
2577
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
2578
- const report = await computeProcedureStats({
2579
- storage,
2580
- config: this.orchestrator.config
2581
- });
2582
- return { namespace: resolvedNamespace, ...report };
2583
- }
2584
- async memorySummarizeHourly() {
2585
- await this.orchestrator.summarizer.runHourly();
2586
- return {
2587
- ok: true,
2588
- message: "Hourly summarization completed. Check the summaries directory for results."
2589
- };
2590
- }
2591
- async conversationIndexUpdate(request = {}) {
2592
- if (!this.orchestrator.config.conversationIndexEnabled) {
2593
- return {
2594
- enabled: false,
2595
- sessions: 0,
2596
- chunks: 0,
2597
- skipped: 0,
2598
- skippedSessionKeys: [],
2599
- embeddedRuns: 0,
2600
- reason: "disabled"
2601
- };
2602
- }
2603
- const hours = typeof request.hours === "number" && Number.isFinite(request.hours) ? Math.max(1, Math.floor(request.hours)) : 24;
2604
- let sessionKey;
2605
- if (request.sessionKey !== void 0) {
2606
- if (typeof request.sessionKey !== "string" || request.sessionKey.trim().length === 0) {
2607
- throw new EngramAccessInputError("sessionKey must be a non-empty string when provided");
2608
- }
2609
- sessionKey = request.sessionKey.trim();
2610
- }
2611
- if (sessionKey) {
2612
- const result = await this.orchestrator.updateConversationIndex(
2613
- sessionKey,
2614
- hours,
2615
- { embed: request.embed }
2616
- );
2617
- return {
2618
- enabled: true,
2619
- sessionKey,
2620
- sessions: 1,
2621
- chunks: result.chunks,
2622
- skipped: result.skipped ? 1 : 0,
2623
- skippedSessionKeys: result.skipped ? [sessionKey] : [],
2624
- embeddedRuns: result.embedded ? 1 : 0,
2625
- reason: result.reason,
2626
- retryAfterMs: result.retryAfterMs
2627
- };
2628
- }
2629
- const sessionKeys = await this.orchestrator.transcript.listSessionKeys();
2630
- let chunks = 0;
2631
- let skipped = 0;
2632
- const skippedSessionKeys = [];
2633
- let embeddedRuns = 0;
2634
- for (const sessionKey2 of sessionKeys) {
2635
- const result = await this.orchestrator.updateConversationIndex(
2636
- sessionKey2,
2637
- hours,
2638
- { embed: request.embed }
2639
- );
2640
- chunks += result.chunks;
2641
- if (result.skipped) {
2642
- skipped += 1;
2643
- skippedSessionKeys.push(sessionKey2);
2644
- }
2645
- if (result.embedded) {
2646
- embeddedRuns += 1;
2647
- }
2648
- }
2649
- return {
2650
- enabled: true,
2651
- sessions: sessionKeys.length,
2652
- chunks,
2653
- skipped,
2654
- skippedSessionKeys,
2655
- embeddedRuns
2656
- };
2657
- }
2658
- async profilingReport(request = {}) {
2659
- const profiler = this.orchestrator.profiler;
2660
- if (!profiler.isEnabled) {
2661
- return {
2662
- enabled: false,
2663
- reason: "disabled",
2664
- message: "Profiling is disabled. Set profilingEnabled: true in your plugin config to enable."
2665
- };
2666
- }
2667
- const format = request.format ?? "ascii";
2668
- if (format !== "ascii" && format !== "json") {
2669
- throw new EngramAccessInputError("format must be one of: ascii, json");
2670
- }
2671
- const limit = request.limit ?? 5;
2672
- if (!Number.isInteger(limit) || limit < 1 || limit > 20) {
2673
- throw new EngramAccessInputError("limit must be an integer between 1 and 20");
2674
- }
2675
- const traces = profiler.getRecentTraces(limit);
2676
- const stats = profiler.getStats();
2677
- const bottleneck = profiler.identifyBottleneck();
2678
- if (format === "json") {
2679
- return {
2680
- enabled: true,
2681
- format,
2682
- traces,
2683
- stats,
2684
- bottleneck
2685
- };
2686
- }
2687
- const lines = [];
2688
- lines.push("Engram Profiling Report");
2689
- lines.push("=".repeat(60));
2690
- lines.push("");
2691
- const allBuckets = [
2692
- ["byKind", stats.byKind],
2693
- ["bySpan", stats.bySpan]
2694
- ];
2695
- const hasStats = allBuckets.some(([, entries]) => Object.keys(entries).length > 0);
2696
- if (hasStats) {
2697
- lines.push("Aggregate Stats (all retained traces):");
2698
- for (const [bucket, entries] of allBuckets) {
2699
- for (const [key, summary] of Object.entries(entries)) {
2700
- lines.push(
2701
- ` ${bucket}/${key}: avg=${summary.avgMs}ms p50=${summary.p50Ms}ms p95=${summary.p95Ms}ms max=${summary.maxMs}ms (n=${summary.count})`
2702
- );
2703
- }
2704
- }
2705
- lines.push("");
2706
- }
2707
- if (bottleneck) {
2708
- lines.push(`Bottleneck: ${bottleneck}`);
2709
- lines.push("");
2710
- }
2711
- if (traces.length === 0) {
2712
- lines.push("No traces recorded yet. Trigger a recall or extraction to see timing data.");
2713
- } else {
2714
- for (const trace of traces) {
2715
- lines.push(formatProfileTraceAscii(trace));
2716
- lines.push("");
2717
- }
2718
- }
2719
- return {
2720
- enabled: true,
2721
- format,
2722
- report: lines.join("\n")
2723
- };
2724
- }
2725
- async trustZoneStatus(namespace, principal) {
2726
- const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);
2727
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
2728
- return {
2729
- namespace: resolvedNamespace,
2730
- status: await getTrustZoneStoreStatus({
2731
- memoryDir: storage.dir,
2732
- trustZoneStoreDir: this.orchestrator.config.trustZoneStoreDir,
2733
- enabled: this.orchestrator.config.trustZonesEnabled === true,
2734
- promotionEnabled: this.orchestrator.config.quarantinePromotionEnabled === true,
2735
- poisoningDefenseEnabled: this.orchestrator.config.memoryPoisoningDefenseEnabled === true
2736
- })
2737
- };
2738
- }
2739
- async trustZoneBrowse(request, principal) {
2740
- const resolvedNamespace = this.resolveReadableNamespace(request.namespace, principal);
2741
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
2742
- const result = await listTrustZoneRecords({
2743
- memoryDir: storage.dir,
2744
- trustZoneStoreDir: this.orchestrator.config.trustZoneStoreDir,
2745
- query: request.query,
2746
- zone: request.zone,
2747
- kind: request.kind,
2748
- sourceClass: request.sourceClass,
2749
- limit: request.limit,
2750
- offset: request.offset
2751
- });
2752
- return {
2753
- namespace: resolvedNamespace,
2754
- total: result.total,
2755
- count: result.count,
2756
- limit: result.limit,
2757
- offset: result.offset,
2758
- records: result.records.map((entry) => summarizeTrustZoneRecord(
2759
- entry.record,
2760
- entry.filePath,
2761
- result.allRecords,
2762
- this.orchestrator.config.memoryPoisoningDefenseEnabled === true,
2763
- this.orchestrator.config.trustZonesEnabled === true,
2764
- this.orchestrator.config.quarantinePromotionEnabled === true
2765
- ))
2766
- };
2767
- }
2768
- async trustZonePromote(request) {
2769
- if (!isTrustZoneName(request.targetZone)) {
2770
- throw new EngramAccessInputError(`unsupported trust-zone target: ${String(request.targetZone)}`);
2771
- }
2772
- const resolvedNamespace = this.resolveWritableNamespace(
2773
- request.namespace,
2774
- void 0,
2775
- request.authenticatedPrincipal
2776
- );
2777
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
2778
- let result;
2779
- try {
2780
- result = await promoteTrustZoneRecord({
2781
- memoryDir: storage.dir,
2782
- trustZoneStoreDir: this.orchestrator.config.trustZoneStoreDir,
2783
- enabled: this.orchestrator.config.trustZonesEnabled === true,
2784
- promotionEnabled: this.orchestrator.config.quarantinePromotionEnabled === true,
2785
- poisoningDefenseEnabled: this.orchestrator.config.memoryPoisoningDefenseEnabled === true,
2786
- sourceRecordId: request.recordId,
2787
- targetZone: request.targetZone,
2788
- recordedAt: request.recordedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
2789
- promotionReason: request.promotionReason,
2790
- summary: request.summary,
2791
- dryRun: request.dryRun === true
2792
- });
2793
- } catch (error) {
2794
- throw normalizeTrustZoneInputError(error) ?? error;
2795
- }
2796
- return {
2797
- namespace: resolvedNamespace,
2798
- ...result,
2799
- dryRun: request.dryRun === true
2800
- };
2801
- }
2802
- async trustZoneDemoSeed(request) {
2803
- const resolvedNamespace = this.resolveWritableNamespace(
2804
- request.namespace,
2805
- void 0,
2806
- request.authenticatedPrincipal
2807
- );
2808
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
2809
- let result;
2810
- try {
2811
- result = await seedTrustZoneDemoDataset({
2812
- memoryDir: storage.dir,
2813
- trustZoneStoreDir: this.orchestrator.config.trustZoneStoreDir,
2814
- enabled: this.orchestrator.config.trustZonesEnabled === true,
2815
- scenario: request.scenario,
2816
- recordedAt: request.recordedAt,
2817
- dryRun: request.dryRun === true
2818
- });
2819
- } catch (error) {
2820
- throw normalizeTrustZoneInputError(error) ?? error;
2821
- }
2822
- return {
2823
- namespace: resolvedNamespace,
2824
- ...result
2825
- };
2826
- }
2827
- async reviewDisposition(request) {
2828
- const memoryId = request.memoryId.trim();
2829
- const reasonCode = request.reasonCode.trim();
2830
- if (memoryId.length === 0) {
2831
- throw new EngramAccessInputError("memoryId is required");
2832
- }
2833
- if (reasonCode.length === 0) {
2834
- throw new EngramAccessInputError("reasonCode is required");
2835
- }
2836
- const resolvedNamespace = this.resolveWritableNamespace(
2837
- request.namespace,
2838
- void 0,
2839
- request.authenticatedPrincipal
2840
- );
2841
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
2842
- const memory = await storage.getMemoryById(memoryId);
2843
- if (!memory) {
2844
- throw new EngramAccessInputError(`memory not found: ${memoryId}`);
2845
- }
2846
- const previousStatus = memory.frontmatter.status ?? "active";
2847
- const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2848
- const lifecycle = {
2849
- actor: "admin-console.review-disposition",
2850
- reasonCode,
2851
- ruleVersion: "memory-governance.v1"
2852
- };
2853
- if (request.status === "archived") {
2854
- const archivedPath = await storage.archiveMemory(memory, {
2855
- at: new Date(updatedAt),
2856
- ...lifecycle
2857
- });
2858
- if (!archivedPath) {
2859
- throw new Error(`failed to archive memory disposition: ${memoryId}`);
2860
- }
2861
- return {
2862
- ok: true,
2863
- namespace: resolvedNamespace,
2864
- memoryId,
2865
- status: "archived",
2866
- previousStatus,
2867
- currentPath: archivedPath
2868
- };
2869
- }
2870
- const updated = await storage.writeMemoryFrontmatter(memory, {
2871
- status: request.status,
2872
- updated: updatedAt
2873
- }, lifecycle);
2874
- if (!updated) {
2875
- throw new Error(`failed to update memory disposition: ${memoryId}`);
2876
- }
2877
- return {
2878
- ok: true,
2879
- namespace: resolvedNamespace,
2880
- memoryId,
2881
- status: request.status,
2882
- previousStatus,
2883
- currentPath: memory.path
2884
- };
2885
- }
2886
- serializeMemory(memory) {
2887
- return {
2888
- id: memory.frontmatter.id,
2889
- path: memory.path,
2890
- category: memory.frontmatter.category,
2891
- status: memory.frontmatter.status,
2892
- created: memory.frontmatter.created,
2893
- updated: memory.frontmatter.updated,
2894
- content: memory.content,
2895
- frontmatter: memory.frontmatter
2896
- };
2897
- }
2898
- serializeMemorySummary(memory, baseDir, disclosure, rawExcerpts) {
2899
- return shapeMemorySummary(memory, baseDir, disclosure, rawExcerpts);
2900
- }
2901
- async observe(request) {
2902
- if (!request.sessionKey || typeof request.sessionKey !== "string" || request.sessionKey.trim().length === 0) {
2903
- throw new EngramAccessInputError("sessionKey is required and must be a non-empty string");
2904
- }
2905
- if (!Array.isArray(request.messages) || request.messages.length === 0) {
2906
- throw new EngramAccessInputError("messages is required and must be a non-empty array");
2907
- }
2908
- for (const msg of request.messages) {
2909
- if (!msg || typeof msg !== "object" || typeof msg.role !== "string" || typeof msg.content !== "string") {
2910
- throw new EngramAccessInputError("each message must have a string 'role' and 'content'");
2911
- }
2912
- if (msg.role !== "user" && msg.role !== "assistant") {
2913
- throw new EngramAccessInputError(`invalid message role: ${msg.role} (expected 'user' or 'assistant')`);
2914
- }
2915
- }
2916
- const hasExplicitNamespace = typeof request.namespace === "string" && request.namespace.trim().length > 0;
2917
- const principal = this.resolveWritePrincipal(
2918
- request.sessionKey,
2919
- request.authenticatedPrincipal
2920
- );
2921
- const namespace = this.resolveWritableNamespace(
2922
- request.namespace,
2923
- request.sessionKey,
2924
- request.authenticatedPrincipal
2925
- );
2926
- const shouldWriteObjectiveState = this.orchestrator.config.objectiveStateMemoryEnabled === true && this.orchestrator.config.objectiveStateSnapshotWritesEnabled === true;
2927
- const objectiveStateBaseNamespace = hasExplicitNamespace ? namespace : defaultNamespaceForPrincipal(principal, this.orchestrator.config);
2928
- if (shouldWriteObjectiveState && !hasExplicitNamespace && !canWriteNamespace(
2929
- principal,
2930
- objectiveStateBaseNamespace,
2931
- this.orchestrator.config
2932
- )) {
2933
- throw new EngramAccessInputError(
2934
- `namespace is not writable: ${objectiveStateBaseNamespace}`
2935
- );
2936
- }
2937
- await this.maybeAttachCodingContext(request.sessionKey, {
2938
- cwd: request.cwd,
2939
- projectTag: request.projectTag
2940
- });
2941
- const objectiveStateNamespace = hasExplicitNamespace ? namespace : this.orchestrator.applyCodingNamespaceOverlay(
2942
- request.sessionKey,
2943
- objectiveStateBaseNamespace
2944
- );
2945
- const lcmSessionKey = namespace !== this.orchestrator.config.defaultNamespace ? `${namespace}:${request.sessionKey}` : request.sessionKey;
2946
- if (shouldWriteObjectiveState) {
2947
- try {
2948
- const objectiveStateLocation = await this.objectiveStateStoreLocationForNamespace(
2949
- objectiveStateNamespace
2950
- );
2951
- await recordObjectiveStateSnapshotsFromObservedMessages({
2952
- memoryDir: objectiveStateLocation.memoryDir,
2953
- objectiveStateStoreDir: objectiveStateLocation.objectiveStateStoreDir,
2954
- objectiveStateMemoryEnabled: this.orchestrator.config.objectiveStateMemoryEnabled,
2955
- objectiveStateSnapshotWritesEnabled: this.orchestrator.config.objectiveStateSnapshotWritesEnabled,
2956
- sessionKey: request.sessionKey,
2957
- recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
2958
- messages: request.messages
2959
- });
2960
- } catch (err) {
2961
- log.error(`access-observe objective-state snapshot write failed: ${err}`);
2962
- }
2963
- }
2964
- let lcmArchived = false;
2965
- if (this.orchestrator.lcmEngine && this.orchestrator.lcmEngine.enabled) {
2966
- try {
2967
- this.orchestrator.lcmEngine.enqueueObserveMessages(lcmSessionKey, request.messages);
2968
- lcmArchived = true;
2969
- } catch (err) {
2970
- log.error(`access-observe LCM enqueue failed: ${err}`);
2971
- }
2972
- }
2973
- let extractionQueued = false;
2974
- if (request.skipExtraction !== true) {
2975
- const turns = request.messages.map((m) => ({
2976
- source: "openclaw",
2977
- sessionKey: lcmSessionKey,
2978
- role: m.role,
2979
- content: m.content,
2980
- parts: m.parts,
2981
- rawContent: m.rawContent,
2982
- sourceFormat: m.sourceFormat,
2983
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
2984
- }));
2985
- try {
2986
- const extractionPromise = this.orchestrator.ingestReplayBatch(turns, {
2987
- archiveLcm: false
2988
- });
2989
- extractionPromise.catch((err) => {
2990
- log.error(`access-observe background extraction failed: ${err}`);
2991
- });
2992
- extractionQueued = true;
2993
- } catch (err) {
2994
- log.error(`access-observe extraction enqueue failed: ${err}`);
2995
- }
2996
- }
2997
- log.info(
2998
- `access-observe namespace=${namespace} sessionKey=${request.sessionKey} messages=${request.messages.length} lcm=${lcmArchived} extraction=${extractionQueued}`
2999
- );
3000
- return {
3001
- accepted: request.messages.length,
3002
- sessionKey: request.sessionKey,
3003
- namespace,
3004
- lcmArchived,
3005
- extractionQueued
3006
- };
3007
- }
3008
- async lcmSearch(request) {
3009
- if (!request.query || typeof request.query !== "string" || request.query.trim().length === 0) {
3010
- throw new EngramAccessInputError("query is required and must be a non-empty string");
3011
- }
3012
- const principal = this.resolveWritePrincipal(request.sessionKey, request.authenticatedPrincipal);
3013
- const namespace = this.resolveReadableNamespace(request.namespace, principal);
3014
- if (!this.orchestrator.lcmEngine || !this.orchestrator.lcmEngine.enabled) {
3015
- return {
3016
- query: request.query,
3017
- namespace,
3018
- results: [],
3019
- count: 0,
3020
- lcmEnabled: false
3021
- };
3022
- }
3023
- const limit = Math.max(1, Math.min(request.limit ?? 10, 100));
3024
- const lcmSessionKey = request.sessionKey && namespace !== this.orchestrator.config.defaultNamespace ? `${namespace}:${request.sessionKey}` : request.sessionKey;
3025
- const rawResults = await this.orchestrator.lcmEngine.searchContextFull(
3026
- request.query,
3027
- limit,
3028
- lcmSessionKey
3029
- );
3030
- const results = rawResults.map((r) => ({
3031
- sessionId: r.session_id,
3032
- content: r.content,
3033
- turnIndex: r.turn_index
3034
- }));
3035
- return {
3036
- query: request.query,
3037
- namespace,
3038
- results,
3039
- count: results.length,
3040
- lcmEnabled: true
3041
- };
3042
- }
3043
- // ── Parity tools (match OpenClaw plugin feature set) ──────────────────
3044
- // ── Continuity / Identity ──────────────────────────────────────────────
3045
- async continuityAuditGenerate(request) {
3046
- if (!this.orchestrator.config.identityContinuityEnabled) {
3047
- return { enabled: false, reason: "Identity continuity is disabled. Enable `identityContinuityEnabled: true`." };
3048
- }
3049
- if (!this.orchestrator.config.continuityAuditEnabled) {
3050
- return { enabled: false, reason: "Continuity audits are disabled. Enable `continuityAuditEnabled: true`." };
3051
- }
3052
- if (!this.orchestrator.compounding) {
3053
- return { enabled: false, reason: "Compounding engine is disabled. Enable `compoundingEnabled: true`." };
3054
- }
3055
- const period = request.period === "monthly" ? "monthly" : "weekly";
3056
- const key = request.key?.trim() || void 0;
3057
- const audit = await this.orchestrator.compounding.synthesizeContinuityAudit({ period, key });
3058
- return { enabled: true, period: audit.period, key: audit.key, reportPath: audit.reportPath };
3059
- }
3060
- async continuityIncidentOpen(request) {
3061
- if (!this.orchestrator.config.identityContinuityEnabled) {
3062
- return { enabled: false, reason: "Identity continuity is disabled. Enable `identityContinuityEnabled: true`." };
3063
- }
3064
- if (!this.orchestrator.config.continuityIncidentLoggingEnabled) {
3065
- return { enabled: false, reason: "Continuity incident logging is disabled. Enable `continuityIncidentLoggingEnabled: true`." };
3066
- }
3067
- const symptom = request.symptom?.trim();
3068
- if (!symptom) throw new EngramAccessInputError("symptom is required");
3069
- const resolvedNs = this.resolveWritableNamespace(request.namespace, void 0, request.principal);
3070
- const storage = await this.orchestrator.getStorage(resolvedNs);
3071
- const created = await storage.appendContinuityIncident({
3072
- symptom,
3073
- triggerWindow: request.triggerWindow?.trim() || void 0,
3074
- suspectedCause: request.suspectedCause?.trim() || void 0
3075
- });
3076
- return { created: true, incident: created };
3077
- }
3078
- async continuityIncidentClose(request) {
3079
- if (!this.orchestrator.config.identityContinuityEnabled) {
3080
- return { enabled: false, reason: "Identity continuity is disabled." };
3081
- }
3082
- if (!this.orchestrator.config.continuityIncidentLoggingEnabled) {
3083
- return { enabled: false, reason: "Continuity incident logging is disabled." };
3084
- }
3085
- const id = request.id?.trim();
3086
- if (!id) throw new EngramAccessInputError("id is required");
3087
- const fixApplied = request.fixApplied?.trim();
3088
- if (!fixApplied) throw new EngramAccessInputError("fixApplied is required");
3089
- const verificationResult = request.verificationResult?.trim();
3090
- if (!verificationResult) throw new EngramAccessInputError("verificationResult is required");
3091
- const resolvedNs = this.resolveWritableNamespace(request.namespace, void 0, request.principal);
3092
- const storage = await this.orchestrator.getStorage(resolvedNs);
3093
- const closed = await storage.closeContinuityIncident(id, {
3094
- fixApplied,
3095
- verificationResult,
3096
- preventiveRule: request.preventiveRule?.trim() || void 0
3097
- });
3098
- if (!closed) return { closed: false, reason: `Incident not found: ${id}` };
3099
- return { closed: true, incident: closed };
3100
- }
3101
- async continuityIncidentList(request) {
3102
- if (!this.orchestrator.config.identityContinuityEnabled) {
3103
- return { enabled: false, reason: "Identity continuity is disabled." };
3104
- }
3105
- const state = request.state === "closed" || request.state === "all" ? request.state : "open";
3106
- const limit = Math.max(1, Math.min(200, Math.floor(request.limit ?? 25)));
3107
- const resolvedNs = this.resolveReadableNamespace(request.namespace, request.principal);
3108
- const storage = await this.orchestrator.getStorage(resolvedNs);
3109
- const incidents = await storage.readContinuityIncidents(limit, state);
3110
- return { state, incidents, count: incidents.length };
3111
- }
3112
- async continuityLoopAddOrUpdate(request) {
3113
- if (!this.orchestrator.config.identityContinuityEnabled) {
3114
- return { enabled: false, reason: "Identity continuity is disabled." };
3115
- }
3116
- const resolvedNs = this.resolveWritableNamespace(request.namespace, void 0, request.principal);
3117
- const storage = await this.orchestrator.getStorage(resolvedNs);
3118
- const loop = await storage.upsertIdentityImprovementLoop({
3119
- id: request.id?.trim() || "",
3120
- cadence: request.cadence,
3121
- purpose: request.purpose?.trim() || "",
3122
- status: request.status,
3123
- killCondition: request.killCondition?.trim() || "",
3124
- lastReviewed: request.lastReviewed?.trim() || void 0,
3125
- notes: request.notes?.trim() || void 0
3126
- });
3127
- return { saved: true, loop };
3128
- }
3129
- async continuityLoopReview(request) {
3130
- if (!this.orchestrator.config.identityContinuityEnabled) {
3131
- return { enabled: false, reason: "Identity continuity is disabled." };
3132
- }
3133
- const id = request.id?.trim();
3134
- if (!id) throw new EngramAccessInputError("id is required");
3135
- const resolvedNs = this.resolveWritableNamespace(request.namespace, void 0, request.principal);
3136
- const storage = await this.orchestrator.getStorage(resolvedNs);
3137
- const reviewed = await storage.reviewIdentityImprovementLoop(id, {
3138
- status: request.status,
3139
- notes: request.notes?.trim() || void 0,
3140
- reviewedAt: request.reviewedAt?.trim() || void 0
3141
- });
3142
- if (!reviewed) return { reviewed: false, reason: `Continuity loop not found: ${id}` };
3143
- return { reviewed: true, loop: reviewed };
3144
- }
3145
- async identityAnchorGet(request) {
3146
- if (!this.orchestrator.config.identityContinuityEnabled) {
3147
- return { enabled: false, reason: "Identity continuity is disabled." };
3148
- }
3149
- const resolvedNs = this.resolveReadableNamespace(request.namespace, request.principal);
3150
- const storage = await this.orchestrator.getStorage(resolvedNs);
3151
- const anchor = await storage.readIdentityAnchor();
3152
- if (!anchor) return { found: false, message: "No identity anchor found yet. Use identity_anchor_update to create one." };
3153
- return { found: true, anchor };
3154
- }
3155
- /**
3156
- * @deprecated since issue #679 PR 5/5 — the identity-anchor model is
3157
- * superseded by the peer registry. Use `peerSet({ id: "self", ... })` or
3158
- * `remnic peer set self` to update the self peer's identity kernel, and
3159
- * `remnic peer migrate` to seed `peers/self/identity.md` from existing
3160
- * legacy anchor data. This method continues to function for backward
3161
- * compatibility but will be removed in a future major version.
3162
- */
3163
- async identityAnchorUpdate(request) {
3164
- if (!this.orchestrator.config.identityContinuityEnabled) {
3165
- return { enabled: false, reason: "Identity continuity is disabled." };
3166
- }
3167
- const updates = {
3168
- "Identity Traits": request.identityTraits?.trim() || void 0,
3169
- "Communication Preferences": request.communicationPreferences?.trim() || void 0,
3170
- "Operating Principles": request.operatingPrinciples?.trim() || void 0,
3171
- "Continuity Notes": request.continuityNotes?.trim() || void 0
3172
- };
3173
- const hasUpdate = Object.values(updates).some((v) => typeof v === "string" && v.length > 0);
3174
- if (!hasUpdate) throw new EngramAccessInputError("At least one section field is required.");
3175
- const resolvedNs = this.resolveWritableNamespace(request.namespace, void 0, request.principal);
3176
- const storage = await this.orchestrator.getStorage(resolvedNs);
3177
- const existing = await storage.readIdentityAnchor();
3178
- const merged = this.mergeIdentityAnchorSections(existing, updates);
3179
- await storage.writeIdentityAnchor(merged);
3180
- const updatedSections = Object.entries(updates).filter(([, v]) => typeof v === "string" && v.length > 0).map(([name]) => name);
3181
- return { updated: true, sections: updatedSections, anchor: merged };
3182
- }
3183
- async memoryIdentity(request) {
3184
- const resolvedNs = this.resolveReadableNamespace(request.namespace, request.principal);
3185
- const storage = await this.orchestrator.getStorage(resolvedNs);
3186
- const identity = await storage.readIdentityReflections();
3187
- if (!identity) return { found: false, message: "No identity reflections found." };
3188
- return { found: true, identity };
3189
- }
3190
- // ── Work Layer ──────────────────────────────────────────────────────────
3191
- async workTask(request) {
3192
- const STATUSES = /* @__PURE__ */ new Set(["todo", "in_progress", "blocked", "done", "cancelled"]);
3193
- const PRIORITIES = /* @__PURE__ */ new Set(["low", "medium", "high"]);
3194
- const asStatus = (v) => v && STATUSES.has(v) ? v : void 0;
3195
- const asPriority = (v) => v && PRIORITIES.has(v) ? v : void 0;
3196
- const storage = new WorkStorage(this.orchestrator.config.memoryDir);
3197
- await storage.ensureDirectories();
3198
- const action = request.action;
3199
- if (action === "create") {
3200
- if (!request.title?.trim()) throw new EngramAccessInputError("title is required for create");
3201
- const task = await storage.createTask({
3202
- title: request.title,
3203
- description: request.description,
3204
- status: asStatus(request.status),
3205
- priority: asPriority(request.priority),
3206
- owner: request.owner?.trim() || void 0,
3207
- assignee: request.assignee?.trim() || void 0,
3208
- projectId: request.projectId?.trim() || void 0,
3209
- tags: request.tags,
3210
- dueAt: request.dueAt?.trim() || void 0
3211
- });
3212
- return { action, task };
3213
- }
3214
- if (action === "get") {
3215
- if (!request.id?.trim()) throw new EngramAccessInputError("id is required for get");
3216
- return { action, task: await storage.getTask(request.id) };
3217
- }
3218
- if (action === "list") {
3219
- const tasks = await storage.listTasks({
3220
- status: asStatus(request.status),
3221
- owner: request.owner?.trim() || void 0,
3222
- assignee: request.assignee?.trim() || void 0,
3223
- projectId: request.projectId?.trim() || void 0
3224
- });
3225
- return { action, count: tasks.length, tasks };
3226
- }
3227
- if (action === "update") {
3228
- if (!request.id?.trim()) throw new EngramAccessInputError("id is required for update");
3229
- const patch = {};
3230
- if (request.title !== void 0) patch.title = request.title;
3231
- if (request.description !== void 0) patch.description = request.description;
3232
- const st = asStatus(request.status);
3233
- if (st) patch.status = st;
3234
- const pr = asPriority(request.priority);
3235
- if (pr) patch.priority = pr;
3236
- if (request.owner !== void 0) patch.owner = request.owner || null;
3237
- if (request.assignee !== void 0) patch.assignee = request.assignee || null;
3238
- if (request.projectId !== void 0) patch.projectId = request.projectId || null;
3239
- if (request.tags) patch.tags = request.tags;
3240
- if (request.dueAt !== void 0) patch.dueAt = request.dueAt || null;
3241
- return { action, task: await storage.updateTask(request.id, patch) };
3242
- }
3243
- if (action === "transition") {
3244
- if (!request.id?.trim()) throw new EngramAccessInputError("id is required for transition");
3245
- const st = asStatus(request.status);
3246
- if (!st) throw new EngramAccessInputError("valid status is required for transition");
3247
- return { action, task: await storage.transitionTask(request.id, st) };
3248
- }
3249
- if (action === "delete") {
3250
- if (!request.id?.trim()) throw new EngramAccessInputError("id is required for delete");
3251
- return { action, deleted: await storage.deleteTask(request.id) };
3252
- }
3253
- throw new EngramAccessInputError(`Unsupported work_task action: ${action}`);
3254
- }
3255
- async workProject(request) {
3256
- const STATUSES = /* @__PURE__ */ new Set(["active", "on_hold", "completed", "archived"]);
3257
- const asStatus = (v) => v && STATUSES.has(v) ? v : void 0;
3258
- const storage = new WorkStorage(this.orchestrator.config.memoryDir);
3259
- await storage.ensureDirectories();
3260
- const action = request.action;
3261
- if (action === "create") {
3262
- if (!request.name?.trim()) throw new EngramAccessInputError("name is required for create");
3263
- const project = await storage.createProject({
3264
- name: request.name,
3265
- description: request.description,
3266
- status: asStatus(request.status),
3267
- owner: request.owner?.trim() || void 0,
3268
- tags: request.tags
3269
- });
3270
- return { action, project };
3271
- }
3272
- if (action === "get") {
3273
- if (!request.id?.trim()) throw new EngramAccessInputError("id is required for get");
3274
- return { action, project: await storage.getProject(request.id) };
3275
- }
3276
- if (action === "list") {
3277
- const projects = await storage.listProjects();
3278
- return { action, count: projects.length, projects };
3279
- }
3280
- if (action === "update") {
3281
- if (!request.id?.trim()) throw new EngramAccessInputError("id is required for update");
3282
- const patch = {};
3283
- if (request.name !== void 0) patch.name = request.name;
3284
- if (request.description !== void 0) patch.description = request.description;
3285
- const st = asStatus(request.status);
3286
- if (st) patch.status = st;
3287
- if (request.owner !== void 0) patch.owner = request.owner || null;
3288
- if (request.tags) patch.tags = request.tags;
3289
- return { action, project: await storage.updateProject(request.id, patch) };
3290
- }
3291
- if (action === "delete") {
3292
- if (!request.id?.trim()) throw new EngramAccessInputError("id is required for delete");
3293
- return { action, deleted: await storage.deleteProject(request.id) };
3294
- }
3295
- if (action === "link_task") {
3296
- if (!request.taskId?.trim() || !request.projectId?.trim()) {
3297
- throw new EngramAccessInputError("taskId and projectId are required for link_task");
3298
- }
3299
- return { action, linked: await storage.linkTaskToProject(request.taskId, request.projectId) };
3300
- }
3301
- throw new EngramAccessInputError(`Unsupported work_project action: ${action}`);
3302
- }
3303
- async workBoard(request) {
3304
- const memoryDir = this.orchestrator.config.memoryDir;
3305
- await new WorkStorage(memoryDir).ensureDirectories();
3306
- const action = request.action;
3307
- const projectId = request.projectId?.trim() || void 0;
3308
- if (action === "export_markdown") {
3309
- const markdown = await exportWorkBoardMarkdown({ memoryDir, projectId });
3310
- return { action, markdown: wrapWorkLayerContext(markdown, { linkToMemory: request.linkToMemory === true }) };
3311
- }
3312
- if (action === "export_snapshot") {
3313
- const snapshot = await exportWorkBoardSnapshot({ memoryDir, projectId });
3314
- return { action, snapshot };
3315
- }
3316
- if (action === "import_snapshot") {
3317
- if (!request.snapshotJson?.trim()) throw new EngramAccessInputError("snapshotJson is required for import_snapshot");
3318
- const snapshot = JSON.parse(request.snapshotJson);
3319
- const result = await importWorkBoardSnapshot({ memoryDir, snapshot, projectId });
3320
- return { action, result };
3321
- }
3322
- throw new EngramAccessInputError(`Unsupported work_board action: ${action}`);
3323
- }
3324
- // ── Shared Context / Compounding ────────────────────────────────────────
3325
- async sharedContextWriteOutput(request) {
3326
- if (!this.orchestrator.sharedContext) {
3327
- return { enabled: false, reason: "Shared context is disabled. Enable `sharedContextEnabled: true`." };
3328
- }
3329
- const fp = await this.orchestrator.sharedContext.writeAgentOutput({
3330
- agentId: request.agentId,
3331
- title: request.title,
3332
- content: request.content
3333
- });
3334
- return { written: true, path: fp };
3335
- }
3336
- async sharedFeedbackRecord(request) {
3337
- if (!this.orchestrator.sharedContext) {
3338
- return { enabled: false, reason: "Shared context is disabled. Enable `sharedContextEnabled: true`." };
3339
- }
3340
- await this.orchestrator.sharedContext.appendFeedback({
3341
- agent: request.agent,
3342
- decision: request.decision,
3343
- reason: request.reason,
3344
- date: request.date?.trim() || (/* @__PURE__ */ new Date()).toISOString(),
3345
- learning: request.learning,
3346
- outcome: request.outcome,
3347
- severity: request.severity,
3348
- confidence: request.confidence,
3349
- workflow: request.workflow,
3350
- tags: request.tags,
3351
- evidenceWindowStart: request.evidenceWindowStart,
3352
- evidenceWindowEnd: request.evidenceWindowEnd,
3353
- refs: request.refs
3354
- });
3355
- return { recorded: true };
3356
- }
3357
- async sharedPrioritiesAppend(request) {
3358
- if (!this.orchestrator.sharedContext) {
3359
- return { enabled: false, reason: "Shared context is disabled. Enable `sharedContextEnabled: true`." };
3360
- }
3361
- await this.orchestrator.sharedContext.appendPrioritiesInbox({
3362
- agentId: request.agentId,
3363
- text: request.text
3364
- });
3365
- return { appended: true };
3366
- }
3367
- async sharedContextCrossSignalsRun(request) {
3368
- if (!this.orchestrator.sharedContext) {
3369
- return { enabled: false, reason: "Shared context is disabled. Enable `sharedContextEnabled: true`." };
3370
- }
3371
- const result = await this.orchestrator.sharedContext.synthesizeCrossSignals({ date: request.date });
3372
- return {
3373
- crossSignalsMarkdownPath: result.crossSignalsMarkdownPath,
3374
- crossSignalsPath: result.crossSignalsPath,
3375
- sourceCount: result.report.sourceCount,
3376
- feedbackCount: result.report.feedbackCount,
3377
- overlapCount: result.overlapCount
3378
- };
3379
- }
3380
- async sharedContextCurateDaily(request) {
3381
- if (!this.orchestrator.sharedContext) {
3382
- return { enabled: false, reason: "Shared context is disabled. Enable `sharedContextEnabled: true`." };
3383
- }
3384
- const result = await this.orchestrator.sharedContext.curateDaily({ date: request.date });
3385
- return {
3386
- roundtablePath: result.roundtablePath,
3387
- crossSignalsMarkdownPath: result.crossSignalsMarkdownPath,
3388
- crossSignalsPath: result.crossSignalsPath,
3389
- overlapCount: result.overlapCount
3390
- };
3391
- }
3392
- async compoundingWeeklySynthesize(request) {
3393
- if (!this.orchestrator.compounding) {
3394
- return { enabled: false, reason: "Compounding engine is disabled. Enable `compoundingEnabled: true`." };
3395
- }
3396
- const res = await this.orchestrator.compounding.synthesizeWeekly({ weekId: request.weekId });
3397
- return {
3398
- weekId: res.weekId,
3399
- reportPath: res.reportPath,
3400
- reportJsonPath: res.reportJsonPath,
3401
- rubricsPath: res.rubricsPath,
3402
- rubricsIndexPath: res.rubricsIndexPath,
3403
- mistakesCount: res.mistakesCount,
3404
- promotionCandidateCount: res.promotionCandidateCount
3405
- };
3406
- }
3407
- async compoundingPromoteCandidate(request) {
3408
- if (!this.orchestrator.compounding) {
3409
- return { enabled: false, reason: "Compounding engine is disabled. Enable `compoundingEnabled: true`." };
3410
- }
3411
- return await this.orchestrator.compounding.promoteCandidate({
3412
- weekId: request.weekId,
3413
- candidateId: request.candidateId,
3414
- dryRun: request.dryRun
3415
- });
3416
- }
3417
- // ── Compression Guidelines ────────────────────────────────────────────
3418
- async compressionGuidelinesOptimize(request) {
3419
- if (!this.orchestrator.config.compressionGuidelineLearningEnabled) {
3420
- return { enabled: false, reason: "Compression guideline learning is disabled. Enable `compressionGuidelineLearningEnabled: true`." };
3421
- }
3422
- return await this.orchestrator.optimizeCompressionGuidelines({
3423
- dryRun: request.dryRun,
3424
- eventLimit: request.eventLimit
3425
- });
3426
- }
3427
- async compressionGuidelinesActivate(request) {
3428
- if (!this.orchestrator.config.compressionGuidelineLearningEnabled) {
3429
- return { enabled: false, reason: "Compression guideline learning is disabled." };
3430
- }
3431
- return await this.orchestrator.activateCompressionGuidelineDraft({
3432
- expectedContentHash: request.expectedContentHash,
3433
- expectedGuidelineVersion: request.expectedGuidelineVersion
3434
- });
3435
- }
3436
- /** Conservative identity anchor section merge (matches tools.ts mergeIdentityAnchor logic). */
3437
- mergeIdentityAnchorSections(existingRaw, updates) {
3438
- const TITLE = "# Identity Continuity Anchor";
3439
- const SECTION_ORDER = ["Identity Traits", "Communication Preferences", "Operating Principles", "Continuity Notes"];
3440
- const lines = (existingRaw ?? "").replace(/\r/g, "").split("\n");
3441
- const headerLines = [];
3442
- const sectionContent = /* @__PURE__ */ new Map();
3443
- const order = [];
3444
- let current = null;
3445
- for (const line of lines) {
3446
- const m = line.match(/^##\s+(.+?)\s*$/);
3447
- if (m) {
3448
- current = m[1].trim();
3449
- if (!sectionContent.has(current)) {
3450
- sectionContent.set(current, []);
3451
- order.push(current);
3452
- }
3453
- continue;
3454
- }
3455
- if (!current) {
3456
- headerLines.push(line);
3457
- } else {
3458
- sectionContent.get(current)?.push(line);
3459
- }
3460
- }
3461
- const sections = /* @__PURE__ */ new Map();
3462
- for (const [name, cLines] of sectionContent) sections.set(name, cLines.join("\n").trim());
3463
- const header = headerLines.join("\n").trim() || TITLE;
3464
- for (const sectionName of SECTION_ORDER) {
3465
- const prev = sections.get(sectionName)?.trim();
3466
- const next = updates[sectionName]?.trim();
3467
- const existing = prev === "- (empty)" ? "" : prev;
3468
- if (!next) {
3469
- if (!sections.has(sectionName)) sections.set(sectionName, "");
3470
- continue;
3471
- }
3472
- if (!existing) {
3473
- sections.set(sectionName, next);
3474
- continue;
3475
- }
3476
- if (existing.includes(next)) continue;
3477
- if (next.includes(existing)) {
3478
- sections.set(sectionName, next);
3479
- continue;
3480
- }
3481
- sections.set(sectionName, `${existing}
3482
-
3483
- ${next}`);
3484
- }
3485
- const finalOrder = [...SECTION_ORDER.filter((s) => sections.has(s)), ...order.filter((s) => !SECTION_ORDER.includes(s) && sections.has(s))];
3486
- const out = [header, ""];
3487
- for (const name of finalOrder) {
3488
- out.push(`## ${name}`, "");
3489
- const body = sections.get(name)?.trim();
3490
- if (body) out.push(body, "");
3491
- else out.push("");
3492
- }
3493
- return out.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
3494
- }
3495
- // ── Memory search & debug ─────────────────────────────────────────────
3496
- async memorySearch(request) {
3497
- const { query, namespace, maxResults, collection, principal } = request;
3498
- const resolvedNs = this.resolveReadableNamespace(namespace, principal);
3499
- const namespaceFilter = resolvedNs !== this.orchestrator.config.defaultNamespace ? resolvedNs : void 0;
3500
- const results = collection === "global" ? (await this.orchestrator.qmd.searchGlobal(query, maxResults)).filter(
3501
- (r) => namespaceFilter ? r.path.includes(`/namespaces/${namespaceFilter}/`) || !r.path.includes("/namespaces/") && namespaceFilter === this.orchestrator.config.defaultNamespace : true
3502
- ) : await this.orchestrator.searchAcrossNamespaces({
3503
- query,
3504
- namespaces: namespaceFilter ? [namespaceFilter] : void 0,
3505
- maxResults,
3506
- mode: "search"
3507
- });
3508
- return {
3509
- query,
3510
- results: results.map((r) => ({
3511
- path: r.path,
3512
- score: r.score,
3513
- snippet: (r.snippet ?? "").slice(0, 800)
3514
- })),
3515
- count: results.length
3516
- };
3517
- }
3518
- async memoryProfile(namespace, principal) {
3519
- const resolvedNs = this.resolveReadableNamespace(namespace, principal);
3520
- const storage = await this.orchestrator.getStorage(resolvedNs);
3521
- const profile = await storage.readProfile();
3522
- return {
3523
- profile: profile || "No profile built yet. The profile builds automatically through conversations."
3524
- };
3525
- }
3526
- async memoryEntitiesList(namespace, principal) {
3527
- const resolvedNs = this.resolveReadableNamespace(namespace, principal);
3528
- const storage = await this.orchestrator.getStorage(resolvedNs);
3529
- const entities = await storage.readEntities();
3530
- return { entities, count: entities.length };
3531
- }
3532
- async memoryQuestions(namespace, principal) {
3533
- const resolvedNs = this.resolveReadableNamespace(namespace, principal);
3534
- const storage = await this.orchestrator.getStorage(resolvedNs);
3535
- const questions = await storage.readQuestions();
3536
- return {
3537
- questions: questions.map((q) => ({ id: q.id, question: q.question, resolved: q.resolved })),
3538
- count: questions.length
3539
- };
3540
- }
3541
- async lastRecallSnapshot(sessionKey) {
3542
- const snapshot = sessionKey ? this.orchestrator.lastRecall.get(sessionKey) : this.orchestrator.lastRecall.getMostRecent();
3543
- return snapshot ?? { message: "No recall snapshot available" };
3544
- }
3545
- async intentDebug(namespace) {
3546
- const snapshot = await this.orchestrator.getLastIntentSnapshot(namespace);
3547
- return snapshot ?? { message: "No intent debug snapshot available" };
3548
- }
3549
- async qmdDebug(namespace) {
3550
- const snapshot = await this.orchestrator.getLastQmdRecallSnapshot(namespace);
3551
- return snapshot ?? { message: "No QMD debug snapshot available" };
3552
- }
3553
- async graphExplainLastRecall(namespace) {
3554
- const explanation = await this.orchestrator.explainLastGraphRecall({ namespace });
3555
- return { explanation };
3556
- }
3557
- /**
3558
- * Read-only graph snapshot for the admin pane (issue #691 PR 2/5).
3559
- *
3560
- * Reads adjacency from the JSONL edge store written by `GraphIndex` and
3561
- * resolves node metadata via the namespaced storage manager. Namespace
3562
- * resolution mirrors the read-side path used by `recall` /
3563
- * `procedureStats`, so multi-principal deployments can't leak edges from
3564
- * a peer namespace (CLAUDE.md rule 42).
3565
- */
3566
- async graphSnapshot(request, authenticatedPrincipal) {
3567
- const namespace = this.resolveReadableNamespace(
3568
- request.namespace,
3569
- authenticatedPrincipal
3570
- );
3571
- const storage = await this.orchestrator.getStorage(namespace);
3572
- const cfg = this.orchestrator.config;
3573
- let namespaceRootReal;
3574
- try {
3575
- namespaceRootReal = await nodeFs.realpath(storage.dir);
3576
- } catch {
3577
- namespaceRootReal = nodePath.resolve(storage.dir);
3578
- }
3579
- const namespaceRootWithSep = namespaceRootReal.endsWith(nodePath.sep) ? namespaceRootReal : namespaceRootReal + nodePath.sep;
3580
- const loadNode = async (relPath) => {
3581
- if (nodePath.isAbsolute(relPath)) {
3582
- log.warn(
3583
- `graphSnapshot: rejected absolute edge endpoint (len=${relPath.length}) outside namespace root`
3584
- );
3585
- return null;
3586
- }
3587
- const candidate = nodePath.resolve(namespaceRootReal, relPath);
3588
- if (candidate !== namespaceRootReal && !candidate.startsWith(namespaceRootWithSep)) {
3589
- log.warn(
3590
- `graphSnapshot: rejected traversing edge endpoint (len=${relPath.length}) outside namespace root`
3591
- );
3592
- return null;
3593
- }
3594
- let canonical;
3595
- try {
3596
- canonical = await nodeFs.realpath(candidate);
3597
- } catch {
3598
- canonical = candidate;
3599
- }
3600
- if (canonical !== namespaceRootReal && !canonical.startsWith(namespaceRootWithSep)) {
3601
- log.warn(
3602
- `graphSnapshot: rejected symlinked edge endpoint (len=${relPath.length}) that resolved outside namespace root`
3603
- );
3604
- return null;
3605
- }
3606
- const memory = await storage.readMemoryByPath(canonical);
3607
- if (!memory) return null;
3608
- const fm = memory.frontmatter;
3609
- return {
3610
- category: fm.category ?? "unknown",
3611
- label: fm.id ?? nodePath.basename(canonical, nodePath.extname(canonical)),
3612
- updated: fm.updated
3613
- };
3614
- };
3615
- return buildGraphSnapshot({
3616
- memoryDir: namespaceRootReal,
3617
- graphConfig: {
3618
- entityGraphEnabled: cfg.entityGraphEnabled === true,
3619
- timeGraphEnabled: cfg.timeGraphEnabled === true,
3620
- causalGraphEnabled: cfg.causalGraphEnabled === true
3621
- },
3622
- request: {
3623
- limit: request.limit,
3624
- since: request.since,
3625
- focusNodeId: request.focusNodeId,
3626
- categories: request.categories
3627
- },
3628
- loadNode
3629
- });
3630
- }
3631
- async memoryFeedback(request) {
3632
- if (!this.orchestrator.config.feedbackEnabled) {
3633
- return {
3634
- recorded: false,
3635
- enabled: false,
3636
- reason: "Feedback is disabled. Enable `feedbackEnabled: true` in the Engram config to store feedback."
3637
- };
3638
- }
3639
- await this.orchestrator.recordMemoryFeedback(
3640
- request.memoryId,
3641
- request.vote,
3642
- request.note
3643
- );
3644
- return { recorded: true };
3645
- }
3646
- /**
3647
- * Record a Memory Worth outcome observation (issue #560 PR 3).
3648
- *
3649
- * This is distinct from `memoryFeedback` — feedback is a human thumbs
3650
- * up/down on whether a recalled memory was relevant; outcome is an
3651
- * automated signal about whether the session that consumed the memory
3652
- * ultimately succeeded or failed. Outcomes feed the Laplace-smoothed
3653
- * worth score (`computeMemoryWorth`, PR 2) that PR 4 will use to
3654
- * downweight memories correlated with bad sessions.
3655
- *
3656
- * The underlying writer only touches fact-category memories. Corrections,
3657
- * procedures, and other kinds return `{ ok: false, reason:
3658
- * "ineligible_category" }` so a ledger drainer doesn't need to pre-filter.
3659
- */
3660
- async memoryOutcome(request) {
3661
- if (request.memoryId.includes("/") || request.memoryId.includes("\\")) {
3662
- throw new EngramAccessInputError(
3663
- "memoryId must not contain path separators"
3664
- );
3665
- }
3666
- const resolvedNs = this.resolveWritableNamespace(
3667
- request.namespace,
3668
- request.sessionKey,
3669
- request.principal
3670
- );
3671
- const storage = await this.orchestrator.getStorage(resolvedNs);
3672
- return recordMemoryOutcome(storage, {
3673
- memoryPath: `${request.memoryId}.md`,
3674
- outcome: request.outcome,
3675
- timestamp: request.timestamp
3676
- });
3677
- }
3678
- async memoryPromote(request) {
3679
- const resolvedNs = this.resolveWritableNamespace(request.namespace, request.sessionKey, request.principal);
3680
- const storage = await this.orchestrator.getStorage(resolvedNs);
3681
- await storage.updateMemoryFrontmatter(request.memoryId, {
3682
- lifecycleState: "active",
3683
- updated: (/* @__PURE__ */ new Date()).toISOString()
3684
- });
3685
- return { promoted: true, memoryId: request.memoryId };
3686
- }
3687
- async memoryActionApply(request) {
3688
- const actionTypes = /* @__PURE__ */ new Set([
3689
- "store_episode",
3690
- "store_note",
3691
- "update_note",
3692
- "create_artifact",
3693
- "summarize_node",
3694
- "discard",
3695
- "link_graph"
3696
- ]);
3697
- if (!actionTypes.has(request.action)) {
3698
- throw new EngramAccessInputError(
3699
- `memory_action_apply: invalid action ${JSON.stringify(request.action)}`
3700
- );
3701
- }
3702
- if (this.orchestrator.config.contextCompressionActionsEnabled !== true) {
3703
- throw new EngramAccessInputError(
3704
- "memory_action_apply is disabled; enable contextCompressionActionsEnabled to use this tool"
3705
- );
3706
- }
3707
- const outcome = request.outcome ?? "skipped";
3708
- if (outcome !== "applied" && outcome !== "skipped" && outcome !== "failed") {
3709
- throw new EngramAccessInputError(
3710
- `memory_action_apply: outcome must be "applied", "skipped", or "failed"; got ${JSON.stringify(outcome)}`
3711
- );
3712
- }
3713
- const resolvedNs = this.resolveWritableNamespace(
3714
- request.namespace,
3715
- request.sessionKey,
3716
- request.principal
3717
- );
3718
- const inputSummaryParts = [
3719
- request.content,
3720
- request.category ? `category=${request.category}` : void 0,
3721
- request.linkTargetId ? `linkTargetId=${request.linkTargetId}` : void 0,
3722
- request.linkType ? `linkType=${request.linkType}` : void 0,
3723
- typeof request.linkStrength === "number" ? `linkStrength=${request.linkStrength}` : void 0,
3724
- request.artifactType ? `artifactType=${request.artifactType}` : void 0,
3725
- typeof request.execute === "boolean" ? `execute=${request.execute}` : void 0
3726
- ].filter((part) => typeof part === "string" && part.length > 0);
3727
- const event = {
3728
- action: request.action,
3729
- outcome,
3730
- namespace: resolvedNs,
3731
- actor: "access.memory_action_apply",
3732
- subsystem: "access.memory_action_apply",
3733
- reason: request.reason,
3734
- memoryId: request.memoryId,
3735
- sourceSessionKey: request.sessionKey,
3736
- inputSummary: inputSummaryParts.length > 0 ? inputSummaryParts.join(" | ").slice(0, 500) : void 0,
3737
- dryRun: request.dryRun === true,
3738
- promptHash: typeof request.sourcePrompt === "string" && request.sourcePrompt.length > 0 ? createHash("sha256").update(request.sourcePrompt).digest("hex") : void 0
3739
- };
3740
- const preview = this.orchestrator.previewMemoryActionEvent(event);
3741
- if (request.dryRun === true) {
3742
- return { recorded: false, dryRun: true, event: preview };
3743
- }
3744
- const recorded = await this.orchestrator.appendMemoryActionEvent(event);
3745
- return { recorded, event: preview };
3746
- }
3747
- async contextCheckpoint(request) {
3748
- const resolvedNs = this.resolveWritableNamespace(request.namespace, request.sessionKey, request.principal);
3749
- const storage = await this.orchestrator.getStorage(resolvedNs);
3750
- const storageDir = storage.dir;
3751
- const { writeFile: writeFile2, mkdir: mkdir2 } = await import("fs/promises");
3752
- const { join: join2, resolve: resolve2 } = await import("path");
3753
- const safeKey = request.sessionKey.replace(/[^a-zA-Z0-9_-]/g, "_");
3754
- if (!safeKey) throw new EngramAccessInputError("sessionKey is required");
3755
- const checkpointDir = join2(storageDir, "checkpoints", safeKey);
3756
- const resolved = resolve2(checkpointDir);
3757
- if (!resolved.startsWith(resolve2(storageDir))) {
3758
- throw new EngramAccessInputError("Invalid sessionKey");
3759
- }
3760
- await mkdir2(checkpointDir, { recursive: true });
3761
- const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
3762
- const filePath = join2(checkpointDir, `checkpoint-${ts}.md`);
3763
- await writeFile2(filePath, request.context, "utf-8");
3764
- return { saved: true };
3765
- }
3766
- async lcmStatus() {
3767
- if (!this.orchestrator.lcmEngine || !this.orchestrator.lcmEngine.enabled) {
3768
- return {
3769
- enabled: false,
3770
- archiveAvailable: false
3771
- };
3772
- }
3773
- const stats = await this.orchestrator.lcmEngine.getStats();
3774
- return {
3775
- enabled: true,
3776
- archiveAvailable: true,
3777
- stats: {
3778
- totalTurns: stats.totalMessages
3779
- }
3780
- };
3781
- }
3782
- /**
3783
- * Record citation usage from an observed oai-mem-citation block.
3784
- * For each citation entry, extract the memory ID from the path and
3785
- * increment its access tracking via the orchestrator. Returns the
3786
- * count of submitted IDs and the count of IDs that matched real memories.
3787
- */
3788
- async recordCitationUsage(request) {
3789
- if (request.entries.length === 0) return { submitted: 0, matched: 0 };
3790
- const resolvedNamespace = this.resolveWritableNamespace(
3791
- request.namespace,
3792
- request.sessionId,
3793
- request.authenticatedPrincipal
3794
- );
3795
- const memoryIds = [];
3796
- for (const entry of request.entries) {
3797
- const basename2 = entry.path.split("/").pop() ?? entry.path;
3798
- const id = basename2.endsWith(".md") ? basename2.slice(0, -3) : basename2;
3799
- if (id.length > 0) {
3800
- memoryIds.push(id);
3801
- }
3802
- }
3803
- if (memoryIds.length === 0) return { submitted: 0, matched: 0 };
3804
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
3805
- const existingIds = await storage.filterExistingMemoryIds(memoryIds);
3806
- const matchedIds = memoryIds.filter((id) => existingIds.has(id));
3807
- if (matchedIds.length > 0) {
3808
- try {
3809
- this.orchestrator.trackMemoryAccess(matchedIds);
3810
- } catch {
3811
- log.debug("citation usage tracking: failed to record access for cited memories");
3812
- }
3813
- }
3814
- return { submitted: memoryIds.length, matched: matchedIds.length };
3815
- }
3816
- // ── Operator Console state (issue #688 PR 2/3) ────────────────────────────
3817
- /**
3818
- * Gather a point-in-time `ConsoleStateSnapshot` from the orchestrator.
3819
- *
3820
- * Principal-aware: `resolveReadableNamespace` enforces ACL before the
3821
- * snapshot is gathered, so callers cannot read a namespace they don't
3822
- * have read access to (CLAUDE.md rule 42). The resolved namespace's
3823
- * storage directory is forwarded as `config.memoryDir` so the ledger-
3824
- * tail reader in `gatherConsoleState` scans the correct namespace root
3825
- * rather than the global root. Read-only — never mutates orchestrator state.
3826
- */
3827
- async consoleState(namespace, principal) {
3828
- const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);
3829
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
3830
- const { gatherConsoleState } = await import("./state-NCHQ4TRG.js");
3831
- const orchestratorProxy = Object.create(this.orchestrator, {
3832
- config: {
3833
- value: { ...this.orchestrator.config, memoryDir: storage.dir },
3834
- enumerable: true,
3835
- configurable: true
3836
- }
3837
- });
3838
- return gatherConsoleState(orchestratorProxy);
3839
- }
3840
- // ── Peer Registry surfaces (issue #679 PR 4/5) ────────────────────────────
3841
- /**
3842
- * List all registered peers. Returns the array of `Peer` objects in
3843
- * deterministic alphabetical order (mirroring `listPeers` storage semantics).
3844
- */
3845
- async peerList() {
3846
- const { listPeers } = await import("./peers-HCVGHMAE.js");
3847
- const peers = await listPeers(this.orchestrator.config.memoryDir);
3848
- return { peers };
3849
- }
3850
- /**
3851
- * Get a single peer by id. Returns `{ found: false }` when the peer does
3852
- * not exist rather than throwing, matching the `memoryGet` / `entityGet`
3853
- * pattern used throughout the service.
3854
- */
3855
- async peerGet(peerId) {
3856
- const peers = await import("./peers-HCVGHMAE.js");
3857
- const validateId = peers.assertValidPeerId;
3858
- try {
3859
- validateId(peerId);
3860
- } catch (err) {
3861
- throw new EngramAccessInputError(err.message);
3862
- }
3863
- const peer = await peers.readPeer(this.orchestrator.config.memoryDir, peerId);
3864
- if (!peer) return { found: false };
3865
- return { found: true, peer };
3866
- }
3867
- /**
3868
- * Upsert a peer. Writes `peers/{id}/identity.md`. On first write the
3869
- * `createdAt` timestamp is set to now; on subsequent writes only
3870
- * `displayName` and `notes` are mutated (kind and createdAt are immutable
3871
- * once set, per the storage contract).
3872
- *
3873
- * Returns `{ created: true }` on first write, `{ created: false }` on update.
3874
- */
3875
- async peerSet(input) {
3876
- const peers = await import("./peers-HCVGHMAE.js");
3877
- const validateId = peers.assertValidPeerId;
3878
- const { id } = input;
3879
- try {
3880
- validateId(id);
3881
- } catch (err) {
3882
- throw new EngramAccessInputError(err.message);
3883
- }
3884
- const memoryDir = this.orchestrator.config.memoryDir;
3885
- const now = (/* @__PURE__ */ new Date()).toISOString();
3886
- const existing = await peers.readPeer(memoryDir, id);
3887
- const ALLOWED_KINDS = /* @__PURE__ */ new Set(["self", "human", "agent", "integration"]);
3888
- if (!existing) {
3889
- const kind = input.kind ?? "human";
3890
- if (!ALLOWED_KINDS.has(kind)) {
3891
- throw new EngramAccessInputError(
3892
- `peer kind must be one of ${[...ALLOWED_KINDS].join(", ")}`
3893
- );
3894
- }
3895
- const newPeer = {
3896
- id,
3897
- kind,
3898
- displayName: input.displayName ?? id,
3899
- createdAt: now,
3900
- updatedAt: now,
3901
- ...typeof input.notes === "string" ? { notes: input.notes } : {}
3902
- };
3903
- await peers.writePeer(memoryDir, newPeer);
3904
- return { ok: true, created: true, peer: newPeer };
3905
- }
3906
- const updated = {
3907
- id: existing.id,
3908
- kind: existing.kind,
3909
- createdAt: existing.createdAt,
3910
- updatedAt: now,
3911
- displayName: input.displayName !== void 0 ? input.displayName : existing.displayName,
3912
- ...input.notes !== void 0 ? { notes: input.notes } : existing.notes !== void 0 ? { notes: existing.notes } : {}
3913
- };
3914
- await peers.writePeer(memoryDir, updated);
3915
- return { ok: true, created: false, peer: updated };
3916
- }
3917
- /**
3918
- * Delete a peer by removing `peers/{id}/identity.md`. If the file does not
3919
- * exist the call is a no-op (idempotent). The peer directory itself
3920
- * (`peers/{id}/`) is intentionally left in place — profile and interaction
3921
- * log data are not destroyed.
3922
- */
3923
- async peerDelete(peerId) {
3924
- const peers = await import("./peers-HCVGHMAE.js");
3925
- const validateId = peers.assertValidPeerId;
3926
- try {
3927
- validateId(peerId);
3928
- } catch (err) {
3929
- throw new EngramAccessInputError(err.message);
3930
- }
3931
- const deleted = await peers.deletePeer(this.orchestrator.config.memoryDir, peerId);
3932
- return { ok: true, deleted };
3933
- }
3934
- /**
3935
- * Destructively purge the entire peer directory for a given peerId —
3936
- * `identity.md`, `profile.md`, `interactions.log.md`, and any other
3937
- * files in `peers/{id}/`. Requires `confirm: "yes"` to prevent
3938
- * accidental invocation.
3939
- *
3940
- * This is the DESTRUCTIVE counterpart to `peerDelete`, which only
3941
- * removes `identity.md`. All companion files are permanently removed.
3942
- *
3943
- * Returns `{ ok: true, purged: true }` when the directory existed and
3944
- * was removed; `{ ok: true, purged: false }` when the directory did
3945
- * not exist (idempotent no-op).
3946
- */
3947
- async peerForget(peerId, opts) {
3948
- const peers = await import("./peers-HCVGHMAE.js");
3949
- const validateId = peers.assertValidPeerId;
3950
- try {
3951
- validateId(peerId);
3952
- } catch (err) {
3953
- throw new EngramAccessInputError(err.message);
3954
- }
3955
- if (opts.confirm !== "yes") {
3956
- throw new EngramAccessInputError(
3957
- "peerForget requires confirm: 'yes' to prevent accidental data loss"
3958
- );
3959
- }
3960
- const result = await peers.forgetPeer(this.orchestrator.config.memoryDir, peerId, {
3961
- confirm: "yes"
3962
- });
3963
- return { ok: true, purged: result.purged };
3964
- }
3965
- /**
3966
- * Get the evolving cognitive profile for a peer. Returns `{ found: false }`
3967
- * when no profile file exists yet (profile is written by the async reasoner,
3968
- * PR 2/5). The peer identity itself need not exist for a profile to exist,
3969
- * but in practice the reasoner only writes profiles for registered peers.
3970
- */
3971
- async peerProfileGet(peerId) {
3972
- const peers = await import("./peers-HCVGHMAE.js");
3973
- const validateId = peers.assertValidPeerId;
3974
- try {
3975
- validateId(peerId);
3976
- } catch (err) {
3977
- throw new EngramAccessInputError(err.message);
3978
- }
3979
- const profile = await peers.readPeerProfile(this.orchestrator.config.memoryDir, peerId);
3980
- if (!profile) return { found: false };
3981
- return { found: true, profile };
3982
- }
3983
- // ── Contradiction Review (issue #520) ──────────────────────────────────────
3984
- get memoryDir() {
3985
- return this.orchestrator.config.memoryDir;
3986
- }
3987
- /**
3988
- * Resolve the storage directory for a given namespace. Used by the SSE
3989
- * graph-event handler to subscribe to the correct per-namespace bus rather
3990
- * than the global root (CLAUDE.md rule 42 — read/write paths must resolve
3991
- * through the same namespace layer).
3992
- *
3993
- * `principal` must be the transport-bound request principal (from
3994
- * `resolveRequestPrincipal`). When namespaces are enabled, an absent
3995
- * principal causes `resolveReadableNamespace` to throw an auth error,
3996
- * matching the behaviour of every other authenticated read path.
3997
- *
3998
- * Falls back to `this.memoryDir` when namespaces are disabled or the
3999
- * namespace is absent, matching the behaviour of every other read path.
4000
- */
4001
- async getMemoryDirForNamespace(namespace, principal) {
4002
- const resolved = this.resolveReadableNamespace(namespace, principal);
4003
- const storage = await this.orchestrator.getStorage(resolved);
4004
- return storage.dir;
4005
- }
4006
- get storageRef() {
4007
- return this.orchestrator.storage;
4008
- }
4009
- get configRef() {
4010
- return this.orchestrator.config;
4011
- }
4012
- get localLlmRef() {
4013
- return this.orchestrator.localLlm ?? null;
4014
- }
4015
- get fallbackLlmRef() {
4016
- return this.orchestrator.fastGatewayLlm ?? null;
4017
- }
4018
- get embeddingLookupFactoryRef() {
4019
- return (storage) => {
4020
- if (!this.orchestrator.config.embeddingFallbackEnabled) return void 0;
4021
- return async (content, limit) => {
4022
- try {
4023
- return await this.orchestrator.semanticDedupLookup(content, limit, storage);
4024
- } catch {
4025
- return [];
4026
- }
4027
- };
4028
- };
4029
- }
4030
- /**
4031
- * Import a capsule archive into the orchestrator's memory directory.
4032
- *
4033
- * Delegates directly to the standalone {@link importCapsuleFn} function.
4034
- * The `root` parameter defaults to the orchestrator's `memoryDir` when
4035
- * omitted, so callers that only have access to the service do not need to
4036
- * thread the config value through.
4037
- *
4038
- * `versioning` defaults to the orchestrator's page-versioning config so
4039
- * `mode: "overwrite"` automatically snapshots prior content without the
4040
- * caller having to construct the config object.
4041
- */
4042
- async capsuleImport(opts) {
4043
- const { namespace, principal, root: explicitRoot, memoryDir: explicitMemoryDir, ...importOptions } = opts;
4044
- const resolvedNamespace = this.resolveWritableNamespace(namespace, void 0, principal);
4045
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
4046
- const root = explicitRoot ?? storage.dir;
4047
- const memoryDir = explicitMemoryDir ?? this.orchestrator.config.memoryDir;
4048
- const versioning = importOptions.versioning ?? {
4049
- enabled: this.orchestrator.config.versioningEnabled,
4050
- maxVersionsPerPage: this.orchestrator.config.versioningMaxPerPage,
4051
- sidecarDir: this.orchestrator.config.versioningSidecarDir
4052
- };
4053
- await this.validateCapsuleImportArchivePath(importOptions.archivePath);
4054
- try {
4055
- return await importCapsule({ ...importOptions, root, memoryDir, versioning });
4056
- } catch (err) {
4057
- const message = err instanceof Error ? err.message : String(err);
4058
- if (this.isCapsuleImportArchiveInputError(err, message)) {
4059
- throw new EngramAccessInputError(`capsule import failed: ${message}`);
4060
- }
4061
- throw err;
4062
- }
4063
- }
4064
- async validateCapsuleImportArchivePath(archivePath) {
4065
- let archiveStat;
4066
- try {
4067
- archiveStat = await stat(archivePath);
4068
- } catch (err) {
4069
- if (!this.isCapsuleImportPathInputFsError(err)) throw err;
4070
- const message = err instanceof Error ? err.message : String(err);
4071
- throw new EngramAccessInputError(`capsule import failed: archive is not readable: ${message}`);
4072
- }
4073
- if (!archiveStat.isFile()) {
4074
- throw new EngramAccessInputError("capsule import failed: archivePath must point to a file");
4075
- }
4076
- try {
4077
- await nodeFs.access(archivePath, fsConstants.R_OK);
4078
- } catch (err) {
4079
- if (!this.isCapsuleImportPathInputFsError(err)) throw err;
4080
- const message = err instanceof Error ? err.message : String(err);
4081
- throw new EngramAccessInputError(`capsule import failed: archive is not readable: ${message}`);
4082
- }
4083
- }
4084
- isCapsuleImportPathInputFsError(err) {
4085
- const code = typeof err === "object" && err !== null && "code" in err ? err.code : void 0;
4086
- return code === "ENOENT" || code === "ENOTDIR" || code === "EACCES" || code === "EPERM" || code === "ELOOP";
4087
- }
4088
- isCapsuleImportArchiveInputError(err, message) {
4089
- if (err instanceof ZodError) return true;
4090
- const code = typeof err === "object" && err !== null && "code" in err ? err.code : void 0;
4091
- if (typeof code === "string" && code.startsWith("Z_")) return true;
4092
- return message.startsWith("importCapsule: archive") || message.startsWith("importCapsule: bundle") || message.startsWith("importCapsule: manifest") || message.startsWith("importCapsule: record") || /incorrect header check|invalid stored block lengths|not in gzip format|unexpected end of file/i.test(message);
4093
- }
4094
- /**
4095
- * Export a capsule archive from the orchestrator's memory directory.
4096
- *
4097
- * HTTP and future MCP surfaces use this rather than calling the transfer
4098
- * helper directly so namespace ACL checks stay consistent with the archive
4099
- * write side effect. The exporter still owns archive construction and
4100
- * validation.
4101
- */
4102
- async capsuleExport(opts) {
4103
- const { namespace, principal, root: explicitRoot, memoryDir: explicitMemoryDir, ...exportOptions } = opts;
4104
- const resolvedNamespace = this.resolveWritableNamespace(namespace, void 0, principal);
4105
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
4106
- const root = explicitRoot ?? storage.dir;
4107
- const memoryDir = explicitMemoryDir ?? this.orchestrator.config.memoryDir;
4108
- const pluginVersion = exportOptions.pluginVersion ?? await getPackageVersion();
4109
- return exportCapsule({
4110
- ...exportOptions,
4111
- pluginVersion,
4112
- root,
4113
- memoryDir: exportOptions.encrypt === true ? memoryDir : void 0
4114
- });
4115
- }
4116
- /**
4117
- * List capsule archives in the namespace-scoped capsule store.
4118
- *
4119
- * MCP uses this access-layer method instead of reading arbitrary paths so
4120
- * capsule discovery remains bound to the same namespace ACLs as export and
4121
- * import.
4122
- */
4123
- async capsuleList(options) {
4124
- const resolvedNamespace = this.resolveReadableNamespace(options?.namespace, options?.principal);
4125
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
4126
- const capsulesDir = defaultCapsulesDir(storage.dir);
4127
- let dirEntries;
4128
- try {
4129
- const capsulesDirStat = await nodeFs.lstat(capsulesDir);
4130
- if (capsulesDirStat.isSymbolicLink()) {
4131
- throw new EngramAccessInputError("capsule list failed: capsule store directory must not be a symlink");
4132
- }
4133
- if (!capsulesDirStat.isDirectory()) {
4134
- throw new EngramAccessInputError("capsule list failed: capsule store path must be a directory");
4135
- }
4136
- dirEntries = await nodeFs.readdir(capsulesDir, { withFileTypes: true });
4137
- } catch (err) {
4138
- const code = typeof err === "object" && err !== null && "code" in err ? err.code : void 0;
4139
- if (code === "ENOENT") {
4140
- return { namespace: resolvedNamespace, capsulesDir, capsules: [] };
4141
- }
4142
- throw err;
4143
- }
4144
- const archiveNames = dirEntries.filter(
4145
- (entry) => entry.isFile() && (entry.name.endsWith(".capsule.json.gz") || entry.name.endsWith(".capsule.json.gz.enc"))
4146
- ).map((entry) => entry.name).sort();
4147
- const capsules = [];
4148
- for (const archiveName of archiveNames) {
4149
- const archivePath = nodePath.join(capsulesDir, archiveName);
4150
- const id = archiveName.replace(/\.capsule\.json\.gz\.enc$/, "").replace(/\.capsule\.json\.gz$/, "");
4151
- const manifestPath = nodePath.join(capsulesDir, `${id}.manifest.json`);
4152
- let createdAt = null;
4153
- let pluginVersion = null;
4154
- let fileCount = null;
4155
- let description = null;
4156
- let manifestPathOrNull = manifestPath;
4157
- try {
4158
- const manifestStat = await nodeFs.lstat(manifestPath);
4159
- if (manifestStat.isSymbolicLink() || !manifestStat.isFile()) {
4160
- capsules.push({
4161
- id,
4162
- archivePath,
4163
- manifestPath: manifestPathOrNull,
4164
- createdAt,
4165
- pluginVersion,
4166
- fileCount,
4167
- description
4168
- });
4169
- continue;
4170
- }
4171
- const raw = await nodeFs.readFile(manifestPath, "utf-8");
4172
- const sidecar = JSON.parse(raw);
4173
- createdAt = typeof sidecar.createdAt === "string" ? sidecar.createdAt : null;
4174
- pluginVersion = typeof sidecar.pluginVersion === "string" ? sidecar.pluginVersion : null;
4175
- fileCount = Array.isArray(sidecar.files) ? sidecar.files.length : null;
4176
- const capsule = sidecar.capsule;
4177
- description = capsule && typeof capsule.description === "string" ? capsule.description : null;
4178
- } catch (err) {
4179
- const code = typeof err === "object" && err !== null && "code" in err ? err.code : void 0;
4180
- if (code === "ENOENT") {
4181
- manifestPathOrNull = null;
4182
- }
4183
- }
4184
- capsules.push({
4185
- id,
4186
- archivePath,
4187
- manifestPath: manifestPathOrNull,
4188
- createdAt,
4189
- pluginVersion,
4190
- fileCount,
4191
- description
4192
- });
4193
- }
4194
- return { namespace: resolvedNamespace, capsulesDir, capsules };
4195
- }
4196
- // ── Dreams pipeline telemetry surfaces (issue #678 PR 3+4) ──────────────
4197
- /**
4198
- * Return per-phase Dreams telemetry for the last N hours (default 24).
4199
- */
4200
- async dreamsStatus(options) {
4201
- const { getDreamsStatus, normalizeDreamsStatusWindowHours } = await import("./dreams-ledger-LR2NBAZE.js");
4202
- let windowHours;
4203
- try {
4204
- windowHours = normalizeDreamsStatusWindowHours(options?.windowHours);
4205
- } catch (error) {
4206
- throw new EngramAccessInputError(error instanceof Error ? error.message : String(error));
4207
- }
4208
- const resolvedNamespace = this.resolveReadableNamespace(options?.namespace, options?.principal);
4209
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
4210
- return getDreamsStatus(storage.dir, windowHours);
4211
- }
4212
- /**
4213
- * Manually invoke a single Dreams phase pass (PR 4/4).
4214
- *
4215
- * Deep-sleep delegates to memory governance (shadow → dry-run, apply → live).
4216
- * Light-sleep and REM scan the observation ledger and memory corpus
4217
- * respectively, returning the same telemetry shape as a scheduled run.
4218
- */
4219
- async dreamsRun(options) {
4220
- const { runDreamsPhase } = await import("./dreams-ledger-LR2NBAZE.js");
4221
- const validPhases = ["lightSleep", "rem", "deepSleep"];
4222
- if (!validPhases.includes(options.phase)) {
4223
- throw new EngramAccessInputError(
4224
- `Invalid phase: ${String(options.phase)}. Must be one of: ${validPhases.join(", ")}`
4225
- );
4226
- }
4227
- const deepSleep = this.orchestrator.config.dreamsPhases.deepSleep;
4228
- if (options.phase === "deepSleep" && deepSleep.enabled === false && deepSleep.enabledExplicitlySet === true) {
4229
- throw new EngramAccessInputError(
4230
- "memory governance is disabled by dreams.phases.deepSleep.enabled=false"
4231
- );
4232
- }
4233
- const dryRun = options.dryRun === true;
4234
- const resolvedNamespace = this.resolveWritableNamespace(
4235
- options.namespace,
4236
- void 0,
4237
- options.authenticatedPrincipal
4238
- );
4239
- const storage = await this.orchestrator.getStorage(resolvedNamespace);
4240
- const memoryDir = storage.dir;
4241
- const phaseRunner = dryRun || options.phase === "deepSleep" ? void 0 : async (_opts) => {
4242
- if (_opts.phase === "lightSleep") {
4243
- const result3 = await this.orchestrator.runLifecyclePolicyNow(storage);
4244
- return {
4245
- itemsProcessed: result3.memoriesAssessed,
4246
- notes: `scored ${result3.memoriesAssessed} memories`
4247
- };
4248
- }
4249
- const result2 = await this.orchestrator.runSemanticConsolidationNow({
4250
- dryRun: false,
4251
- storage
4252
- });
4253
- const itemsProcessed = result2.clusters.reduce(
4254
- (sum, cluster) => sum + cluster.memories.length,
4255
- 0
4256
- );
4257
- return {
4258
- itemsProcessed,
4259
- notes: `REM consolidation found ${result2.clustersFound} clusters`
4260
- };
4261
- };
4262
- const governanceRunner = options.phase === "deepSleep" ? async (_opts) => {
4263
- return this.orchestrator.runDeepSleepGovernanceNow({
4264
- storage,
4265
- dryRun: _opts.dryRun
4266
- });
4267
- } : void 0;
4268
- const result = await runDreamsPhase(
4269
- { memoryDir, phase: options.phase, dryRun },
4270
- governanceRunner,
4271
- phaseRunner
4272
- );
4273
- return {
4274
- phase: result.phase,
4275
- dryRun: result.dryRun,
4276
- durationMs: result.durationMs,
4277
- itemsProcessed: result.itemsProcessed,
4278
- notes: result.notes
4279
- };
4280
- }
4281
- };
4282
-
4283
- export {
4284
- WorkStorage,
4285
- computeProcedureStats,
4286
- formatProcedureStatsText,
4287
- EngramAccessInputError,
4288
- ENGRAM_ACCESS_WRITE_SCHEMA_VERSION,
4289
- shapeMemorySummary,
4290
- EngramAccessService
4291
- };
4292
- //# sourceMappingURL=chunk-WGK4VHGP.js.map