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